GVOHub.cpp 72.3 KB
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
/***************************************************************************
 *                     GVOHub.cpp - VO SAMP Hub class                      *
 * ----------------------------------------------------------------------- *
 *  copyright (C) 2014-2015 by Thierry Louge                               *
 * ----------------------------------------------------------------------- *
 *                                                                         *
 *  This program is free software: you can redistribute it and/or modify   *
 *  it under the terms of the GNU General Public License as published by   *
 *  the Free Software Foundation, either version 3 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 General Public License for more details.                           *
 *                                                                         *
 *  You should have received a copy of the GNU General Public License      *
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.  *
 *                                                                         *
 ***************************************************************************/
/**
 * @file GVOHub.cpp
 * @brief VO SAMP Hub class implementation
 * @author Thierry Louge
 */

/* __ Includes ___________________________________________________________ */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <cstdlib>         // std::getenv() function
#include <cstdio>          // std::fopen(), etc. functions
#include <cstring>         // std::memset() function
#include <csignal>         // signal() function
#include <cerrno>          // errno
#include <unistd.h>        // close() function
#include <netdb.h>         // getaddrinfo() function
#include <netinet/in.h>    // sockaddr_in, INADDR_ANY, htons
#include <fstream>
#include <sys/shm.h>
#include <sys/socket.h>    // socket(), connect() functions
#include <sys/wait.h>      // waitpid() function
#include <arpa/inet.h>     // inet_addr() function
#include "GVOHub.hpp"
#include "GException.hpp"
#include "GTools.hpp"

/* __ Method name definitions ____________________________________________ */
#define G_START_HUB                                     "GVOHub::start_hub()"

/* __ Macros _____________________________________________________________ */

/* __ Coding definitions _________________________________________________ */

/* __ Debug definitions __________________________________________________ */
#define G_CONSOLE_DUMP
#define G_SHOW_MESSAGE


/*==========================================================================
 =                                                                         =
 =                         Constructors/destructors                        =
 =                                                                         =
 ==========================================================================*/

/***********************************************************************//**
 * @brief Void constructor
 ***************************************************************************/
