summaryrefslogtreecommitdiff
path: root/src/lib/evas/cserve2/evas_cs2_client.c
blob: 59ca5406c653eb34739e5d6f3153a39921db28a4 (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
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
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
#include "config.h"

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#include <Eina.h>

#include "evas_cs2.h"
#include "evas_cs2_private.h"
#include "evas_cs2_utils.h"

#ifdef EVAS_CSERVE2

#define TIMEOUT 1000
#define USE_SHARED_INDEX 1
#define SHARED_INDEX_ADD_TO_HASH 1
#define HKEY_LOAD_OPTS_STR_LEN 215
typedef void (*Op_Callback)(void *data, const void *msg, int size);

struct _File_Entry {
   unsigned int file_id;
   unsigned int server_file_id;
};

struct _Client_Request {
   Message_Type type;
   unsigned int rid;
   Op_Callback cb;
   void *data;
};

typedef struct _File_Entry File_Entry;
typedef struct _Client_Request Client_Request;

static int cserve2_init = 0;
static int socketfd = -1;

static unsigned int _rid_count = 0;
static unsigned int _file_id = 0;
static unsigned int _data_id = 0;

static Eina_List *_requests = NULL;

// Shared index table
static Index_Table _index;
static const char *_shared_string_get(int id);
static int _server_index_list_set(Msg_Base *data, int size);
static const File_Data *_shared_file_data_get_by_id(unsigned int id);
static const Shm_Object *_shared_index_item_get_by_id(Shared_Index *si, int elemsize, unsigned int id);
static const File_Data *_shared_image_entry_file_data_find(Image_Entry *ie);
static const Image_Data *_shared_image_entry_image_data_find(Image_Entry *ie);
static const Font_Data *_shared_font_entry_data_find(Font_Entry *fe);
static Eina_Bool _shared_index_remap_check(Shared_Index *si, int elemsize);

#ifndef UNIX_PATH_MAX
#define UNIX_PATH_MAX sizeof(((struct sockaddr_un *)NULL)->sun_path)
#endif

static inline Eina_Bool
_memory_zero_cmp(void *data, size_t len)
{
   const int *idata = data;
   const char *cdata;
   int remain;

   if (!data || !len) return EINA_TRUE;

   for (remain = len / sizeof(idata); remain > 0; --remain)
     if (*idata++ != 0) return EINA_FALSE;

   cdata = (const char*) idata;
   for (remain = ((const char*) data + len) - cdata; remain > 0; --remain)
     if (*cdata++ != 0) return EINA_FALSE;

   return EINA_TRUE;
}

static void
_socket_path_set(char *path)
{
   char *env;
   char buf[UNIX_PATH_MAX];

   env = getenv("EVAS_CSERVE2_SOCKET");
   if (env && env[0])
     {
        eina_strlcpy(path, env, UNIX_PATH_MAX);
        return;
     }

   snprintf(buf, sizeof(buf), "/tmp/.evas-cserve2-%x.socket", (int)getuid());
   /* FIXME: check we can actually create this socket */
   strcpy(path, buf);
#if 0   
   env = getenv("XDG_RUNTIME_DIR");
   if (!env || !env[0])
     {
        env = getenv("HOME");
        if (!env || !env[0])
          {
             env = getenv("TMPDIR");
             if (!env || !env[0])
               env = "/tmp";
          }
     }

   snprintf(buf, sizeof(buf), "%s/evas-cserve2-%x.socket", env, getuid());
   /* FIXME: check we can actually create this socket */
   strcpy(path, buf);
#endif   
}

static Eina_Bool
_server_connect(void)
{
   int s, len;
   struct sockaddr_un remote;
#ifdef HAVE_FCNTL
   int flags;
#endif

   if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
     {
        ERR("cserve2 socket creation failed with error [%d] %s", errno, strerror(errno));
        return EINA_FALSE;
     }

#ifdef HAVE_FCNTL
   flags = fcntl(s, F_GETFD);
   flags |= FD_CLOEXEC;
   fcntl(s, F_SETFD, flags);
#endif

   remote.sun_family = AF_UNIX;
   _socket_path_set(remote.sun_path);
   len = strlen(remote.sun_path) + sizeof(remote.sun_family);
   for (;;)
     {
        errno = 0;
        if (connect(s, (struct sockaddr *)&remote, len) != -1) break;
        if (errno == EACCES)
          {
             ERR("not authorized to connect to cserve2!");
             return EINA_FALSE;
          }
        ERR("cserve2 connect failed: [%d] %s. Retrying...", errno, strerror(errno));

        errno = 0;
        usleep(10000);
        if (errno == EINTR)
          {
             WRN("received interruption while trying to connect to cserve2!");
             return EINA_FALSE;
          }

        /* FIXME: Here we should identify the error, maybe signal the daemon manager
         * that we need cserve2 to [re]start or just quit and return false.
         * There probably should be a timeout of some sort also...
         * -- jpeg
         */
     }

#ifdef HAVE_FCNTL
   fcntl(s, F_SETFL, O_NONBLOCK);
#endif

   socketfd = s;

   DBG("connected to cserve2 server.");
   return EINA_TRUE;
}

static void
_server_disconnect(void)
{
   if (socketfd != -1)
     close(socketfd);
   socketfd = -1;
}

static void
_request_answer_add(Message_Type type, unsigned int rid, Op_Callback cb, void *data)
{
   Client_Request *cr = calloc(1, sizeof(*cr));

   cr->type = type;
   cr->rid = rid;
   cr->cb = cb;
   cr->data = data;

   _requests = eina_list_append(_requests, cr);
}

static Eina_Bool
_server_safe_send(int fd, const void *data, int size)
{
   int sent = 0;
   ssize_t ret;
   const char *msg = data;

   while (sent < size)
     {
        ret = send(fd, msg + sent, size - sent, MSG_NOSIGNAL);
        if (ret < 0)
          {
             if ((errno == EAGAIN) || (errno == EINTR))
               continue;
             DBG("send() failed with error [%d] %s", errno, strerror(errno));
             return EINA_FALSE;
          }
        sent += ret;
     }

   return EINA_TRUE;
}

static Eina_Bool
_server_send(const void *buf, int size, Op_Callback cb, void *data)
{
   const Msg_Base *msg;
   if (!_server_safe_send(socketfd, &size, sizeof(size)))
     {
        ERR("Couldn't send message size to server.");
        return EINA_FALSE;
     }
   if (!_server_safe_send(socketfd, buf, size))
     {
        ERR("Couldn't send message body to server.");
        return EINA_FALSE;
     }

   msg = buf;
   switch (msg->type)
     {
      case CSERVE2_OPEN:
      case CSERVE2_LOAD:
      case CSERVE2_PRELOAD:
      case CSERVE2_FONT_LOAD:
      case CSERVE2_FONT_GLYPHS_LOAD:
         _request_answer_add(msg->type, msg->rid, cb, data);
         break;
      default:
         break;
     }

   return EINA_TRUE;
}

static int sr_size = 0;
static int sr_got = 0;
static char *sr_buf = NULL;

static void *
_server_read(int *size)
{
   int n;
   void *ret;

   if (sr_size)
     goto get_data;

   n = recv(socketfd, &sr_size, sizeof(sr_size), 0);
   if (n < 0)
     return NULL;

   sr_buf = malloc(sr_size);

get_data:
   n = recv(socketfd, sr_buf + sr_got, sr_size - sr_got, 0);
   if (n < 0)
     return NULL;

   sr_got += n;
   if (sr_got < sr_size)
     return NULL;

   *size = sr_size;
   sr_size = 0;
   sr_got = 0;
   ret = sr_buf;
   sr_buf = NULL;

   return ret;
}

int
evas_cserve2_init(void)
{
   if (cserve2_init++)
     return cserve2_init;

   memset(&_index, 0, sizeof(_index));

   DBG("Connecting to cserve2.");
   if (!_server_connect())
     {
        cserve2_init = 0;
        return 0;
     }

   return cserve2_init;
}

int
evas_cserve2_shutdown(void)
{
   const char zeros[sizeof(Msg_Index_List)] = {0};
   Msg_Index_List *empty = (Msg_Index_List *) zeros;

   if ((--cserve2_init) > 0)
     return cserve2_init;

   DBG("Disconnecting from cserve2.");
   empty->base.type = CSERVE2_INDEX_LIST;
   _server_index_list_set((Msg_Base *) empty, sizeof(Msg_Index_List));
   _server_disconnect();

   return cserve2_init;
}

int
evas_cserve2_use_get(void)
{
   return cserve2_init;
}

static unsigned int
_next_rid(void)
{
   if (!_rid_count)
     _rid_count++;

   return _rid_count++;
}

static unsigned int
_server_dispatch(Eina_Bool *failed)
{
   int size;
   unsigned int rid;
   Eina_List *l, *l_next;
   Client_Request *cr;
   Msg_Base *msg;

   msg = _server_read(&size);
   if (!msg)
     {
        *failed = EINA_TRUE;
        return 0;
     }
   *failed = EINA_FALSE;

   // Special messages (no request)
   switch (msg->type)
     {
      case CSERVE2_INDEX_LIST:
        _server_index_list_set(msg, size);
        free(msg);
        return 0;
      default: break;
     }

   // Normal client to server requests
   EINA_LIST_FOREACH_SAFE(_requests, l, l_next, cr)
     {
        if (cr->rid != msg->rid) // dispatch this answer
          continue;

        _requests = eina_list_remove_list(_requests, l);
        if (cr->cb)
          cr->cb(cr->data, msg, size);
        free(cr);
     }

   rid = msg->rid;
   free(msg);

   return rid;
}

static Eina_Bool
_server_dispatch_until(unsigned int rid)
{
   Eina_Bool failed;
   fd_set rfds;
   unsigned int rrid;
   struct timeval tv;

   while (1)
     {
        rrid = _server_dispatch(&failed);
        if (rrid == rid) break;
#if TIMEOUT
        else if (failed)
          {
             int sel;

             //DBG("Waiting for request %d...", rid);
             FD_ZERO(&rfds);
             FD_SET(socketfd, &rfds);
             tv.tv_sec = TIMEOUT / 1000;
             tv.tv_usec = TIMEOUT * 1000;
             sel = select(socketfd + 1, &rfds, NULL, NULL, &tv);
             if (sel == -1)
               {
                  ERR("select() failed: [%d] %s", errno, strerror(errno));
                  /* FIXME: Depending on the error, we should probably try to reconnect to the server.
                   * Or even ask to [re]start the daemon.
                   * Or maybe just return EINA_FALSE after some timeout?
                   * -- jpeg
                   */
                  if (errno == EINTR)
                    {
                       DBG("giving up on request %d after interrupt", rid);
                       return EINA_FALSE;
                    }
               }
             else if (!sel)
               {
                  WRN("select() timed out. giving up on request %d", rid);
                  return EINA_FALSE;
               }
          }
#endif
     }
   return EINA_TRUE;
}

static void
_image_opened_cb(void *data, const void *msg_received, int size)
{
   const Msg_Base *answer = msg_received;
   const Msg_Opened *msg = msg_received;
   Image_Entry *ie = data;

   /* FIXME: Maybe we could have more asynchronous loading in the server side
    * and so we would have to check that open_rid is equal to answer->rid.
    * -- jpeg
    */
   //DBG("Received OPENED for RID: %d [open_rid: %d]", answer->rid, ie->open_rid);

   if (ie->server_id && !ie->open_rid)
     return;

   if (answer->rid != ie->open_rid)
     {
        WRN("Message rid (%d) differs from expected rid (open_rid: %d)", answer->rid, ie->open_rid);
        return;
     }
   ie->open_rid = 0;

   if (answer->type != CSERVE2_OPENED)
     {
        if (answer->type == CSERVE2_ERROR)
          {
             const Msg_Error *msg_error = msg_received;
             ERR("Couldn't open image: '%s':'%s'; error: %d",
                 ie->file, ie->key, msg_error->error);
          }
        else
          ERR("Invalid message type received: %d (%s)", answer->type, __FUNCTION__);
        free(ie->data1);
        ie->data1 = NULL;
        return;
     }
   else if (size < (int) sizeof(*msg))
     {
        ERR("Received message is too small");
        free(ie->data1);
        ie->data1 = NULL;
        return;
     }

   ie->w = msg->image.w;
   ie->h = msg->image.h;
   ie->flags.alpha = msg->image.alpha;
   ie->animated.loop_hint = msg->image.loop_hint;
   ie->animated.loop_count = msg->image.loop_count;
   ie->animated.frame_count = msg->image.frame_count;
}

static void
_loaded_handle(Image_Entry *ie, const Msg_Loaded *msg, int size)
{
   Data_Entry *dentry = ie->data2;
   RGBA_Image *im = (RGBA_Image *)ie;
   const char *shmpath;

   shmpath = ((const char *)msg) + sizeof(*msg);
   if ((size < (int) sizeof(*msg) + 1)
       || (strnlen(shmpath, size - sizeof(*msg)) >= (size - sizeof(*msg))))
     {
        DBG("invalid message size");
        goto fail;
     }

   // dentry->shm.path = strdup(shmpath);
   dentry->shm.mmap_offset = msg->shm.mmap_offset;
   dentry->shm.use_offset = msg->shm.use_offset;
   dentry->shm.mmap_size = msg->shm.mmap_size;
   dentry->shm.image_size = msg->shm.image_size;

   dentry->shm.f = eina_file_open(shmpath, EINA_TRUE);
   if (!dentry->shm.f)
     {
        DBG("could not open the shm file: %d %m", errno);
        goto fail;
     }

   dentry->shm.data = eina_file_map_new(dentry->shm.f, EINA_FILE_WILLNEED,
                                        dentry->shm.mmap_offset,
                                        dentry->shm.mmap_size);

   if (!dentry->shm.data)
     {
        DBG("could not mmap the shm file: %d %m", errno);
        eina_file_close(dentry->shm.f);
        goto fail;
     }

   im->image.data = evas_cserve2_image_data_get(ie);
   ie->flags.alpha_sparse = msg->alpha_sparse;
   ie->flags.loaded = EINA_TRUE;
   im->image.no_free = 1;
   return;

fail:
   ERR("Failed in %s", __FUNCTION__);
   free(ie->data2);
   ie->data2 = NULL;
}

static void
_image_loaded_cb(void *data, const void *msg_received, int size)
{
   const Msg_Base *answer = msg_received;
   const Msg_Loaded *msg = msg_received;
   Image_Entry *ie = data;

   //DBG("Received LOADED for RID: %d [load_rid: %d]", answer->rid, ie->load_rid);

   if (!ie->load_rid)
     return;

   if (answer->rid != ie->load_rid)
     {
        WRN("Message rid (%d) differs from expected rid (load_rid: %d)", answer->rid, ie->load_rid);
        return;
     }
   ie->load_rid = 0;

   if (!ie->data2)
     {
        ERR("No data2 for loaded file");
        return;
     }

   if (answer->type != CSERVE2_LOADED)
     {
        if (answer->type == CSERVE2_ERROR)
          {
             const Msg_Error *msg_error = msg_received;
             ERR("Couldn't load image: '%s':'%s'; error: %d",
                 ie->file, ie->key, msg_error->error);
          }
        else
          ERR("Invalid message type received: %d (%s)", answer->type, __FUNCTION__);
        free(ie->data2);
        ie->data2 = NULL;
        return;
     }

   _loaded_handle(ie, msg, size);
}

static void
_image_preloaded_cb(void *data, const void *msg_received, int size)
{
   const Msg_Base *answer = msg_received;
   Image_Entry *ie = data;
   Data_Entry *dentry = ie->data2;

   //DBG("Received PRELOADED for RID: %d [preload_rid: %d]", answer->rid, ie->preload_rid);
   if (answer->rid != ie->preload_rid)
     WRN("Message rid (%d) differs from expected rid (preload_rid: %d)", answer->rid, ie->preload_rid);
   ie->preload_rid = 0;

   if (!ie->data2)
     {
        ERR("No data2 for preloaded file");
        return;
     }

   if (answer->type != CSERVE2_PRELOAD &&
       answer->type != CSERVE2_LOADED)
     {
        if (answer->type == CSERVE2_ERROR)
          {
             const Msg_Error *msg_error = msg_received;
             ERR("Couldn't preload image: '%s':'%s'; error: %d",
                 ie->file, ie->key, msg_error->error);
          }
        else
          ERR("Invalid message type received: %d (%s)", answer->type, __FUNCTION__);
        if (dentry->preloaded_cb)
          dentry->preloaded_cb(data, EINA_FALSE);
        dentry->preloaded_cb = NULL;
        return;
     }

   _loaded_handle(ie, msg_received, size);

   dentry = ie->data2;
   if (dentry && (dentry->preloaded_cb))
     {
        dentry->preloaded_cb(data, EINA_TRUE);
        dentry->preloaded_cb = NULL;
     }
}

static int
_build_absolute_path(const char *path, char buf[], int size)
{
   char *p;
   int len;

   if (!path)
     return 0;

   p = buf;

   if (path[0] == '/')
     len = eina_strlcpy(p, path, size);
   else if (path[0] == '~')
     {
        const char *home = getenv("HOME");
        if (!home)
          return 0;
        len = eina_strlcpy(p, home, size);
        size -= len + 1;
        p += len;
        p[0] = '/';
        p++;
        len++;
        len += eina_strlcpy(p, path + 2, size);
     }
   else
     {
        if (!getcwd(p, size))
          return 0;
        len = strlen(p);
        size -= len + 1;
        p += len;
        p[0] = '/';
        p++;
        len++;
        len += eina_strlcpy(p, path, size);
     }

   return len;
}

static unsigned int
_image_open_server_send(Image_Entry *ie, const char *file, const char *key,
                        Evas_Image_Load_Opts *opts)
{
   int flen, klen;
   int size;
   char *buf;
   char filebuf[PATH_MAX];
   Msg_Open msg_open;
   File_Entry *fentry;
   Data_Entry *dentry;

   if (cserve2_init == 0)
     {
        ERR("Server not initialized.");
        return 0;
     }

   ie->data1 = NULL;
   ie->data2 = NULL;

   flen = _build_absolute_path(file, filebuf, sizeof(filebuf));
   if (!flen)
     {
        ERR("Could not find absolute path for %s", file);
        return 0;
     }
   flen++;

   if (!key) key = "";

   fentry = calloc(1, sizeof(*fentry));
   if (!fentry)
     return 0;

   dentry = calloc(1, sizeof(*dentry));
   if (!dentry)
     {
        free(fentry);
        return 0;
     }

   memset(&msg_open, 0, sizeof(msg_open));

   fentry->file_id = ++_file_id;
   klen = strlen(key) + 1;

   msg_open.base.rid = _next_rid();
   msg_open.base.type = CSERVE2_OPEN;
   msg_open.file_id = fentry->file_id;
   msg_open.path_offset = 0;
   msg_open.key_offset = flen;
   msg_open.has_load_opts = (opts != NULL);
   msg_open.image_id = ++_data_id;

   size = sizeof(msg_open) + flen + klen;
   if (opts)
     size += sizeof(*opts);
   buf = malloc(size);
   if (!buf)
     {
        free(fentry);
        free(dentry);
        return 0;
     }
   memcpy(buf, &msg_open, sizeof(msg_open));
   memcpy(buf + sizeof(msg_open), filebuf, flen);
   memcpy(buf + sizeof(msg_open) + flen, key, klen);
   if (opts)
     memcpy(buf + sizeof(msg_open) + flen + klen, opts, sizeof(*opts));

   if (!_server_send(buf, size, _image_opened_cb, ie))
     {
        ERR("Couldn't send message to server.");
        free(buf);
        free(fentry);
        free(dentry);
        return 0;
     }

   free(buf);
   ie->data1 = fentry;

   dentry->image_id = msg_open.image_id;
   ie->data2 = dentry;

   return msg_open.base.rid;
}

unsigned int
_image_load_server_send(Image_Entry *ie)
{
   Data_Entry *dentry;
   Msg_Load msg;

   if (cserve2_init == 0)
     return 0;

   if (!ie->data1)
     {
        ERR("No data1 for opened file.");
        return 0;
     }

   dentry = ie->data2;
   if (!dentry)
     {
        ERR("No data2 for opened file.");
        return 0;
     }

   memset(&msg, 0, sizeof(msg));

   msg.base.rid = _next_rid();
   msg.base.type = CSERVE2_LOAD;
   msg.image_id = dentry->image_id;

   if (!_server_send(&msg, sizeof(msg), _image_loaded_cb, ie))
     return 0;

   return msg.base.rid;
}

unsigned int
_image_preload_server_send(Image_Entry *ie, void (*preloaded_cb)(void *im, Eina_Bool success))
{
   Data_Entry *dentry;
   Msg_Preload msg;

   if (cserve2_init == 0)
     return 0;

   dentry = ie->data2;
   if (!dentry)
     {
        ERR("No data2 for opened file.");
        return 0;
     }
   dentry->preloaded_cb = preloaded_cb;

   memset(&msg, 0, sizeof(msg));

   msg.base.rid = _next_rid();
   msg.base.type = CSERVE2_PRELOAD;
   msg.image_id = dentry->image_id;

   if (!_server_send(&msg, sizeof(msg), _image_preloaded_cb, ie))
     return 0;

   return msg.base.rid;
}

unsigned int
_image_close_server_send(Image_Entry *ie)
{
   Msg_Close msg;
   File_Entry *fentry;

   if (cserve2_init == 0)
     return 0;

   if (!ie->data1)
     return 0;

   fentry = ie->data1;

   if (ie->data2)
     {
        Data_Entry *dentry = ie->data2;
        if (dentry->shm.data)
          eina_file_map_free(dentry->shm.f, dentry->shm.data);
        if (dentry->shm.f)
          eina_file_close(dentry->shm.f);
        free(ie->data2);
        ie->data2 = NULL;
     }

   memset(&msg, 0, sizeof(msg));
   msg.base.rid = _next_rid();
   msg.base.type = CSERVE2_CLOSE;
   msg.file_id = fentry->file_id;

   free(fentry);
   ie->data1 = NULL;

   if (!_server_send(&msg, sizeof(msg), NULL, NULL))
     return 0;

   return msg.base.rid;
}

unsigned int
_image_unload_server_send(Image_Entry *ie)
{
   Msg_Unload msg;
   Data_Entry *dentry;

   if (cserve2_init == 0)
     return 0;

   if (!ie->data2)
     return 0;

   dentry = ie->data2;

   if (dentry->shm.data)
     eina_file_map_free(dentry->shm.f, dentry->shm.data);
   if (dentry->shm.f)
     eina_file_close(dentry->shm.f);

   // if (dentry->shm.path)
   //   free(dentry->shm.path);
   memset(&msg, 0, sizeof(msg));
   msg.base.rid = _next_rid();
   msg.base.type = CSERVE2_UNLOAD;
   msg.image_id = dentry->image_id;

   free(dentry);
   ie->data2 = NULL;

   if (!_server_send(&msg, sizeof(msg), NULL, NULL))
     return 0;

   return msg.base.rid;
}

Eina_Bool
evas_cserve2_image_load(Image_Entry *ie)
{
   unsigned int rid;
   const char *file, *key;
   Evas_Image_Load_Opts *opts = NULL;

   if (!ie)
     return EINA_FALSE;

   file = ie->file;
   key = ie->key;
   if (!_memory_zero_cmp(&ie->load_opts, sizeof(ie->load_opts)))
     opts = &ie->load_opts;
   rid = _image_open_server_send(ie, file, key, opts);
   if (!rid)
     return EINA_FALSE;

   ie->open_rid = rid;

   if (ie->data1)
     return EINA_TRUE;
   else
     return EINA_FALSE;
}

int
evas_cserve2_image_load_wait(Image_Entry *ie)
{
   const File_Data *fd;
   Eina_Bool failed;
   unsigned int rrid, rid;

   if (!ie)
     return CSERVE2_GENERIC;

   if (!ie->open_rid)
     return CSERVE2_NONE;

   rid = ie->open_rid;
   rrid = _server_dispatch(&failed);
   if (rid == rrid)
     return CSERVE2_NONE;

#if USE_SHARED_INDEX
   fd = _shared_image_entry_file_data_find(ie);
   if (fd && fd->valid)
     {
        DBG("Bypassing socket wait (open_rid %d)", ie->open_rid);
        ie->w = fd->w;
        ie->h = fd->h;
        ie->flags.alpha = fd->alpha;
        ie->animated.loop_hint = fd->loop_hint;
        ie->animated.loop_count = fd->loop_count;
        ie->animated.frame_count = fd->frame_count;
        ie->server_id = fd->id;
        ie->open_rid = 0;
        return CSERVE2_NONE;
     }
#endif

   if (ie->open_rid)
     {
        if (!_server_dispatch_until(ie->open_rid))
          return CSERVE2_GENERIC;
        if (!ie->data1)
          return CSERVE2_GENERIC;
     }

   return CSERVE2_NONE;
}

Eina_Bool
evas_cserve2_image_data_load(Image_Entry *ie)
{
   unsigned int rid;

   if (!ie)
     return EINA_FALSE;

   rid = _image_load_server_send(ie);
   if (!rid)
     return EINA_FALSE;

   ie->load_rid = rid;

   if (ie->data2)
     return EINA_TRUE;
   else
     return EINA_FALSE;
}

int
evas_cserve2_image_load_data_wait(Image_Entry *ie)
{
   const Image_Data *idata;

   if (!ie)
     return CSERVE2_GENERIC;

#if USE_SHARED_INDEX
   idata = _shared_image_entry_image_data_find(ie);
   if (idata && idata->valid)
     {
        // FIXME: Ugly copy & paste from _loaded_handle
        Data_Entry *dentry = ie->data2;
        RGBA_Image *im = (RGBA_Image *)ie;
        const char *shmpath;

        shmpath = _shared_string_get(idata->shm_id);
        if (!shmpath) goto load_wait;
        DBG("Bypassing image load socket wait. Image found: %d in %s",
            idata->id, shmpath);

        dentry->shm.mmap_offset = 0;
        dentry->shm.use_offset = 0;
        dentry->shm.f = eina_file_open(shmpath, EINA_TRUE);
        dentry->shm.mmap_size = eina_file_size_get(dentry->shm.f);
        dentry->shm.image_size = dentry->shm.mmap_size;

        dentry->shm.data = eina_file_map_new(dentry->shm.f, EINA_FILE_WILLNEED,
                                             dentry->shm.mmap_offset,
                                             dentry->shm.mmap_size);
        if (!dentry->shm.data)
          {
             DBG("could not mmap the shm file: %d %m", errno);
             eina_file_close(dentry->shm.f);
             dentry->shm.f = NULL;
             goto load_wait;
          }

        im->image.data = dentry->shm.data;
        ie->flags.alpha_sparse = idata->alpha_sparse;
        ie->flags.loaded = EINA_TRUE;
        im->image.no_free = 1;

        ie->load_rid = 0;
        return CSERVE2_NONE;
     }
#endif

load_wait:
   if (ie->load_rid)
     {
        if (!_server_dispatch_until(ie->load_rid))
          return CSERVE2_GENERIC;
        if (!ie->data2)
          return CSERVE2_GENERIC;
     }

   return CSERVE2_NONE;
}

Eina_Bool
evas_cserve2_image_preload(Image_Entry *ie, void (*preloaded_cb)(void *im, Eina_Bool success))
{
   unsigned int rid;

   if (!ie || !ie->data1)
     return EINA_FALSE;

   rid = _image_preload_server_send(ie, preloaded_cb);
   if (!rid)
     return EINA_FALSE;

   ie->preload_rid = rid;

   return EINA_FALSE;
}

void
evas_cserve2_image_free(Image_Entry *ie)
{
   if (!ie || !ie->data1)
     return;

   if (!_image_close_server_send(ie))
     WRN("Couldn't send close message to cserve2.");
}

void
evas_cserve2_image_unload(Image_Entry *ie)
{
   if (!ie || !ie->data2)
     return;

   if (!_image_unload_server_send(ie))
     WRN("Couldn't send unload message to cserve2.");
}

void
evas_cserve2_dispatch(void)
{
   _server_dispatch_until(0);
}

typedef struct _Glyph_Map Glyph_Map;
typedef struct _CS_Glyph_Out CS_Glyph_Out;

struct _Font_Entry
{
   const char *source;
   const char *name;
   unsigned int size;
   unsigned int dpi;
   Font_Rend_Flags wanted_rend;

   char *hkey;
   int font_data_id;

   unsigned int rid; // open

   Glyph_Map *map;
   Fash_Glyph2 *fash[3]; // one per hinting value

   Eina_Clist glyphs_queue;
   int glyphs_queue_count;
   Eina_Clist glyphs_used;
   int glyphs_used_count;

   Eina_Bool failed : 1;
};

struct _Glyph_Map
{
   Font_Entry *fe;
   Shared_Index index;
   Shared_Buffer mempool;
   Eina_Clist glyphs;
};

struct _CS_Glyph_Out
{
   RGBA_Font_Glyph_Out base;
   Eina_Clist map_entry;
   Eina_Clist used_list;
   unsigned int idx;
   unsigned int rid;
   Glyph_Map *map;
   unsigned int offset;
   unsigned int size;
   Eina_Bool used;
};

static void
_glyphs_map_free(Glyph_Map *map)
{
   if (!map) return;
   eina_file_map_free(map->mempool.f, map->mempool.data);
   eina_file_close(map->mempool.f);
   eina_file_map_free(map->index.f, map->index.data);
   eina_file_close(map->index.f);
   eina_hash_free(map->index.entries_by_hkey);
   map->fe->map = NULL;
   free(map);
}

static void
_glyph_out_free(void *gl)
{
   CS_Glyph_Out *glout = gl;

   if (glout->map)
     {
        eina_clist_remove(&glout->map_entry);
        if (eina_clist_empty(&glout->map->glyphs))
          _glyphs_map_free(glout->map);
     }

   free(glout);
}

static void
_font_entry_free(Font_Entry *fe)
{
   int i;

   for (i = 0; i < 3; i++)
     if (fe->fash[i])
       fash_gl_free(fe->fash[i]);

   eina_hash_del_by_key(_index.fonts.entries_by_hkey, fe->hkey);
   free(fe->hkey);
   eina_stringshare_del(fe->source);
   eina_stringshare_del(fe->name);
   _glyphs_map_free(fe->map);
   free(fe);
}

static void
_font_loaded_cb(void *data, const void *msg, int size)
{
   const Msg_Base *m = msg;
   Font_Entry *fe = data;

   fe->rid = 0;

   if ((size < (int) sizeof(*m))
       || (m->type == CSERVE2_ERROR))
     fe->failed = EINA_TRUE;
}

static unsigned int
_font_load_server_send(Font_Entry *fe, Message_Type type)
{
   Msg_Font_Load *msg;
   int source_len, path_len, size;
   char *buf;
   unsigned int ret = 0;
   Op_Callback cb = NULL;

   if (!cserve2_init)
     return 0;

   source_len = fe->source ? eina_stringshare_strlen(fe->source) + 1 : 0;
   path_len = eina_stringshare_strlen(fe->name) + 1;

   size = sizeof(*msg) + path_len + source_len;
   msg = calloc(1, size);

   msg->base.rid = _next_rid();
   msg->base.type = type;

   msg->sourcelen = source_len;
   msg->pathlen = path_len;
   msg->rend_flags = fe->wanted_rend;
   msg->size = fe->size;
   msg->dpi = fe->dpi;

   buf = ((char *)msg) + sizeof(*msg);
   if (source_len > 0) memcpy(buf, fe->source, source_len);
   buf += source_len;
   memcpy(buf, fe->name, path_len);

   if (type == CSERVE2_FONT_LOAD)
     cb = _font_loaded_cb;

   if (_server_send(msg, size, cb, fe))
     ret = msg->base.rid;

   free(msg);

   return ret;
}

Font_Entry *
evas_cserve2_font_load(const char *source, const char *name, int size, int dpi,
                       Font_Rend_Flags wanted_rend)
{
   Font_Entry *fe;

   fe = calloc(1, sizeof(Font_Entry));
   if (!fe) return NULL;

   fe->source = source ? eina_stringshare_add(source) : NULL;
   fe->name = eina_stringshare_add(name);
   fe->size = size;
   fe->dpi = dpi;
   fe->wanted_rend = wanted_rend;

   if (!(fe->rid = _font_load_server_send(fe, CSERVE2_FONT_LOAD)))
     {
        eina_stringshare_del(fe->source);
        eina_stringshare_del(fe->name);
        free(fe);
        return NULL;
     }

   eina_clist_init(&fe->glyphs_queue);
   eina_clist_init(&fe->glyphs_used);

   if (asprintf(&fe->hkey, "%s:%s/%u:%u:%u", fe->name, fe->source,
                fe->size, fe->dpi, (unsigned int) fe->wanted_rend) == -1)
     fe->hkey = NULL;

   return fe;
}

int
evas_cserve2_font_load_wait(Font_Entry *fe)
{
#if USE_SHARED_INDEX
   const Font_Data *fd;
   Eina_Bool failed;
   unsigned int rid, rrid;

   rid = fe->rid;
   rrid = _server_dispatch(&failed);
   if ((rid == rrid) && !fe->failed)
     return CSERVE2_NONE;

   fd = _shared_font_entry_data_find(fe);
   if (fd)
     {
        DBG("Bypassing socket wait (rid %d)", fe->rid);
        fe->failed = EINA_FALSE;
        fe->rid = 0;
        return CSERVE2_NONE;
     }
#endif

   if (!_server_dispatch_until(fe->rid))
     return CSERVE2_GENERIC;

   if (fe->failed)
     return CSERVE2_GENERIC;

   return CSERVE2_NONE;
}

void
evas_cserve2_font_free(Font_Entry *fe)
{
   int ret;

   if (!fe) return;

   ret = evas_cserve2_font_load_wait(fe);
   if (ret != CSERVE2_NONE)
     {
        ERR("Failed to wait loading font '%s'.", fe->name);
        _font_entry_free(fe);
        return;
     }

   _font_load_server_send(fe, CSERVE2_FONT_UNLOAD);

   _font_entry_free(fe);
}

typedef struct
{
   Font_Entry *fe;
   Font_Hint_Flags hints;
   unsigned int rid;
} Glyph_Request_Data;

static Glyph_Map *
_glyph_map_open(Font_Entry *fe, const char *indexpath, const char *datapath)
{
   Glyph_Map *map;

   if (!fe) return NULL;
   if (fe->map) return fe->map;

   map = calloc(1, sizeof(*map));
   if (!map) return NULL;

   map->fe = fe;
   eina_clist_init(&map->glyphs);
   eina_strlcpy(map->mempool.path, datapath, SHARED_BUFFER_PATH_MAX);

   if (indexpath)
     {
        eina_strlcpy(map->index.path, indexpath, SHARED_BUFFER_PATH_MAX);
        map->index.generation_id = _index.generation_id;
        _shared_index_remap_check(&map->index, sizeof(Glyph_Data));
     }

   map->mempool.f = eina_file_open(map->mempool.path, EINA_TRUE);
   map->mempool.size = eina_file_size_get(map->mempool.f);
   map->mempool.data = eina_file_map_all(map->mempool.f, EINA_FILE_RANDOM);

   fe->map = map;
   return map;
}

static Eina_Bool
_glyph_map_remap_check(Glyph_Map *map)
{
   Eina_Bool changed = EINA_FALSE;
   int oldcount;

   if (eina_file_refresh(map->mempool.f)
       || (eina_file_size_get(map->mempool.f) != (size_t) map->mempool.size))
     {
        CS_Glyph_Out *gl;

        WRN("Glyph pool has been resized.");
        eina_file_map_free(map->mempool.f, map->mempool.data);
        map->mempool.data = eina_file_map_all(map->mempool.f, EINA_FILE_RANDOM);
        if (map->mempool.data)
          map->mempool.size = eina_file_size_get(map->mempool.f);
        else
          map->mempool.size = 0;
        changed = EINA_TRUE;

        // Remap loaded glyphs
        EINA_CLIST_FOR_EACH_ENTRY(gl, &map->fe->map->glyphs,
                                  CS_Glyph_Out, map_entry)
          {
             if (map->mempool.data)
               gl->base.bitmap.buffer = (unsigned char *)
                     map->mempool.data + gl->offset;
             else
               gl->base.bitmap.buffer = NULL;
          }
     }

   map->index.generation_id = _index.generation_id;
   oldcount = map->index.count;
   _shared_index_remap_check(&map->index, sizeof(Glyph_Data));
   changed |= (oldcount != map->index.count);

   return changed;
}

static int
_font_entry_glyph_map_rebuild_check(Font_Entry *fe, Font_Hint_Flags hints)
{
   Eina_Bool changed = EINA_FALSE;
   int cnt = 0;

   if (!fe->map)
     {
        const Font_Data *fd;
        const char *idxpath, *datapath;

        fd = _shared_font_entry_data_find(fe);
        if (!fd) return -1;

        idxpath = _shared_string_get(fd->glyph_index_shm);
        datapath = _shared_string_get(fd->mempool_shm);
        if (!idxpath || !datapath) return -1;

        fe->map =_glyph_map_open(fe, idxpath, datapath);
        changed = EINA_TRUE;
     }

   changed |= _glyph_map_remap_check(fe->map);
   if (changed && fe->map && fe->map->index.data && fe->map->mempool.data)
     {
        CS_Glyph_Out *gl;
        const Glyph_Data *gd;
        int k, tot = 0;

        DBG("Rebuilding font hash based on shared index...");
        for (k = 0; k < fe->map->index.count; k++)
          {
             gd = &(fe->map->index.entries.gldata[k]);
             if (!gd->id) break;
             if (!gd->refcount) continue;
             if (gd->hint != hints) continue;

             tot++;
             gl = fash_gl_find(fe->fash[hints], gd->index);
             if (gl && gl->base.bitmap.buffer) continue;

             if (!gl) gl = calloc(1, sizeof(*gl));
             gl->map = fe->map;
             gl->offset = gd->offset;
             gl->size = gd->size;
             gl->base.bitmap.rows = gd->rows;
             gl->base.bitmap.width = gd->width;
             gl->base.bitmap.pitch = gd->pitch;
             gl->base.bitmap.buffer = (unsigned char *)
                   fe->map->mempool.data + gl->offset;
             gl->base.bitmap.num_grays = gd->num_grays;
             gl->base.bitmap.pixel_mode = gd->pixel_mode;
             gl->idx = gd->index;
             gl->rid = 0;

             eina_clist_add_head(&fe->map->glyphs, &gl->map_entry);
             fash_gl_add(fe->fash[hints], gd->index, gl);
             cnt++;
          }
        if (cnt)
          DBG("Added %d glyphs to the font hash (out of %d scanned)", cnt, tot);
     }

   return cnt;
}

static void
_glyph_request_cb(void *data, const void *msg, int size)
{
   const Msg_Font_Glyphs_Loaded *resp = msg;
   Glyph_Request_Data *grd = data;
   Font_Entry *fe = grd->fe;
   const char *buf;
   int i, nglyphs;
   int namelen;
   const char *name;
   int pos;

   if (resp->base.type == CSERVE2_ERROR)
     goto end;

   if (!fe->fash[grd->hints])
     goto end;

   if (size <= (int) sizeof(*resp)) goto end;

   buf = (const char *)resp + sizeof(*resp);
   pos = buf - (const char*) resp;

   pos += sizeof(int);
   if (pos > size) goto end;

   memcpy(&namelen, buf, sizeof(int));
   buf += sizeof(int);

   pos += namelen + sizeof(int);
   if (pos > size) goto end;

   name = buf; //eina_stringshare_add_length(buf, namelen);
   buf += namelen;

   memcpy(&nglyphs, buf, sizeof(int));
   buf += sizeof(int);

   if (!fe->map)
     {
        const Font_Data *fd;
        const char *idxpath = NULL, *datapath;

        fd = _shared_font_entry_data_find(fe);
        if (fd)
          {
             idxpath = _shared_string_get(fd->glyph_index_shm);
             datapath = _shared_string_get(fd->mempool_shm);
          }
        else
          datapath = name;
        fe->map = _glyph_map_open(fe, idxpath, datapath);
     }
   else
     _glyph_map_remap_check(fe->map);

   for (i = 0; i < nglyphs; i++)
     {
        string_t shm_id;
        unsigned int idx, offset, glsize, hints;
        int rows, width, pitch, num_grays, pixel_mode;
        CS_Glyph_Out *gl;

        pos = buf - (const char*) resp;
        pos += 8 * sizeof(int);
        if (pos > size) goto end;

        memcpy(&idx, buf, sizeof(int));
        buf += sizeof(int);
        memcpy(&shm_id, buf, sizeof(string_t));
        buf += sizeof(string_t);
        memcpy(&offset, buf, sizeof(int));
        buf += sizeof(int);
        memcpy(&glsize, buf, sizeof(int));
        buf += sizeof(int);
        memcpy(&rows, buf, sizeof(int));
        buf += sizeof(int);
        memcpy(&width, buf, sizeof(int));
        buf += sizeof(int);
        memcpy(&pitch, buf, sizeof(int));
        buf += sizeof(int);
        memcpy(&num_grays, buf, sizeof(int));
        buf += sizeof(int);
        memcpy(&pixel_mode, buf, sizeof(int));
        buf += sizeof(int);
        memcpy(&hints, buf, sizeof(int));
        buf += sizeof(int);
        if (hints != grd->hints)
          {
             WRN("Invalid hints received: %d vs %d. Skip.", hints, grd->hints);
             continue;
          }

        gl = fash_gl_find(fe->fash[hints], idx);
        if (gl)
          {
             gl->map = fe->map;
             gl->offset = offset;
             gl->size = glsize;
             gl->base.bitmap.rows = rows;
             gl->base.bitmap.width = width;
             gl->base.bitmap.pitch = pitch;
             gl->base.bitmap.buffer = (unsigned char *)
                   fe->map->mempool.data + gl->offset;
             gl->base.bitmap.num_grays = num_grays;
             gl->base.bitmap.pixel_mode = pixel_mode;
             gl->rid = 0;

             if (gl->offset + glsize > (size_t) fe->map->mempool.size)
               {
                  ERR("Glyph is out of the buffer. Set buffer to NULL.");
                  gl->base.bitmap.buffer = NULL;
               }

             eina_clist_add_head(&fe->map->glyphs, &gl->map_entry);
          }
     }

end:
   free(grd);
}

static unsigned int
_glyph_request_server_send(Font_Entry *fe, Font_Hint_Flags hints, Eina_Bool used)
{
   Msg_Font_Glyphs_Request *msg;
   Glyph_Request_Data *grd = NULL;
   int source_len, name_len, size, nglyphs;
   char *buf;
   unsigned int *glyphs;
   unsigned int ret = 0;
   Op_Callback cb;
   Eina_Clist *queue, *itr, *itr_next;


   source_len = fe->source ? eina_stringshare_strlen(fe->source) + 1 : 0;
   name_len = eina_stringshare_strlen(fe->name) + 1;

   if (!used)
     {
        nglyphs = fe->glyphs_queue_count;
        queue = &fe->glyphs_queue;
     }
   else
     {
        nglyphs = fe->glyphs_used_count;
        queue = &fe->glyphs_used;
     }

   size = sizeof(*msg) + source_len + name_len + (nglyphs * sizeof(int));
   msg = calloc(1, size);

   msg->base.rid = _next_rid();
   if (!used)
     msg->base.type = CSERVE2_FONT_GLYPHS_LOAD;
   else
     msg->base.type = CSERVE2_FONT_GLYPHS_USED;

   msg->sourcelen = source_len;
   msg->pathlen = name_len;
   msg->rend_flags = fe->wanted_rend;
   msg->size = fe->size;
   msg->dpi = fe->dpi;
   msg->hint = hints;
   msg->nglyphs = nglyphs;

   buf = ((char *)msg) + sizeof(*msg);
   if (source_len > 0) memcpy(buf, fe->source, source_len);
   buf += source_len;
   memcpy(buf, fe->name, name_len);
   buf += name_len;
   glyphs = (unsigned int *)buf;
   nglyphs = 0;
   EINA_CLIST_FOR_EACH_SAFE(itr, itr_next, queue)
     {
        CS_Glyph_Out *gl;

        if (!used)
          {
             gl = EINA_CLIST_ENTRY(itr, CS_Glyph_Out, map_entry);
             gl->rid = msg->base.rid;
             eina_clist_remove(&gl->map_entry);
          }
        else
          {
             gl = EINA_CLIST_ENTRY(itr, CS_Glyph_Out, used_list);
             gl->used = EINA_FALSE;
             eina_clist_remove(&gl->used_list);
          }
        glyphs[nglyphs++] = gl->idx;
     }
   if (!used)
     fe->glyphs_queue_count = 0;
   else
     fe->glyphs_used_count = 0;

   if (!used)
     {
        cb = _glyph_request_cb;
        grd = malloc(sizeof(*grd));
        grd->fe = fe;
        grd->rid = msg->base.rid;
        grd->hints = hints;
     }
   else
     cb = NULL;

   if (_server_send(msg, size, cb, grd))
     ret = msg->base.rid;
   else
     free(grd);

   free(msg);

   return ret;
}

Eina_Bool
evas_cserve2_font_glyph_request(Font_Entry *fe, unsigned int idx, Font_Hint_Flags hints)
{
   Fash_Glyph2 *fash;
   CS_Glyph_Out *glyph;

   if (fe->rid)
     _server_dispatch_until(0); /* dispatch anything pending just to avoid
                                   requesting glyphs for a font we may already
                                   know it failed loading, but don't block */

   if (fe->failed)
     return EINA_FALSE;

   fash = fe->fash[hints];
   if (!fash)
     {
        fash = fash_gl_new(_glyph_out_free);
        fe->fash[hints] = fash;
     }

   glyph = fash_gl_find(fash, idx);
   if (!glyph)
     {
        glyph = calloc(1, sizeof(*glyph));

        glyph->idx = idx;

        fash_gl_add(fash, idx, glyph);

        eina_clist_add_head(&fe->glyphs_queue, &glyph->map_entry);
        fe->glyphs_queue_count++;
     }
   else if (!glyph->used)
     {
        eina_clist_add_head(&fe->glyphs_used, &glyph->used_list);
        fe->glyphs_used_count++;
        glyph->used = EINA_TRUE;
     }

   /* FIXME crude way to manage a queue, but it will work for now */
   if (fe->glyphs_queue_count == 50)
     _glyph_request_server_send(fe, hints, EINA_FALSE);

   return EINA_TRUE;
}

Eina_Bool
evas_cserve2_font_glyph_used(Font_Entry *fe, unsigned int idx, Font_Hint_Flags hints)
{
   Fash_Glyph2 *fash;
   CS_Glyph_Out *glyph;

   if (fe->rid)
     _server_dispatch_until(0); /* dispatch anything pending just to avoid
                                   requesting glyphs for a font we may already
                                   know it failed loading, but don't block */

   if (fe->failed)
     return EINA_FALSE;

   fash = fe->fash[hints];
   if (!fash)
     return EINA_FALSE;

   glyph = fash_gl_find(fash, idx);
   /* If we found the glyph on client cache, we should also have at least
    * its request done.
    */
   if (!glyph)
     return EINA_FALSE;

   if (!glyph->map)
     return EINA_TRUE;

   if (glyph->used)
     return EINA_TRUE;

   eina_clist_add_head(&fe->glyphs_used, &glyph->used_list);
   fe->glyphs_used_count++;
   glyph->used = EINA_TRUE;

   return EINA_TRUE;
}

RGBA_Font_Glyph_Out *
evas_cserve2_font_glyph_bitmap_get(Font_Entry *fe, unsigned int idx,
                                   Font_Hint_Flags hints)
{
   Fash_Glyph2 *fash;
   CS_Glyph_Out *out;

   if (fe->failed)
     return NULL;

   /* quick hack, flush pending queue when we are asked for a bitmap */
   if (fe->glyphs_queue_count)
     _glyph_request_server_send(fe, hints, EINA_FALSE);

   if (fe->glyphs_used_count)
     _glyph_request_server_send(fe, hints, EINA_TRUE);

   fash = fe->fash[hints];
   if (!fash)
     {
        // this should not happen really, so let the user know he fucked up
        ERR("was called with a hinting value that was not requested!");
        return NULL;
     }

   out = fash_gl_find(fash, idx);
   if (!out)
     {
        // again, if we are asking for a bitmap we were supposed to already
        // have requested the glyph, it must be there
        ERR("was called with a glyph index that was not requested!");
        return NULL;
     }

#if USE_SHARED_INDEX
   _font_entry_glyph_map_rebuild_check(fe, hints);
#endif

   if (out->rid)
     _server_dispatch_until(out->rid);

   // promote shm and font entry in lru or something

   return &(out->base);
}



// Fast access to shared index tables

static Eina_Bool
_string_index_refresh(void)
{
   size_t sz;
   Eina_Bool ret = EINA_FALSE;

   if (!_index.strings_entries.data
       && _index.strings_entries.path[0]
       && _index.strings_index.path[0])
     {
        _index.strings_entries.f = eina_file_open(_index.strings_entries.path, EINA_TRUE);
        _index.strings_entries.size = eina_file_size_get(_index.strings_entries.f);
        if (_index.strings_entries.size > 0)
          _index.strings_entries.data = eina_file_map_all(_index.strings_entries.f, EINA_FILE_RANDOM);

        if (!_index.strings_entries.data)
          {
             ERR("Could not map strings entries from: '%s'", _index.strings_entries.path);
             eina_file_close(_index.strings_entries.f);
             _index.strings_entries.f = NULL;
             _index.strings_entries.data = NULL;
             ret = EINA_FALSE;
          }
        else
          {
             DBG("Mapped string entries from %s", _index.strings_entries.path);
             ret = EINA_TRUE;
          }
     }

   if (_index.strings_entries.data &&
       (!_index.strings_index.data && _index.strings_index.path[0]))
     {
        _index.strings_index.f = eina_file_open(_index.strings_index.path, EINA_TRUE);
        sz = eina_file_size_get(_index.strings_index.f);
        if (sz >= sizeof(Shared_Array_Header))
          _index.strings_index.data = eina_file_map_all(_index.strings_index.f, EINA_FILE_RANDOM);

        if (_index.strings_index.data)
          {
             DBG("Mapped string indexes from %s", _index.strings_index.path);
             sz = eina_file_size_get(_index.strings_index.f);
             _index.strings_index.count = (sz - sizeof(Shared_Array_Header)) / sizeof(Index_Entry);
             if (_index.strings_index.count > _index.strings_index.header->count)
               {
                  WRN("Detected larger index than advertised: %d > %d",
                      _index.strings_index.count, _index.strings_index.header->count);
                  _index.strings_index.count = _index.strings_index.header->count;
               }
             ret = EINA_TRUE;
          }
        else
          {
             ERR("Could not map string indexes from %s", _index.strings_index.path);
             eina_file_close(_index.strings_index.f);
             eina_file_map_free(_index.strings_entries.f, _index.strings_entries.data);
             eina_file_close(_index.strings_entries.f);
             _index.strings_index.f = NULL;
             _index.strings_entries.f = NULL;
             _index.strings_entries.data = NULL;
             ret = EINA_FALSE;
          }
     }

   _shared_index_remap_check(&_index.strings_index, sizeof(Index_Entry));
   if (_index.strings_entries.data)
     {
        if (eina_file_refresh(_index.strings_entries.f)
            || (_index.strings_entries.size != (int) eina_file_size_get(_index.strings_entries.f)))
          {
             eina_file_map_free(_index.strings_entries.f, _index.strings_entries.data);
             _index.strings_entries.data = eina_file_map_all(_index.strings_entries.f, EINA_FILE_RANDOM);
             _index.strings_entries.size = eina_file_size_get(_index.strings_entries.f);
             return EINA_TRUE;
          }
     }

   return ret;
}

// Returns the number of correctly opened index arrays
static int
_server_index_list_set(Msg_Base *data, int size)
{
   Msg_Index_List *msg = (Msg_Index_List *) data;

   // TODO #1: Check populate rule.
   // TODO #2: Protect memory for read-only access.
   // TODO #3: Optimize file reopen/remap (esp. strings table)

   if (size != sizeof(*msg) || msg->base.type != CSERVE2_INDEX_LIST)
     {
        CRIT("Invalid message! type: %d, size: %d (expected %d)",
             msg->base.type, size, (int) sizeof(*msg));
        return -1;
     }

   if (_index.generation_id == msg->generation_id)
     {
        ERR("New index generation_id is the same as before: %d",
            _index.generation_id);
     }

   _index.generation_id = msg->generation_id;

   // 1. Strings (indexes and entries)

   if (_index.strings_entries.data
       && strncmp(_index.strings_entries.path, msg->strings_entries_path,
                  SHARED_BUFFER_PATH_MAX) != 0)
     {
        DBG("Updating string entries shm to: '%s'", msg->strings_entries_path);
        eina_file_map_free(_index.strings_entries.f, _index.strings_entries.data);
        eina_file_close(_index.strings_entries.f);
        _index.strings_entries.f = NULL;
        _index.strings_entries.data = NULL;
     }

   if (_index.strings_index.data
       && strncmp(_index.strings_index.path, msg->strings_index_path,
                  SHARED_BUFFER_PATH_MAX) != 0)
     {
        DBG("Updating string indexes shm to: '%s'", msg->strings_index_path);
        eina_file_map_free(_index.strings_index.f, _index.strings_index.data);
        eina_file_close(_index.strings_index.f);
        _index.strings_index.f = NULL;
        _index.strings_index.data = NULL;
     }

   eina_strlcpy(_index.strings_entries.path, msg->strings_entries_path, SHARED_BUFFER_PATH_MAX);
   eina_strlcpy(_index.strings_index.path, msg->strings_index_path, SHARED_BUFFER_PATH_MAX);
   _string_index_refresh();


   // 2. File indexes

   eina_strlcpy(_index.files.path, msg->files_index_path, SHARED_BUFFER_PATH_MAX);
   _shared_index_remap_check(&_index.files, sizeof(File_Data));


   // 3. Image indexes

   eina_strlcpy(_index.images.path, msg->images_index_path, SHARED_BUFFER_PATH_MAX);
   _shared_index_remap_check(&_index.images, sizeof(Image_Data));


   // 4. Font indexes

   eina_strlcpy(_index.fonts.path, msg->fonts_index_path, SHARED_BUFFER_PATH_MAX);
   _shared_index_remap_check(&_index.fonts, sizeof(Font_Data));

   return 0;
}

// FIXME: (almost) copy & paste from evas_cserve2_cache.c
static const char *
_shared_string_get(int id)
{
   Index_Entry *ie;

   if (!_index.strings_entries.data)
     {
        CRIT("Strings table is not valid: no data");
        return NULL;
     }

   ie = (Index_Entry *)
         _shared_index_item_get_by_id(&_index.strings_index, sizeof(*ie), id);
   if (!ie) return NULL;
   if (ie->offset < 0) return NULL;
   if (!ie->refcount) return NULL;
   if (ie->offset + ie->length > _index.strings_entries.size)
     {
        if (eina_file_refresh(_index.strings_entries.f)
            || (_index.strings_entries.size != (int) eina_file_size_get(_index.strings_entries.f)))
          {
             DBG("String entries size has changed from %d to %d",
                 _index.strings_entries.size, (int) eina_file_size_get(_index.strings_entries.f));
             if (_string_index_refresh())
               return _shared_string_get(id);
          }
        return NULL;
     }

   return _index.strings_entries.data + ie->offset;
}

#define SHARED_INDEX_CHECK(si, typ) \
   do { if (!_shared_index_remap_check(&(si), sizeof(typ))) { \
   CRIT("Failed to remap index"); return NULL; } } while (0)

static const char *
_shared_file_data_hkey_get(char *hkey, const char *file, const char *key,
                           size_t hkey_size)
{
   size_t keylen = 0, filelen;

   if (key) keylen = strlen(key) + 1;
   filelen = strlen(file);

   if (filelen + keylen + 1 > hkey_size)
     return NULL;

   memcpy(hkey, file, filelen);
   hkey[filelen] = ':';
   if (key)
     memcpy(hkey + filelen + 1, key, keylen);
   else
     memcpy(hkey + filelen + 1, "(null)", 7);

   return hkey;
}

static const File_Data *
_shared_image_entry_file_data_find(Image_Entry *ie)
{
   const File_Data *fdata = NULL;
   File_Entry *fe;
   Eina_Bool add_to_hash = SHARED_INDEX_ADD_TO_HASH;
   char hkey[PATH_MAX];
   int k;

   DBG("Trying to find if image '%s:%s' is already opened by cserve2",
       ie->file, ie->key);

   SHARED_INDEX_CHECK(_index.files, File_Data);

   if (!_index.strings_index.header || !_index.strings_entries.data)
     return NULL;

   if (!_index.files.header || !_index.files.entries.filedata)
     return NULL;

   // Direct access
   fe = ie->data1;
   if (fe->server_file_id)
     {
        if ((fdata = _shared_file_data_get_by_id(fe->server_file_id)) != NULL)
          return fdata;
     }

   // Check hash
   _shared_file_data_hkey_get(hkey, ie->file, ie->key, PATH_MAX);
   fdata = eina_hash_find(_index.files.entries_by_hkey, hkey);
   if (fdata)
     return fdata;

   // Scan shared index
   for (k = _index.files.last_entry_in_hash;
        k < _index.files.count && k < _index.files.header->emptyidx; k++)
     {
        const char *file, *key;
        const File_Data *fd;
        char fd_hkey[PATH_MAX];

        fd = &(_index.files.entries.filedata[k]);
        if (!fd->id) break;
        if (!fd->refcount) continue;

        key = _shared_string_get(fd->key);
        file = _shared_string_get(fd->path);
        if (!file)
          {
             ERR("Could not find filename for file %d: path id: %d",
                 fd->id, fd->path);
             add_to_hash = EINA_FALSE;
             continue;
          }

        // Note: The strings base pointer may change if the index grows
        if ((key < _index.strings_entries.data) ||
            (key > _index.strings_entries.data + _index.strings_entries.size))
          key = _shared_string_get(fd->key);

        _shared_file_data_hkey_get(fd_hkey, file, key, PATH_MAX);

        if (add_to_hash)
          {
             eina_hash_add(_index.files.entries_by_hkey, fd_hkey, fd);
             _index.files.last_entry_in_hash = k;
          }

        if (!strcmp(hkey, fd_hkey))
          return fd;
     }

   return NULL;
}

static const Shm_Object *
_shared_index_item_get_by_id(Shared_Index *si, int elemsize, unsigned int id)
{
   const Shm_Object *obj;
   const char *base;
   int low = 0, high, start_high;
   int cur;

   if (!si || elemsize <= 0 || !id)
     return NULL;

   // FIXME: HACK (consider all arrays always sorted by id)
   high = si->header->emptyidx; // Should be si->header->sortedidx

   if (high > si->count)
     {
        if (eina_file_refresh(si->f))
          {
             WRN("Refreshing indexes.");
             _string_index_refresh();
             _shared_index_remap_check(si, elemsize);
             high = MIN(si->header->emptyidx, si->count);
          }
        else
          high = si->count;
     }

   base = si->data  + sizeof(Shared_Array_Header);

   // Direct access, works for non-repacked arrays
   if ((int) id < high)
     {
        obj = (Shm_Object *) (base + (elemsize * id));
        if (obj->id == id)
          return obj;
     }

   // Binary search
   start_high = high;
   while(high != low)
     {
        cur = low + ((high - low) / 2);
        obj = (Shm_Object *) (base + (elemsize * cur));
        if (obj->id == id)
          return obj;
        if (obj->id < id)
          low = cur + 1;
        else
          high = cur;
     }

   // Linear search
   for (cur = start_high; cur < si->count; cur++)
     {
        obj = (Shm_Object *) (base + (elemsize * cur));
        if (!obj->id)
          return NULL;
        if (obj->id == id)
          return obj;
     }

   return NULL;
}

static const File_Data *
_shared_file_data_get_by_id(unsigned int id)
{
   return (const File_Data *)
         _shared_index_item_get_by_id(&_index.files, sizeof(File_Data), id);
}

static inline Eina_Bool
_shared_image_entry_image_data_match(Image_Entry *ie, const Image_Data *id)
{
   int cmp;
   cmp = memcmp(&ie->load_opts, &id->opts, sizeof(ie->load_opts));
   if (!cmp)
     {
        DBG("Found loaded image entry at %d", id->id);
        return EINA_TRUE;
     }
   return EINA_FALSE;
}

static Eina_Bool
_shared_index_remap_check(Shared_Index *si, int elemsize)
{
   size_t filesize;
   Eina_Bool refresh = EINA_FALSE;

   // Note: all checks are unlikely to be true.

   if (!si || elemsize <= 0)
     return EINA_FALSE;

   if (!si->path[0])
     {
        if (si->f)
          {
             DBG("Closing index map");
             eina_file_map_free(si->f, si->data);
             eina_file_close(si->f);
             eina_hash_free(si->entries_by_hkey);
             si->f = NULL;
             si->data = NULL;
             memset(si, 0, sizeof(*si));
          }
        return EINA_FALSE;
     }

   if (si->generation_id != _index.generation_id)
     {
        DBG("Generation ID changed from %d to %d.",
            si->generation_id, _index.generation_id);
        if (si->f)
          {
             if (strncmp(si->path, eina_file_filename_get(si->f),
                         SHARED_BUFFER_PATH_MAX) != 0)
               {
                  DBG("Index file changed. Closing and reopening.");
                  eina_file_map_free(si->f, si->data);
                  eina_file_close(si->f);
                  si->f = NULL;
                  si->data = NULL;
               }
             else
               {
                  if (si->data)
                    {
                       if (eina_file_refresh(si->f))
                         {
                            DBG("Remapping index.");
                            eina_file_map_free(si->f, si->data);
                            si->data = NULL;
                         }
                    }
                  else
                    {
                       eina_file_close(si->f);
                       si->f = NULL;
                    }
               }
          }
        si->generation_id = _index.generation_id;
     }
   if (!si->f)
     {
        si->data = NULL; // If that was not NULL, the address was invalid.
        si->f = eina_file_open(si->path, EINA_TRUE);
        if (!si->f)
          {
             ERR("Could not open index '%s'", si->path);
             return EINA_FALSE;
          }
     }
   if (!si->data)
     {
        filesize = eina_file_size_get(si->f);
        if (filesize < sizeof(Shared_Array_Header))
          {
             ERR("Index is invalid. Got file size %d", (int) filesize);
             eina_file_close(si->f);
             si->f = NULL;
             return EINA_FALSE;
          }
        si->data = eina_file_map_all(si->f, EINA_FILE_RANDOM);
        if (!si->data)
          {
             ERR("Could not mmap index '%s'", si->path);
             eina_file_close(si->f);
             si->f = NULL;
             return EINA_FALSE;
          }
        si->count = (filesize - sizeof(Shared_Array_Header)) / elemsize;
        refresh = EINA_TRUE;
     }

   if (elemsize != si->header->elemsize)
     {
        ERR("Index is invalid. Expected element size %d, got %d.",
            elemsize, si->header->elemsize);
        return EINA_FALSE;
     }

   if (si->count != si->header->count)
     {
        int oldcount;
        // generation_id should have been incremented. Maybe we are hitting
        // a race condition here, when cserve2 grows an index.
        WRN("Reported index count differs from known count: %d vs %d",
            si->header->count, si->count);
        oldcount = si->count;
        eina_file_refresh(si->f);
        filesize = eina_file_size_get(si->f);
        si->count = (filesize - sizeof(Shared_Array_Header)) / elemsize;
        if (si->count != oldcount)
          {
             DBG("Remapping current index");
             eina_file_map_free(si->f, si->data);
             si->data = eina_file_map_all(si->f, EINA_FILE_RANDOM);
             if (!si->data)
               {
                  ERR("Failed to remap index: %m");
                  return EINA_FALSE;
               }
          }
        if (si->count > si->header->count)
          {
             WRN("Index reports %d elements, but file can contain only %d",
                 si->header->count, si->count);
             si->count = si->header->count;
          }
        refresh = EINA_TRUE;
     }

   if (!si->entries_by_hkey)
     refresh = EINA_TRUE;

   if (refresh)
     {
        if (si->entries_by_hkey) eina_hash_free_buckets(si->entries_by_hkey);
        else si->entries_by_hkey = eina_hash_string_small_new(NULL);
        si->last_entry_in_hash = 0;
        si->entries.p = si->data + sizeof(Shared_Array_Header);
     }

   return EINA_TRUE;
}

static const Image_Data *
_shared_image_entry_image_data_find(Image_Entry *ie)
{
   const Image_Data *idata = NULL;
   const char *shmpath;
   File_Entry *fe;
   unsigned int file_id = 0;
   Eina_Bool add_to_hash = SHARED_INDEX_ADD_TO_HASH;
   int k;


   DBG("Trying to find if image '%s:%s' is already loaded by cserve2",
       ie->file, ie->key);

   if (!_index.strings_entries.data || !_index.strings_index.data)
     return NULL;

   if (!_index.images.entries.idata || !_index.images.count)
     return NULL;

   if (!ie->cache_key)
     {
        CRIT("Looking for an image in remote cache without hash key?");
        return NULL;
     }

   fe = ie->data1;
   if (fe && fe->server_file_id)
     file_id = fe->server_file_id;
   else
     {
        const File_Data *fdata = _shared_image_entry_file_data_find(ie);
        if (!fdata)
          {
             ERR("File is not opened by cserve2");
             return NULL;
          }
        file_id = fdata->id;
     }

   SHARED_INDEX_CHECK(_index.images, Image_Data);

   // Find in known entries hash. O(log n)
   DBG("Looking for %s in hash", ie->cache_key);
   idata = (const Image_Data *)
         eina_hash_find(_index.images.entries_by_hkey, ie->cache_key);
   if (idata)
     {
        DBG("Image found in shared index (by cache_key).");
        goto found;
     }

   // Linear search in non-hashed entries. O(n)
   DBG("Looking for loaded image with file id %d", file_id);
   for (k = _index.images.last_entry_in_hash; k < _index.images.count; k++)
     {
        const char *file, *key;
        size_t keylen, filelen;
        const File_Data *fd;
        char *hkey;
        const Image_Data *id = &(_index.images.entries.idata[k]);

        if (!id->id) return NULL;
        if (!id->refcount) continue;

        if (add_to_hash)
          {
             fd = _shared_file_data_get_by_id(id->file_id);
             if (!fd)
               {
                  ERR("Did not find file data for %d", id->file_id);
                  add_to_hash = EINA_FALSE;
                  continue;
               }

             key = _shared_string_get(fd->key);
             file = _shared_string_get(fd->path);
             if (!file)
               {
                  ERR("No filename for file %d", fd->id);
                  add_to_hash = EINA_FALSE;
                  continue;
               }

             // Note: The strings base pointer may change if the index grows
             if ((key < _index.strings_entries.data) ||
                 (key > _index.strings_entries.data + _index.strings_entries.size))
               key = _shared_string_get(fd->key);

             keylen = key ? strlen(key) : 0;
             filelen = strlen(file);

             hkey = alloca(filelen + keylen + HKEY_LOAD_OPTS_STR_LEN);
             evas_cache2_image_cache_key_create(hkey, file, filelen,
                                                key, keylen, &id->opts);
             eina_hash_add(_index.images.entries_by_hkey, hkey, id);
             _index.images.last_entry_in_hash = k;
          }

        if (id->file_id != file_id) continue;

        if (_shared_image_entry_image_data_match(ie, id))
          {
             idata = id;
             goto found;
          }
     }

   if (!idata)
     return NULL;

found:
   if (!idata->valid)
     {
        DBG("Found image but it is not ready yet: %d", idata->id);
        return NULL;
     }

   shmpath = _shared_string_get(idata->shm_id);
   if (!shmpath)
     {
        ERR("Found image but it is not loaded yet: %d (doload %d)",
            idata->id, idata->doload);
        return NULL;
     }

   DBG("Found image, loaded, in shm %s", shmpath);
   return idata;
}

static const Font_Data *
_shared_font_entry_data_get_by_id(int id)
{
   return (Font_Data *)
         _shared_index_item_get_by_id(&_index.fonts, sizeof(Font_Data), id);
}

static const Font_Data *
_shared_font_entry_data_find(Font_Entry *fe)
{
   const Font_Data *fd = NULL;
   Eina_Bool add_to_hash = SHARED_INDEX_ADD_TO_HASH;
   char hkey[PATH_MAX];
   int k;

   if (!_index.strings_entries.data || !_index.strings_index.data)
     return NULL;

   if (!fe || !fe->hkey)
     return NULL;

   if (fe->font_data_id)
     {
        fd = _shared_font_entry_data_get_by_id(fe->font_data_id);
        if (fd) return fd;
        fe->font_data_id = 0;
     }

   // Find in hash
   fd = eina_hash_find(_index.fonts.entries_by_hkey, fe->hkey);
   if (fd) return fd;

   // Find in shared index
   for (k = _index.fonts.last_entry_in_hash;
        k < _index.fonts.count && k < _index.fonts.header->emptyidx; k++)
     {
        const Font_Data *cur;
        const char *name, *source;

        cur = &(_index.fonts.entries.fontdata[k]);
        if (!cur->id) return NULL;
        if (!cur->refcount) continue;

        name = _shared_string_get(cur->name);
        source = _shared_string_get(cur->file);
        snprintf(hkey, PATH_MAX, "%s:%s/%u:%u:%u", source, name,
                 cur->size, cur->dpi, cur->rend_flags);

        if (add_to_hash)
          {
             eina_hash_add(_index.fonts.entries_by_hkey, hkey, cur);
             _index.fonts.last_entry_in_hash++;
          }

        if (!strcmp(hkey, fe->hkey))
          {
             fe->font_data_id = cur->id;
             return cur;
          }
     }

   return fd;
}

#endif