GVOHub::GVOHub(void)
{
    // Initialise members
    init_members();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Copy constructor
 *
 * @param[in] hub VO Hub.
 ***************************************************************************/
GVOHub::GVOHub(const GVOHub& hub)
{
    // Initialise members
    init_members();
    
    // Copy members
    copy_members(hub);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Destructor
 ***************************************************************************/
GVOHub::~GVOHub(void)
{
    // Free members
    free_members();

    // Return
    return;
}


/*==========================================================================
 =                                                                         =
 =                                Operators                                =
 =                                                                         =
 ==========================================================================*/

/***********************************************************************//**
 * @brief Assignment operator
 *
 * @param[in] hub VO hub.
 * @return VO hub.
 ***************************************************************************/
GVOHub& GVOHub::operator=(const GVOHub& hub)
{
    // Execute only if object is not identical
    if (this != &hub) {

        // Free members
        free_members();

        // Initialise members
        init_members();

        // Copy members
        copy_members(hub);

    } // endif: object was not identical

    // Return
    return *this;
}


/*==========================================================================
 =                                                                         =
 =                             Public methods                              =
 =                                                                         =
 ==========================================================================*/

/***********************************************************************//**
 * @brief Clear object.
 *
 * Reset object to a clean initial state.
 ***************************************************************************/
void GVOHub::clear(void)
{
    // Free members
    free_members();

    // Initialise members
    init_members();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Clone object
 ***************************************************************************/
GVOHub* GVOHub::clone(void) const
{
    // Clone client
    return new GVOHub(*this);
}


/***********************************************************************//**
 * @brief Start Hub
 ***************************************************************************/
void GVOHub::start(void)
{
    // Create SAMP file
    create_samp_file();

    // Start Hub
    start_hub();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Print VO hub information
 *
 * @param[in] chatter Chattiness (defaults to NORMAL).
 * @return String containing VO hub information
 ***************************************************************************/
std::string GVOHub::print(const GChatter& chatter) const
{
    // Initialise result string
    std::string result;

    // Continue only if chatter is not silent
    if (chatter != SILENT) {

        // Append header
        result.append("=== GVOHub ===");

        // Append Hub information
        result.append("\n"+gammalib::parformat("Hub identifier")+m_hub_id);
        result.append("\n"+gammalib::parformat("Hub key")+m_secret);
        result.append("\n"+gammalib::parformat("Hub URL")+m_hub_url);
        result.append("\n"+gammalib::parformat("Hub host")+m_hub_host);
        result.append("\n"+gammalib::parformat("Hub port")+m_hub_port);
        result.append("\n"+gammalib::parformat("Hub path")+m_hub_path);
        result.append("\n"+gammalib::parformat("SAMP protocol version"));
        result.append(m_version);

    } // endif: chatter was not silent

    // Return result
    return result;
}


/*==========================================================================
 =                                                                         =
 =                             Private methods                             =
 =                                                                         =
 ==========================================================================*/

/***********************************************************************//**
 * @brief Initialise class members
 ***************************************************************************/
void GVOHub::init_members(void)
{
    // Initialise members
    m_secret        = random_string(15);
    m_hub_host      = "127.0.0.1";
    m_hub_port      = "2526";
    m_hub_path      = "xmlrpc";
    m_hub_url       = "http://"+m_hub_host+":"+m_hub_port+"/"+m_hub_path;
    m_version       = "1.3";
    m_hub_id        = "gammalib_hub";
    m_socket        = -1;        // Signals no socket
    m_shutdown      = false;
    m_clients.clear();
    
    // Return
    return;
}


/***********************************************************************//**
 * @brief Copy class members
 *
 * @param[in] hub VO hub.
 ***************************************************************************/
void GVOHub::copy_members(const GVOHub& hub)
{
    // Copy members
    m_secret   = hub.m_secret;
    m_hub_url  = hub.m_hub_url;
    m_hub_host = hub.m_hub_host;
    m_hub_port = hub.m_hub_port;
    m_hub_path = hub.m_hub_path;
    m_version  = hub.m_version;
    m_hub_id   = hub.m_hub_id;
    m_socket   = hub.m_socket;
    m_shutdown = hub.m_shutdown;
    m_clients  = hub.m_clients;

    // Return
    return;
}


/***********************************************************************//**
 * @brief Delete class members
 ***************************************************************************/
void GVOHub::free_members(void)
{ 
    // Close sockets
    if (m_socket != -1) {
        close(m_socket);
        m_socket = -1;
    }
    
    // Remove lockfile
    std::string lockurl = get_hub_lockfile();
    std::remove(lockurl.c_str());

    // Return
    return;
}


/***********************************************************************//**
 * @brief Starts the SAMP hub socket and listens on it
 *
 * @exception GException::runtime_error
 *            Problem with creating of or listening on socket
 *
 * This is the main Hub event loop.
 ***************************************************************************/
void GVOHub::start_hub(void)
{
    // Prepare TCP/IP structure
    struct sockaddr_in serv_addr;
    std::memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family      = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(m_hub_host.c_str());
    serv_addr.sin_port        = htons(gammalib::toint(m_hub_port));
    
    // Create Hub socket
    m_socket = socket(AF_INET, SOCK_STREAM, 0);
    
    // Creation of hub main socket
    if (m_socket < 0) {
        std::string msg = "Unable to create Hub socket. Errno="+
                          gammalib::str(errno);
        throw GException::runtime_error(G_START_HUB, msg);
    }
    
    // Set hub main socket to allow multiple connections
    int opt = 1;
    if (setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (char*)&opt, sizeof(opt)) < 0) {
        std::string msg = "Unable to set Hub socket to multiple connections."
                          " Errno="+gammalib::str(errno);
        throw GException::runtime_error(G_START_HUB, msg);
    }
    #ifdef SO_REUSEPORT
    if (setsockopt(m_socket, SOL_SOCKET, SO_REUSEPORT, (char*)&opt, sizeof(opt)) < 0) {
        std::string msg = "Unable to set Hub socket to multiple connections."
                          " Errno="+gammalib::str(errno);
        throw GException::runtime_error(G_START_HUB, msg);
    }
    #endif
    
    // Server socket is opened. Now, bind it to the port, with family etc.
    if (bind(m_socket, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
        std::string msg = "Unable to bind Hub socket to server socket. Errno="+
                          gammalib::str(errno);
        throw GException::runtime_error(G_START_HUB, msg);
    }

    // Now start listening for the clients: 5 requests simultaneously pending
    // at maximum
    if (listen(m_socket, 5) < 0) {
        std::string msg = "Unable to start listening on Hub socket. Errno="+
                          gammalib::str(errno);
        throw GException::runtime_error(G_START_HUB, msg);
    }

    // ...
    struct sockaddr_in cli_addr;
    socklen_t clilen = sizeof(cli_addr);

    // Main event handling loop
    while (1) {

        // Accept connection from the client 
    	socklen_t socket = accept(m_socket, (struct sockaddr *)&cli_addr, &clilen);
    	if (socket < 0) {
            std::string msg = "Client connection to socket not accepted.";
            throw GException::runtime_error(G_START_HUB, msg);
    	}

        // Handle request
        handle_request(socket);

        // Close socket
        close(socket);

        // If we have received a shutdown request then exit the event
        // loop
        if (m_shutdown) {
            break;
        }

    } // endwhile: main event loop

    // Close socket
    close(m_socket);
    m_socket = -1;

    // Return
    return;
}


/***********************************************************************//**
 * @brief Reads the client message and runs appropriate function
 *
 * @param[in] sock Socket to client.
 ***************************************************************************/
void GVOHub::handle_request(const socklen_t& sock)
{
    // Header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::handle_request" << std::endl;
    #endif

    // Initialize buffer
    char buffer[1001];

    // Initialise message
    std::string message = "";

    // Read from socket until nothing is received anymore.
    int timeout = 2000; // Initial timeout is 2 sec
    int n       = 0;
    do {
        n = gammalib::recv(sock, buffer, 1000, 0, timeout);
        if (n > 0) {
            buffer[n] = '\0';
            message.append(std::string(buffer));
        }
        timeout = 10; // The timeout now is 0.01 sec 
    } while (n > 0);
    
    // Dump the buffer
    #if defined(G_SHOW_MESSAGE)
    std::cout << std::endl;
    std::cout << "GVOHub has received the following message:" << std::endl;
    std::cout << "==========================================" << std::endl;
    std::cout << message << std::endl;
    #endif
    
    // Extract response into an XML object
    GXml   xml;
    size_t start_html = message.find("GET /get_fits");
    if (start_html != std::string::npos) {
         #if defined(G_CONSOLE_DUMP)
         std::cout << "get_fits called " << std::endl;
         #endif
	 //Form and send here the html message containing fits file data
	 std::string msg ="";
	 msg.append("HTTP/1.1 200 OK\n");
	 msg.append("Connection: open\n");
         msg.append("Content-Type: multipart/form-data\n");
	 //Fixed length for tests
         msg.append("Content-Length: 364\n");
	 //Fixed filename for tests
	 msg.append("Content-Disposition: form-data; name=\"Gammalib_fits\";filename=\"/root/Skw+_Fermi_5.fits\"\n");
	 post_string(msg, sock);
         #if defined(G_CONSOLE_DUMP)
         std::cout <<msg << std::endl;
         #endif
	// Return
        return;
    }
    
    size_t start = message.find("<?xml");
    if (start != std::string::npos) {
        xml = GXml(message.substr(start, std::string::npos));
    }
    
    // Get methodName value
    std::string method_called;
    const GXmlNode* node = xml.element("methodCall > methodName");
    if (node != NULL) {
        const GXmlText* text = static_cast<const GXmlText*>((*node)[0]);
        if (text != NULL) {
            method_called = text->text();
        }
    }

    // Dump the buffer
    #if defined(G_CONSOLE_DUMP)
    std::cout << "Method called: " << method_called << std::endl;
    #endif

    // Dispatch according to method
    if (method_called.compare("samp.hub.ping") == 0) {
        request_ping(sock);
    }
    else if (method_called.compare("samp.hub.register") == 0) {
        request_register(xml, sock);
    }
    else if (method_called.compare("samp.hub.unregister") == 0) {
        request_unregister(xml, sock);
    }
    else if (method_called.compare("samp.hub.declareMetadata") == 0) {
        request_declare_metadata(xml, sock);
    }
    else if (method_called.compare("samp.hub.declareSubscriptions") == 0) {
        request_declare_subscriptions(xml, sock);
    }
    else if (method_called.compare("samp.hub.setXmlrpcCallback") == 0) {
        request_set_xml_rpc_callback(xml, sock);
    }
    else if (method_called.compare("samp.hub.getSubscriptions") == 0) {
        request_get_subscriptions(xml, sock);
    }
    else if (method_called.compare("samp.hub.getRegisteredClients") == 0) {
        request_get_registered_clients(xml, sock);
    }
    else if (method_called.compare("samp.hub.getSubscribedClients") == 0) {
        request_get_subscribed_clients(xml, sock);
    }
    else if (method_called.compare("samp.hub.getMetadata") == 0) {
        request_get_metadata(xml, sock);
    }
    else if (method_called.compare("table.load.votable") == 0) {
        request_ping(sock);
    }
    else if (method_called.compare("samp.hub.notify") == 0) {
        request_ping(sock);
    }
    else if (method_called.compare("samp.hub.notifyAll") == 0) {
         #if defined(G_CONSOLE_DUMP)
	 std::cout << "==========================================" << std::endl;
	 std::cout << "samp.hub.notifyAll" << std::endl;
         #endif
        broadcast(xml, sock);
    }
    else if (method_called.compare("samp.hub.call") == 0) {
        request_ping(sock);
    }
    else if (method_called.compare("samp.hub.callAll") == 0) {
        request_ping(sock);
    }
    else if (method_called.compare("samp.hub.callAndWait") == 0) {
        request_ping(sock);
    }
    else if (method_called.compare("samp.hub.reply") == 0) {
        request_ping(sock);
    }
    else if (method_called.compare("samp.hub.shutdown") == 0) {
        request_shutdown(sock);
    }

    // Return
    return;
}


/***********************************************************************//**
 * @brief Handles ping requests
 *
 * @param[in] sock Socket.
 *
 * Handles all incoming ping requests.
 ***************************************************************************/
void GVOHub::request_ping(const socklen_t& sock)
{
    // Header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::request_ping" << std::endl;
    #endif
    
    // Post void message
    post_samp_void(sock);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Handles registration requests
 *
 * @param[in] xml XML message sent by client.
 * @param[in] sock Socket.
 *
 * Handles all incoming registration requests.
 ***************************************************************************/
void GVOHub::request_register(const GXml& xml, const socklen_t& sock)
{
    // Header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::request_register" << std::endl;
    #endif

    // Set client reference
    int         counter = 0;
    std::string reference;
    do {
        reference = "c"+gammalib::str(counter);
        int i = 0;
        for (; i < m_clients.size(); ++i) {
            if (m_clients[i].reference == reference) {
                counter++;
                break;
            }
        }
        if (i >= m_clients.size()) {
            break;
        }
    } while (true);

    // Create a new client
    struct client voclient;
    voclient.reference   = reference;
    voclient.private_key = random_string(15);
    
    // Attached client
    m_clients.push_back(voclient);

    // Declare response
    std::string response = "";

    // Set response
    response.append("<?xml version='1.0' encoding='UTF-8'?>\n");
    response.append("<methodResponse>\n");
    response.append("<params>\n");
    response.append("  <param><value><struct>\n");
    response.append("    <member>\n");
    response.append("      <name>samp.private-key</name>\n");
    response.append("      <value>"+voclient.private_key+"</value>\n");
    response.append("    </member>\n");
    response.append("    <member>\n");
    response.append("      <name>samp.hub-id</name>\n");
    response.append("      <value>"+m_hub_id+"</value>\n");
    response.append("    </member>\n");
    response.append("    <member>\n");
    response.append("      <name>samp.self-id</name>\n");
    response.append("      <value>"+voclient.reference+"</value>\n");
    response.append("    </member>\n");
    response.append("    <member>\n");
    response.append("      <name>samp.status</name>\n");
    response.append("      <value>samp.ok</value>\n");
    response.append("    </member>\n");
    response.append("    <member>\n");
    response.append("      <name>samp.url-translator</name>\n");
    response.append("      <value>"+m_hub_url+"</value>\n");
    response.append("    </member>\n");
    response.append("  </struct></value></param>\n");
    response.append("</params>\n");
    response.append("</methodResponse>\n");

    // Post response
    post_string(response, sock);

    // Send notifications
    send_notifications("samp.hub.event.register", voclient.reference);	

    //Return
    return;
}


/***********************************************************************//**
 * @brief Handles unregistration requests
 *
 * @param[in] xml XML message sent by client.
 * @param[in] sock Socket.
 *
 * Handles all incoming unregistration requests.
 ***************************************************************************/
void GVOHub::request_unregister(const GXml& xml, const socklen_t& sock)
{
    // Optionally dump header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::request_unregister" << std::endl;
    #endif 

    // Get client index
    int i = get_client_index(xml);

    // Continue only if index is valid
    if (i != -1) {

        // Post void message
        post_samp_void(sock);

        // Send notifications
        send_notifications("samp.hub.event.unregister",
                           m_clients[i].reference);

        // Remove client
        m_clients.erase(m_clients.begin()+i);
        
    } // endif: valid client found

    // Signal if the client was unknown
    #if defined(G_CONSOLE_DUMP)
    else {
        std::cout << " *** ERROR: Unable to find client " << get_client_key(xml) << std::endl;
    }
    #endif
    
    // Return
    return;
}


/***********************************************************************//**
 * @brief Handles metadata declaration requests
 *
 * @param[in] xml XML message sent by client.
 * @param[in] sock Socket.
 *
 * Handles all incoming metadata declaration requests.
 ***************************************************************************/
void GVOHub::request_declare_metadata(const GXml& xml, const socklen_t& sock)
{
    // Header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::request_declare_metadata" << std::endl;
    #endif

    // Get client index
    int i = get_client_index(xml);

    // Continue only if index is valid
    if (i != -1) {

        // Store metadata
        m_clients[i].name          = get_response_value(xml, "samp.name");;
        m_clients[i].description   = get_response_value(xml, "samp.description.text");
        m_clients[i].icon          = get_response_value(xml, "samp.icon.url");
        m_clients[i].documentation = get_response_value(xml, "samp.documentation.url");
        m_clients[i].affiliation   = get_response_value(xml, "author.affiliation");
        m_clients[i].email         = get_response_value(xml, "author.email");
        m_clients[i].author_name   = get_response_value(xml, "author.name");
        m_clients[i].homepage      = get_response_value(xml, "home.page");

        // Post void message
        post_samp_void(sock);
            
        // Send notifications
        send_notifications("samp.hub.event.metadata", m_clients[i].reference);

    } // endif: client found
        
    // Signal if the client was unknown
    #if defined(G_CONSOLE_DUMP)
    else {
        std::cout << " *** ERROR: Unable to find client " << get_client_key(xml) << std::endl;
    }
    #endif
    
    // Return
    return;
}


/***********************************************************************//**
 * @brief Handles subscriptions declaration requests
 *
 * @param[in] xml XML message sent by client.
 * @param[in] sock Socket.
 *
 * Handles all incoming subscription declaration requests.
 ***************************************************************************/
void GVOHub::request_declare_subscriptions(const GXml& xml,const socklen_t& sock)
{
    // Header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::request_declare_subscriptions" << std::endl;
    #endif

    // Get client index
    int i = get_client_index(xml);

    // Continue only if index is valid
    if (i != -1) {

        // Get subscriptions
        std::vector<std::string> subscriptions = get_subscriptions(xml);

        // Store subscriptions
        for (int k = 0; k < subscriptions.size(); ++k) {
            m_clients[i].subscriptions.push_back(subscriptions[k]);
        }

        // Post SAMP ok
        post_samp_ok(sock);
        
    } // endif: valid client found

    // Signal if the client was unknown
    #if defined(G_CONSOLE_DUMP)
    else {
        std::cout << " *** ERROR: Unable to find client " << get_client_key(xml) << std::endl;
    }
    #endif
    
    //Return
    return;
}


/***********************************************************************//**
 * @brief Handles XML-RPC callback setting requests
 *
 * @param[in] xml XML message sent by client.
 * @param[in] sock Socket.
 *
 * Handles all incoming XML-RPC callback setting requests.
 ***************************************************************************/
void GVOHub::request_set_xml_rpc_callback(const GXml&      xml,
                                          const socklen_t& sock)
{
    // Header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::request_set_xml_rpc_callback" << std::endl;
    #endif

    // Get client index
    int i = get_client_index(xml);

    // Continue only if index is valid
    if (i != -1) {

        // Get callback URL
        std::string client_url = get_callback_url(xml);

        // Set callback URL
        m_clients[i].url = get_callback_url(xml);

        // Post SAMP ok
        post_samp_ok(sock);

    } // endif: client found

    // Signal if the client was unknown
    #if defined(G_CONSOLE_DUMP)
    else {
        std::cout << " *** ERROR: Unable to find client " << get_client_key(xml) << std::endl;
    }
    #endif

    // Return
    return;
}


/***********************************************************************//**
 * @brief Handles subscriptions getting requests
 *
 * @param[in] xml XML message sent by client.
 * @param[in] sock Socket.
 *
 * Handles all incoming subscriptions getting requests.
 ***************************************************************************/
void GVOHub::request_get_subscriptions(const GXml& xml, const socklen_t& sock)
{
    // Header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::request_get_subscriptions" << std::endl;
    #endif

    // Initialise client name
    std::string client_name = "";

    // Get the client name
    const GXmlNode* node = xml.element("methodCall > params > param[1] > value");
    if (node != NULL) {
        const GXmlText* text = static_cast<const GXmlText*>((*node)[0]);
        if (text != NULL) {
            client_name = text->text();
        }
    }

    // Declare response
    std::string response = "";

    // Set response
    response.append("<?xml version='1.0' encoding='UTF-8'?>\n");
    response.append("<methodResponse>\n");
    response.append("<params>\n");
    response.append("  <param><value><struct>\n");

    // If key is "gammalib_hub" then return some special information
    if (client_name == "gammalib_hub") {
        // Do nothing
    }
    
    // ... handle all other clients
    else {

        // Get client index
        int i = get_client_index(client_name);

        // Continue only if index is valid
        if (i != -1) {

            // Append all subscriptions
            for (int k = 0; k < m_clients[i].subscriptions.size(); ++k) {
                response.append("    <member>\n");
                response.append("      <name>");
                response.append(m_clients[i].subscriptions[k]);
                response.append("</name>\n");
                response.append("      <value></value>\n");
                response.append("    </member>\n");
            }
            
        }

        // Signal if the client was unknown
        #if defined(G_CONSOLE_DUMP)
        else {
            std::cout << " *** ERROR: Unable to find client " << get_client_key(xml) << std::endl;
        }
        #endif
        
    }

    // Finish response
    response.append("  </struct></value></param>\n");
    response.append("</params>\n");
    response.append("</methodResponse>\n");
        
    // Post response
    post_string(response, sock);
   
    // Return
    return;
}


/***********************************************************************//**
 * @brief Handles registered client information requests
 *
 * @param[in] xml XML message sent by client.
 * @param[in] sock Socket.
 *
 * Handles all incoming registered client information requests.
 ***************************************************************************/
void GVOHub::request_get_registered_clients(const GXml& xml, const socklen_t& sock)
{
    // Header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::request_get_registered_clients" << std::endl;
    #endif

    // Get client key
    std::string key = get_client_key(xml);

    // Declare message
    std::string msg = "";
    // Set response
    msg.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    msg.append("<methodResponse>\n");
    msg.append("<params>\n");
    msg.append("  <param><value><array><data>\n");
    msg.append("    <value>gammalib_hub</value>\n");

    // Loop over all clients. Do not send back current client's registration
    for (int i = 0; i < m_clients.size(); ++i) {
        if (m_clients[i].private_key != key) {
            msg.append("    <value>");
            msg.append(m_clients[i].reference);
            msg.append("</value>\n");
        }
    }
    
    // Finish response
    msg.append("  </data></array></value></param>\n");
    msg.append("</params>\n");
    msg.append("</methodResponse>\n");
    // Post response
    post_string(msg, sock);
    
    // Return
    return;
  
}


/***********************************************************************//**
 * @brief Handles subscribed client information requests
 *
 * @param[in] xml XML message sent by client.
 * @param[in] sock Socket.
 *
 * Handles all incoming subscribed client information requests.
 ***************************************************************************/
void GVOHub::request_get_subscribed_clients(const GXml& xml, const socklen_t& sock)
{
    // Header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::request_get_subscribed_clients" << std::endl;
    #endif

    // Declare message
    std::string msg = "";    

    msg.append("<?xml version=\'1.0\' encoding=\"UTF-8\"?>\n");
    msg.append("<methodResponse>\n");
    msg.append("<params>\n");
    msg.append("  <param><value><struct><member><name>c0</name><value><struct></struct></value></member><member><name>gammalib_hub</name><value><struct></struct></value></member></struct></value></param></params></methodResponse>");

/*
    std::string buffer;
    const int n = 1000; 
    char      line[n];
    FILE* fptr = fopen("SAMP-registered.txt", "r");
    if (fptr != NULL) {
        while (fgets(line, n, fptr) != NULL) {

                // Convert line to C++ string
                std::string cline = std::string(line);

                // Check for secret key
                if (cline.compare(0, 10, "Registered") == 0) {
                    buffer = gammalib::strip_chars(cline.substr(10, std::string::npos), "\r\n");
                }
    }
    
    // Closes file
    fclose(fptr);
*/

    // Post response
    post_string(msg, sock);
    // Post void message
    //post_samp_void(sock);
    
    // Return
    return;
}


/***********************************************************************//**
 * @brief Handles a metadata requests
 *
 * @param[in] xml XML message sent by client.
 * @param[in] sock Socket.
 *
 * Handles all metadata requests.
 ***************************************************************************/
void GVOHub::request_get_metadata(const GXml& xml, const socklen_t& sock)
{
    // Header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::request_get_metadata" << std::endl;
    #endif

    // Initialise client name
    std::string client_name = "";

    // Get the client name
    const GXmlNode* node = xml.element("methodCall > params > param[1] > value");
    if (node != NULL) {
        const GXmlText* text = static_cast<const GXmlText*>((*node)[0]);
        if (text != NULL) {
            client_name = text->text();
        }
    }

    // Declare response
    std::string response = "";

    // Set response
    response.append("<?xml version='1.0' encoding='UTF-8'?>\n");
    response.append("<methodResponse>\n");
    response.append("<params>\n");
    response.append("  <param><value><struct>\n");
    response.append("    <member>\n");
    response.append("      <name>samp.status</name>\n");
    response.append("      <value>samp.ok</value>\n");
    response.append("    </member>\n");

    // If key is "gammalib_hub" then return some special information
    if (client_name == "gammalib_hub") {
		response.append("    <member>\n");
        response.append("      <name>samp.name</name>\n");
        response.append("      <value>gammalib_hub</value>\n");
        response.append("    </member>\n");
   		response.append("    <member>\n");
        response.append("      <name>samp.description.text</name>\n");
        response.append("      <value>GammaLib VO Hub</value>\n");
        response.append("    </member>\n");
		response.append("    <member>\n");
        response.append("      <name>samp.icon.url</name>\n");
        response.append("      <value>http://a.fsdn.com/allura/p/gammalib/icon</value>\n");
        response.append("    </member>\n");
		response.append("    <member>\n");
        response.append("      <name>samp.documentation.url</name>\n");
        response.append("      <value>http://cta.irap.omp.eu/gammalib/user_manual/modules/vo.html</value>\n");
        response.append("    </member>\n");
		response.append("    <member>\n");
        response.append("      <name>author.affiliation</name>\n");
        response.append("      <value>IRAP, Toulouse, France</value>\n");
        response.append("    </member>\n");
		response.append("    <member>\n");
        response.append("      <name>author.email</name>\n");
        response.append("      <value>jurgen.knodlseder@irap.omp.eu</value>\n");
        response.append("    </member>\n");
		response.append("    <member>\n");
        response.append("      <name>author.name</name>\n");
        response.append("      <value>J. Knoedlseder, T. Louge</value>\n");
        response.append("    </member>\n");
		response.append("    <member>\n");
        response.append("      <name>home.page</name>\n");
        response.append("      <value>http://cta.irap.omp.eu/gammalib/</value>\n");
        response.append("    </member>\n");
    }

    // ... otherwise get the index
    else {
 
        // Get client index
        int i = get_client_index(client_name);

        // Continue only if index is valid
        if (i != -1) {

            // Append response
            response.append("    <member>\n");
            response.append("      <name>samp.name</name>\n");
            response.append("      <value>"+m_clients[i].name+"</value>\n");
            response.append("    </member>\n");
            response.append("    <member>\n");
            response.append("      <name>samp.description.text</name>\n");
            response.append("      <value>"+m_clients[i].description+"</value>\n");
            response.append("    </member>\n");
            response.append("    <member>\n");
            response.append("      <name>samp.icon.url</name>\n");
            response.append("      <value>"+m_clients[i].icon+"</value>\n");
            response.append("    </member>\n");
            response.append("    <member>\n");
            response.append("      <name>samp.documentation.url</name>\n");
            response.append("      <value>"+m_clients[i].documentation+"</value>\n");
            response.append("    </member>\n");
            response.append("    <member>\n");
            response.append("      <name>author.affiliation</name>\n");
            response.append("      <value>"+m_clients[i].affiliation+"</value>\n");
            response.append("    </member>\n");
            response.append("    <member>\n");
            response.append("      <name>author.email</name>\n");
            response.append("      <value>"+m_clients[i].email+"</value>\n");
            response.append("    </member>\n");
            response.append("    <member>\n");
            response.append("      <name>author.name</name>\n");
            response.append("      <value>"+m_clients[i].author_name+"</value>\n");
            response.append("    </member>\n");
            response.append("    <member>\n");
            response.append("      <name>home.page</name>\n");
            response.append("      <value>"+m_clients[i].homepage+"</value>\n");
            response.append("    </member>\n");

        } // endif: index was valid
        
    } // endelse: client was not the hub

    // Finish response
    response.append("  </struct></value></param>\n");
    response.append("</params>\n");
    response.append("</methodResponse>\n");
    
    // Post response
    post_string(response, sock);
   
    // Return
    return;
}

/***********************************************************************//**
 * @brief broadcasts a message
 *
 * @param[in] xml XML message sent by client.
 * @param[in] sock Socket.
 *
 * broadcasts an image to every registered client
 ***************************************************************************/
void GVOHub::broadcast(const GXml& xml, const socklen_t& sock)
{
    // Header
   
    // Get client index
    int i = get_client_index(xml);
    // Get message mtype
    std::string mtype = get_mtype(xml);
    #if defined(G_CONSOLE_DUMP)
    std::cout<<"mtype is: " +mtype + " i value: " + gammalib::str(i)<<std::endl;
    #endif
    // Continue only if index is valid
    //if (i != -1) {
        // Post void message
        post_samp_void(sock);
	if (mtype == "image.load.fits") {
	    #if defined(G_CONSOLE_DUMP)
	    std::cout<<"notifying image.load.fits"<<std::endl;
            #endif
	    // Send notifications
	    send_notifications("image.load.fits",
			       m_clients[i].reference,xml);
	}
	if (mtype == "table.load.votable") {
	    // Send notifications
	    send_notifications("table.load.votable",
			       m_clients[i].reference,xml);
	}
        
	//} // endif: valid client found
    #if defined(G_CONSOLE_DUMP)
    std::cout<<"Returning from broadcast function"<<std::endl;
    #endif
    // Return
    return;
  
}

/***********************************************************************//**
 * @brief Handles Hub shutdown requests
 *
 * @param[in] sock Socket.
 *
 * Handles all incoming Hub shutdown requests.
 ***************************************************************************/
void GVOHub::request_shutdown(const socklen_t& sock)
{
    // Header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::request_shutdown" << std::endl;
    #endif

    // Set shutdown flag
    m_shutdown = true;
    
    // Post SAMP ok
    post_samp_ok(sock);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Extract client key from XML request
 *
 * @param[in] xml XML message sent by client.
 *
 * Extracts the clients key from the XML request.
 ***************************************************************************/
std::string GVOHub::get_client_key(const GXml& xml) const
{
    // Header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::get_client_key" << std::endl;
    #endif

    // Initialise response
    std::string client_key = "";

    // Get the client's private key
    const GXmlNode* node = xml.element("methodCall > params > param > value");
    if (node != NULL) {
        const GXmlText* text = static_cast<const GXmlText*>((*node)[0]);
        if (text != NULL) {
            client_key = text->text();
        }
    }

    // Return key
    return client_key;
}


/***********************************************************************//**
 * @brief Extract client index in shared memory from XML request
 *
 * @param[in] xml XML message sent by client.
 * @return Client index (-1 if not found).
 *
 * Extracts the client index from the XML request. The method returns -1 if
 * no client was found.
 ***************************************************************************/
int GVOHub::get_client_index(const GXml& xml) const
{
    // Header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::get_client_index" << std::endl;
    #endif

    // Initialise index
    int index = -1;

    // Get the client's private key
    std::string key = get_client_key(xml);

    // Continue only if string is not empty
    if (!key.empty()) {

        // Searches for key in clients
        for (int i = 0; i < m_clients.size(); ++i) {
            if (m_clients[i].private_key == key) {
                index = i;
                break;
            }
        }

    } // endif: key was not empty

    // Return index
    return index;
}


/***********************************************************************//**
 * @brief Extract client index in shared memory from XML request
 *
 * @param[in] reference Client reference.
 * @return Client index (-1 if not found).
 *
 * Extracts the client index from the client reference. The method returns -1
 * if no client was found.
 ***************************************************************************/
int GVOHub::get_client_index(const std::string& reference) const
{
    // Header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::get_client_index" << std::endl;
    #endif

    // Initialise index
    int index = -1;

    // Search for index
    for (int i = 0; i < m_clients.size(); ++i) {
        if (m_clients[i].reference == reference) {
            index = i;
            break;
        }
    }

    // Return index
    return index;
}


/***********************************************************************//**
 * @brief Returns value for a SAMP client query parameter
 *
 * @param[in] xml client query XML document.
 * @param[in] name Parameter name.
 * @return Parameter value.
 *
 * Returns value for a SAMP client query parameter. If the specified
 * parameter was not found or if the response structure is not compliant,
 * an empty string is returned.
 ***************************************************************************/
std::string GVOHub::get_response_value(const GXml&        xml,
                                       const std::string& name) const
{
    // Declare value
    std::string value = "";

    // Get the client's private key
    const GXmlNode* node = xml.element("methodCall > params > param[1] > value > struct");
    if (node != NULL) {
        int num = node->elements("member");            
        for (int i = 0; i < num; ++i) {
            const GXmlNode* member = node->element("member", i);
            std::string one_name;
            std::string one_value;
            get_name_value_pair(member, one_name, one_value);
            if (one_name == name) {
                value = one_value;
                break;
            }
        }
        
    }

    // Return value
    return value;
}


/***********************************************************************//**
 * @brief Extract name / value pair from XML node
 *
 * @param[in] node Pointer to XML node.
 * @param[out] name Name string.
 * @param[out] value Value string.
 *
 * Extracts a name / value pair from a XML node. If the XML node pointer is
 * NULL, the name and value strings will be empty.
 ***************************************************************************/
void GVOHub::get_name_value_pair(const GXmlNode* node,
                                 std::string&    name,
                                 std::string&    value) const
{
    // Clear name and value strings
    name.clear();
    value.clear();

    // Continue only if node is valid
    if (node != NULL) {

        // Get name node and extract text content
        const GXmlNode* ptr = node->element("name", 0);
        if (ptr != NULL) {
            const GXmlText* text = static_cast<const GXmlText*>((*ptr)[0]);
            if (text != NULL) {
                name = text->text();
            }
        }

        // Get value node and extract text content
        ptr = node->element("value", 0);
        if (ptr != NULL) {
            const GXmlText* text = static_cast<const GXmlText*>((*ptr)[0]);
            if (text != NULL) {
                value = text->text();
            }
        }
    }

    // Return
    return;
}


/***********************************************************************//**
 * @brief Returns subscriptions from XML document
 *
 * @param[in] xml client query XML document.
 * @return List of subscriptions.
 ***************************************************************************/
std::vector<std::string> GVOHub::get_subscriptions(const GXml& xml) const                                         
{
    // Declare subscriptions
    std::vector<std::string> subscriptions;

    // Get the client's private key
    const GXmlNode* node = xml.element("methodCall > params > param[1] > value > struct");
    if (node != NULL) {
        int num = node->elements("member");
        for (int i = 0; i < num; ++i) {
            const GXmlNode* member = node->element("member", i);
            if (member != NULL) {
                const GXmlNode* name = member->element("name", 0);
                if (name != NULL) {
                    const GXmlText* text = static_cast<const GXmlText*>((*name)[0]);
                    if (text != NULL) {
                        subscriptions.push_back(text->text());
                    }
                }
            }
        }
    }

    // Return subscriptions
    return subscriptions;
}


/***********************************************************************//**
 * @brief Returns callback URL of client
 *
 * @param[in] xml client query XML document.
 * @return Callback URL of client.
 ***************************************************************************/
std::string GVOHub::get_callback_url(const GXml& xml) const                                         
{
    // Declare URL
    std::string url;

    // Get the client's private key
    const GXmlNode* node = xml.element("methodCall > params > param[1] > value");
    if (node != NULL) {
		const GXmlText* text = static_cast<const GXmlText*>((*node)[0]);
        if (text != NULL) {
		    url.append(text->text());
        }
    }

    // Return URL
    return url;
}


/***********************************************************************//**
 * @brief Returns SAMP Hub lockfile URL
 *
 * @return SAMP Hub lockfile URL (empty if no lockfile was found).
 *
 * Implements IVOA standard REC-SAMP-1.3-20120411.
 ***************************************************************************/
std::string GVOHub::get_hub_lockfile(void) const
{
    // Initialise result
    std::string url = "";

    // Check for existence of the SAMP_HUB environment variable first
    char* hub_ptr = std::getenv("SAMP_HUB");
    if (hub_ptr != NULL) {

        // Check for mandatory std-lockurl: prefix (no other prefixe is
        // supported so far)
        std::string lockurl = std::string(hub_ptr);
        if (lockurl.compare(0, 12, "std-lockurl:") == 0) {

            // Extract URL
            url = lockurl.substr(12, std::string::npos);

        } // endif: std-lockurl: prefix found
  
    }

    // ... otherwise the lockfile should be $HOME/.samp
    else {

        // Get user's HOME directory path as the prefix of the full
        // path. If the HOME environment variable is not set we
        // expect that .samp is in the local directory. This is non
        // standard, but prevents for creating an exception here.
        std::string prefix = "";
        char* home_ptr = std::getenv("HOME");
        if (home_ptr != NULL) {
            prefix = std::string(home_ptr) + "/";
        }

        // Set filename
        url = prefix + ".samp";

    } // endelse: no SAMP_HUB environment variable found

    // Return URL
    return url;
}


/***********************************************************************//**
 * @brief Send notifications
 *
 * @param[in] method Name of the method
 * @param[in] client Reference of the client
 *
 * The method send notifications to all registered clients that request so.
 ***************************************************************************/
void GVOHub::send_notifications(const std::string& method,
                                const std::string& client)
{
     #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::send_notifications 1st form" << std::endl;
    #endif
    // Loop over all clients
    for (int i = 0; i < m_clients.size(); ++i) {
    
        // Loop over all methods
        for (int j = 0; j < m_clients[i].subscriptions.size(); ++j) {

            // Continue only if method matches
            if (method == m_clients[i].subscriptions[j]) {
    
                // Declare notification
                std::string msg = "";

                // Register
                if (method == "samp.hub.event.register") {

                    // Set response for samp.hub.event.register
                    msg.append("<?xml version=\"1.0\"?>\n");
                    msg.append("<methodCall>\n");
                    msg.append("<methodName>samp.client.receiveNotification</methodName>\n");
                    msg.append("<params>\n");
                    msg.append("  <param><value>");
                    msg.append(m_clients[i].private_key);
                    msg.append("</value></param>\n");
                    msg.append("  <param><value>"+m_hub_id+"</value></param>\n");
                    msg.append("  <param><value><struct>\n");
                    msg.append("    <member>\n");
                    msg.append("      <name>samp.mtype</name>\n");
                    msg.append("      <value>samp.hub.event.register</value>\n");
                    msg.append("    </member>\n");
                    msg.append("    <member>\n");
                    msg.append("      <name>samp.params</name>\n");
                    msg.append("      <value><struct>\n");
                    msg.append("        <member>\n");
                    msg.append("          <name>id</name>\n");
                    msg.append("          <value>"+client+"</value>\n");
                    msg.append("        </member>\n");
                    msg.append("      </struct></value>\n");
                    msg.append("    </member>\n");
                    msg.append("  </struct></value></param>\n");
                    msg.append("</params>\n");
                    msg.append("</methodCall>\n");
                    
                    // Post notification
                    notify(m_clients[i].url, msg);
                    
                }
               
                // Unregister
                else if (method == "samp.hub.event.unregister") {

                    // Set response for samp.hub.event.unregister
                    msg.append("<?xml version=\"1.0\"?>\n");
                    msg.append("<methodCall>\n");
                    msg.append("<methodName>samp.client.receiveNotification</methodName>\n");
                    msg.append("<params>\n");
                    msg.append("  <param><value>");
                    msg.append(m_clients[i].private_key);
                    msg.append("</value></param>\n");
                    msg.append("  <param><value>");
                    msg.append(m_hub_id);
                    msg.append("</value></param>\n");
                    msg.append("  <param><value><struct>\n");
                    msg.append("    <member>\n");
                    msg.append("      <name>samp.mtype</name>\n");
                    msg.append("      <value>samp.hub.event.unregister</value>\n");
                    msg.append("    </member>\n");
                    msg.append("    <member>\n");
                    msg.append("      <name>samp.params</name>\n");
                    msg.append("      <value><struct>\n");
                    msg.append("        <member>\n");
                    msg.append("          <name>id</name>\n");
                    msg.append("          <value>"+client+"</value>\n");
                    msg.append("        </member>\n");
                    msg.append("      </struct></value>\n");
                    msg.append("    </member>\n");
                    msg.append("  </struct></value></param>\n");
                    msg.append("</params>\n");
                    msg.append("</methodCall>\n");
                        
                    // Post notification
                    notify(m_clients[i].url, msg);
					
                }
                    
                // Metadata
			    else if (method == "samp.hub.event.metadata") {

                    // Get index of client
                    int k;
                    for (k = 0; k < m_clients.size(); ++k) {
                        if (m_clients[k].reference == client) {
                            break;
                        }
                    }

                    // Fall through if client index is not valid
                    if (k >= m_clients.size()) {
                        continue;
                    }

                    // Set response for samp.hub.event.metadata
                    msg.append("<?xml version=\"1.0\"?>\n");
                    msg.append("<methodCall><methodName>samp.client.receiveNotification</methodName>\n");
                    msg.append("<params>\n");
                    msg.append("  <param><value>");
                    msg.append(m_clients[i].private_key);
                    msg.append("</value></param>\n");
                    msg.append("  <param><value>"+m_hub_id+"</value></param>\n");
                    msg.append("  <param><value><struct>\n");
                    msg.append("    <member>\n");
                    msg.append("      <name>samp.mtype</name>\n");
                    msg.append("      <value>samp.hub.event.metadata</value>\n");
                    msg.append("    </member>\n");
                    msg.append("    <member>\n");
                    msg.append("      <name>samp.params</name>\n");
                    msg.append("      <value><struct>\n");
                    msg.append("        <member>\n");
                    msg.append("          <name>id</name>\n");
                    msg.append("          <value>"+m_clients[k].reference+"</value>\n");
                    msg.append("        </member>\n");
                    msg.append("        <member>\n");
                    msg.append("          <name>metadata</name>\n");
                    msg.append("          <value><struct>\n");
                    msg.append("            <member>\n");
                    msg.append("              <name>samp.name</name>\n");
                    msg.append("              <value>"+m_clients[k].name+"</value>\n");
                    msg.append("            </member>\n");
                    msg.append("            <member>\n");
                    msg.append("              <name>samp.description.text</name>\n");
                    msg.append("              <value>"+m_clients[k].description+"</value>\n");
                    msg.append("            </member>\n");
                    msg.append("            <member>\n");
                    msg.append("              <name>samp.icon.url</name>\n");
                    msg.append("              <value>"+m_clients[k].icon+"</value>\n");
                    msg.append("            </member>\n");
                    msg.append("            <member>\n");
                    msg.append("              <name>samp.documentation.url</name>\n");
                    msg.append("              <value>"+m_clients[k].documentation+"</value>\n");
                    msg.append("            </member>\n");
                    msg.append("            <member>\n");
                    msg.append("              <name>author.affiliation</name>\n");
                    msg.append("              <value>"+m_clients[k].affiliation+"</value>\n");
                    msg.append("            </member>\n");
                    msg.append("            <member>\n");
                    msg.append("              <name>author.name</name>\n");
                    msg.append("              <value>"+m_clients[k].author_name+"</value>\n");
                    msg.append("            </member>\n");
                    msg.append("            <member>\n");
                    msg.append("              <name>author.email</name>\n");
                    msg.append("              <value>"+m_clients[k].email+"</value>\n");
                    msg.append("            </member>\n");
                    msg.append("            <member>\n");
                    msg.append("              <name>home.page</name>\n");
                    msg.append("              <value>"+m_clients[k].homepage+"</value>\n");
                    msg.append("            </member>\n");
                    msg.append("          </struct></value>\n");
                    msg.append("        </member>\n");				
                    msg.append("      </struct></value>\n");
                    msg.append("    </member>\n");
                    msg.append("  </struct></value></param>\n");
                    msg.append("</params>\n");
                    msg.append("</methodCall>\n");
                        
                    // Post notification
                    notify(m_clients[i].url, msg);
					
	      } // endelse: metadata

            } // endif: method was requested one

        } // endfor: looped over all methods

    } // endfor: looped over all clients
    
    // Return
    return;
}
/***********************************************************************//**
 * @brief Send notifications
 *
 * @param[in] method Name of the method
 * @param[in] client Reference of the client
 * @param[in] xml message sent by the client
 *
 * The method send notifications to all registered clients that request so.
 ***************************************************************************/
void GVOHub::send_notifications(const std::string& method,
                                const std::string& client,
				const GXml& xml)
{
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::send_notifications 2nd form" << std::endl;
    #endif
    // Loop over all clients
    for (int i = 0; i < m_clients.size(); ++i) {
    
        // Loop over all methods
        for (int j = 0; j < m_clients[i].subscriptions.size(); ++j) {

            // Continue only if method matches
            if (method == m_clients[i].subscriptions[j]) {
    
                // Declare notification
                std::string msg = "";

                if (method == "image.load.fits") {
		    #if defined(G_CONSOLE_DUMP)
		    std::cout << "GVOHub:: Preparing broadcast message" << std::endl;
                    #endif
		   // Set response for image.load.fits
                    msg.append("<?xml version=\"1.0\"?>\n");
                    msg.append("<methodCall>\n");
                    msg.append("<methodName>samp.client.receiveNotification</methodName>\n");
                    msg.append("<params>\n");
                    msg.append("  <param><value>");
                    msg.append(m_clients[i].private_key);
                    msg.append("</value></param>\n");
                    msg.append("  <param><value>");
                    msg.append(m_hub_id);
                    msg.append("</value></param>\n");
                    msg.append("  <param><value><struct>\n");
                    msg.append("    <member>\n");
                    msg.append("      <name>samp.mtype</name>\n");
                    msg.append("      <value>image.load.fits</value>\n");
                    msg.append("    </member>\n");
                    msg.append("    <member>\n");
                    msg.append("      <name>samp.params</name>\n");
                    msg.append("      <value><struct>\n");
                    msg.append("        <member>\n");
                    msg.append("          <name>name</name>\n");
                    msg.append("          <value>Gammalib_shared_fits</value>\n");
                    msg.append("        </member>\n");
		    msg.append("        <member>\n");
                    msg.append("          <name>image-id</name>\n");
                    msg.append("          <value>Gammalib_shared_fits_id</value>\n");
                    msg.append("        </member>\n");
		    msg.append("        <member>\n");
                    msg.append("          <name>url</name>\n");
                    msg.append("          <value>http://127.0.0.1:2526/get_fits</value>\n");
                    msg.append("        </member>\n");
                    msg.append("      </struct></value>\n");
                    msg.append("    </member>\n");
                    msg.append("  </struct></value></param>\n");
                    msg.append("</params>\n");
                    msg.append("</methodCall>\n");
                    #if defined(G_CONSOLE_DUMP)
		    std::cout << msg << std::endl;
                    #endif   
                    // Post notification
                    notify(m_clients[i].url, msg);
		  
		}
            } // endif: method was requested one

        } // endfor: looped over all methods

    } // endfor: looped over all clients
    
    // Return
    return;
}

/***********************************************************************//**
 * @brief Creates the lockfile, fill it
 *
 * Implements IVOA standard REC-SAMP-1.3-20120411.
 ***************************************************************************/
void GVOHub::create_samp_file(void) const
{
    // Get lockfile URL
    std::string lockurl = get_hub_lockfile();

    // Open SAMP lockfile. Continue only if opening was successful
    FILE* fptr = fopen(lockurl.c_str(), "w");

    // Successful?
    if (fptr != NULL) {

        // Write lockfile
        fprintf(fptr, "# SAMP lockfile\n");
        fprintf(fptr, "# Required keys:\n");
        fprintf(fptr, "samp.secret=%s\n", m_secret.c_str());
        fprintf(fptr, "samp.hub.xmlrpc.url=%s\n", m_hub_url.c_str());
        fprintf(fptr, "samp.profile.version=%s\n", m_version.c_str());
        fprintf(fptr, "# Info stored by hub for some private reason:\n");
        fprintf(fptr, "gammalib.hubid=%s\n", m_hub_id.c_str());
        
        // Close lockfile
        fclose(fptr);

    }

    // Return
    return;
}


/***********************************************************************//**
 * @brief Post string content to client
 *
 * @param[in] content String content to post.
 * @param[in] sock Socket.
 *
 * Posts the content of a string to a client.
 ***************************************************************************/
void GVOHub::post_string(const std::string& content, const socklen_t& sock) const
{
    // Continue only if socket is valid
    if (sock != -1) {

        // Determine content length
        int length = content.length();

        // Set prefix (note that the response has no POST!)
        std::string prefix = "HTTP/1.1 200 OK\n"
                             "Connection: close\n"
                             "Content-Type: text/xml\n"
                             "Content-Length: "+gammalib::str(length)+"\n\n";


        // Build post string
        std::string post = prefix + content;

        // Dump message to post
        #if defined(G_SHOW_MESSAGE)
        std::cout << std::endl;
        std::cout << "GVOHub response:" << std::endl;
        std::cout << "================" << std::endl;
        std::cout << post << std::endl;
        #endif

        // Send content to socket
        bool done = false;
        do {
            int length      = post.length();
            int sent_length = send(sock, post.c_str(), length, 0);
            if (sent_length < length) {
                post = post.substr(sent_length, std::string::npos);
            }
            else {
                done = true;
            }
        } while (!done);
	
    } // endif: socket was valid

    // Return
    return;
}


/***********************************************************************//**
 * @brief Post SAMP ok massage to client
 *
 * @param[in] sock Socket.
 *
 * Posts a SAMP OK message to a client.
 ***************************************************************************/
void GVOHub::post_samp_ok(const socklen_t& sock) const
{
    // Declare response
    std::string response = "";

    // Compose response
    response.append("<?xml version='1.0' encoding='UTF-8'?>\n");
    response.append("<methodResponse>\n");
    response.append("<params>\n");
    response.append("  <param><value><struct>\n");
    response.append("    <member>\n");
    response.append("      <name>samp.status</name>\n");
    response.append("      <value>samp.ok</value>\n");
    response.append("    </member>\n");
    response.append("  </struct></value></param>\n");
    response.append("</params>\n");
    response.append("</methodResponse>\n");
    
    // Post string
    post_string(response, sock);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Post SAMP void massage to client
 *
 * @param[in] sock Socket.
 *
 * Posts a void SAMP message to a client. Void messages can typically be
 * discared by the client.
 ***************************************************************************/
void GVOHub::post_samp_void(const socklen_t& sock) const
{
    // Declare response
    std::string response = "";

    // Compose response
    response.append("<?xml version='1.0' encoding='UTF-8'?>\n");
    response.append("<methodResponse>\n");
    response.append("  <params>\n");
    response.append("    <param>\n");
    response.append("      <value/>\n");
    response.append("    </param>\n");
    response.append("  </params>\n");
    response.append("</methodResponse>\n");
    
    // Post string
    post_string(response, sock);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Send notification to client
 *
 * @param[in] url URL.
 * @param[in] notification Notification.
 *
 * Send a @p notification to a @p url.
 ***************************************************************************/
void GVOHub::notify(const std::string& url,
                    const std::string& notification) const
{
    // Initalise socket
    int socket = -1;

    // Extract host, port and path from URL
    std::string host = "127.0.0.1";
    std::string port = "2525";
    std::string path = "xmlrpc";
    if (url.compare(0, 7, "http://") == 0) {
        size_t length;
        size_t start = 7;
        size_t stop  = url.find(":", start);
        size_t end   = std::string::npos;
        if (stop != std::string::npos) {
            length = stop - start;
        }
        else {
            length = std::string::npos;
        }
        host = url.substr(start, length);
        if (stop != std::string::npos) {
            stop++;
            end  = url.find("/", stop);
            if (end != std::string::npos) {
                length = end - stop;
            }
            else {
                length = std::string::npos;
            }
            port = url.substr(stop, length);
        }
        if (end != std::string::npos) {
            end++;
            length = url.length() - end;
            path   = url.substr(end, length);
        }
    }

    // Set hints
    struct addrinfo hints;
    std::memset(&hints, 0, sizeof(hints));
    hints.ai_family   = AF_INET;
    hints.ai_socktype = SOCK_STREAM;

    // Get server information
    struct addrinfo* servinfo;
    if (getaddrinfo(host.c_str(), port.c_str(), &hints, &servinfo) == 0) {

        // Loop through all the results and connect to the first we can
        for (struct addrinfo* ptr = servinfo; ptr != NULL; ptr = ptr->ai_next) {

            // Create socket
            socket = ::socket(ptr->ai_family,
                              ptr->ai_socktype,
                              ptr->ai_protocol);

            // Connect to socket if socket is valid
            if (socket != -1) {
                if (::connect(socket,
                              ptr->ai_addr,
                              ptr->ai_addrlen) == -1) {
                    close(socket);
                    socket = -1;
                }
                else {
                    // Socket connection successful, break now
                    break;
                }
            }

        } // endfor: looped through all results

    } // endif: server information was valid

    // Continue only if socket is valid
    if (socket != -1) {

        // Determine notification length
        int length = notification.length();

        // Set prefix
        std::string prefix = "POST /"+path+" HTTP/1.0\n"
                             "Connection: close\n"
                             "User-Agent: GammaLib\n"
                             "Content-Type: text/xml\n"
                             "Content-Length: "+gammalib::str(length)+"\n\n";

        // Build post string
        std::string post = prefix + notification;

        // Dump message to post
        #if defined(G_SHOW_MESSAGE)
        std::cout << std::endl;
        std::cout << "GVOHub sends following notification:" << std::endl;
        std::cout << "====================================" << std::endl;
        std::cout << post << std::endl;
        #endif

        // Send content to socket
        bool done = false;
        do {
            int length      = post.length() + 1; // +1 for terminating 0
            int sent_length = send(socket, post.c_str(), length, 0);
            if (sent_length < length) {
                post = post.substr(sent_length, std::string::npos);
            }
            else {
                done = true;
            }
        } while (!done);

        /*
        // Declare response
        std::string response = "";

        // Read buffer until it is empty
        char buffer[1001];
        int timeout = 1000; // Initial timeout is 1 sec
        int n       = 0;
        do {
            n = gammalib::recv(socket, buffer, 1000, 0, timeout);
            if (n > 0) {
                buffer[n+1] = '\0';
                response.append(std::string(buffer));
            }
            timeout = 10; // The timeout now is 0.01 sec 
        } while (n > 0);
        */

        // Close socket
        close(socket);

    }

    // Return
    return;
}


/***********************************************************************//**
 * @brief Generates random string of characters
 *
 * @param[in] length Length of random string
 ***************************************************************************/
std::string GVOHub::random_string(const size_t& length) const
{
    srand(time(0));
    std::string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    int pos;
    while(str.size() != length) {
        pos = ((rand() % (str.size() - 1)));
        str.erase (pos, 1);
    }
   
    // Return string
    return str;
}
/***********************************************************************//**
 * @brief Extract mtype from XML request
 *
 * @param[in] xml XML message sent by client.
 *
 * Extracts the mtype identifying calling message from the XML request.
 ***************************************************************************/
std::string GVOHub::get_mtype(const GXml& xml) const
{
    // Header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::get_mtype" << std::endl;
    #endif

    // Initialise response
    std::string client_key = "";

    // Get the client's private key
    const GXmlNode* node = xml.element("methodCall > params > param > value");
    if (node != NULL) {
        const GXmlText* text = static_cast<const GXmlText*>((*node)[0]);
        if (text != NULL) {
            client_key = text->text();
        }
    }

    // Return key
    return client_key;
}
/***********************************************************************//**
 * @brief Extract client destination from XML request
 *
 * @param[in] xml XML message sent by client.
 *
 * Extracts identifier of destination client from the XML request.
 ***************************************************************************/
std::string GVOHub::get_destination(const GXml& xml) const
{
    // Header
    #if defined(G_CONSOLE_DUMP)
    std::cout << "GVOHub::get_mtype" << std::endl;
    #endif

    // Initialise response
    std::string client_key = "";

    // Get the client's private key
    const GXmlNode* node = xml.element("methodCall > params > param > value");
    if (node != NULL) {
        const GXmlText* text = static_cast<const GXmlText*>((*node)[0]);
        if (text != NULL) {
            client_key = text->text();
        }
    }

    // Return key
    return client_key;
}