summaryrefslogtreecommitdiffstats
path: root/database/sqlite/administration.c
blob: a27c22017103e794d754a955123dd626f2cb4c43 (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
/* administration.c  --  Functions needed for administration tasks
 *
 *  GPLv2 only - Copyright (C) 2008, 2009
 *               David Sommerseth <dazo@users.sourceforge.net>
 *
 *  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; version 2
 *  of the License.
 *
 *  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, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */

/**
 * @file   administration.c
 * @author David Sommerseth <dazo@users.sourceforge.net>
 * @date   2008-12-03
 *
 * @brief  Functions needed for the administration interface
 *
 */


#include <string.h>
#include <unistd.h>
#include <assert.h>

#include <libxml/tree.h>

/**
 * @{
 */
#ifndef DRIVERAPIVERSION
# define DRIVERAPIVERSION 2
#endif
/**
 * @}
 */

#include <sqlite3.h>

#include <eurephia_nullsafe.h>
#include <eurephia_context.h>
#include <eurephia_log.h>
#include <eurephia_xml.h>
#include <eurephia_values.h>
#include <eurephiadb_session_struct.h>
#include <eurephiadb_mapping.h>
#include <passwd.h>

#ifndef DRIVER_MODE
#define DRIVER_MODE
#endif
#include <eurephiadb_driver.h>

#include "sqlite.h"

#define FMAP_USERS              /**< fieldmapping.h: Include declaration of tbl_sqlite_users */
#define FMAP_CERTS              /**< fieldmapping.h: Include declaration of tbl_sqlite_certs */
#define FMAP_ADMINACCESS        /**< fieldmapping.h: Include declaration of tbl_sqlite_eurephiaadmacc */
#define FMAP_LASTLOG            /**< fieldmapping.h: Include declaration of tbl_sqlite_lastlog */
#include "fieldmapping.h"

#if (DRIVERAPIVERSION > 1) || defined(DOXYGEN)
/*
 *  API Version 2 functions
 *
 */

/**
 * Internal function.  String replace in a xmlChar based string
 *
 * @param str xmlChar input string
 * @param s   search for this character
 * @param r   replace the character with this one
 */
void xmlReplaceChars(xmlChar *str, char s, char r) {
        if( str != NULL ) {
                xmlChar *ptr = str;

                while( *ptr != '\0' ) {
                        if( *ptr == s ) {
                                *ptr = r;
                        }
                        ptr++;
                }
        }
}


/**
 * @copydoc eDBadminAuth()
 */
int eDBadminAuth(eurephiaCTX *ctx, const char *req_access, const char *uname, const char *pwd) {
        dbresult *res = NULL;
        char *crpwd = NULL, *dbpwd = NULL;
        char *activated = NULL, *deactivated = NULL, *blid = NULL;
        int uid = -1, access = 0;
        char interface;

        DEBUG(ctx, 20, "Function call: eDBadminAuth(ctx, '%s, '%s', 'xxxxxxxx')", req_access, uname);

        assert(ctx != NULL);

        switch( ctx->context_type ) {
        case ECTX_ADMIN_CONSOLE:
                interface = 'C';
                break;
        case ECTX_ADMIN_WEB:
                interface = 'W';
                break;
        default:
                eurephia_log(ctx, LOG_ERROR, 0, "Wrong eurephia context type (0x%04x)", ctx->context_type);
                return 0;
        }

        if( (strlen_nullsafe(uname) < 4) || (strlen_nullsafe(pwd) < 4) ) {
                eurephia_log(ctx, LOG_WARNING, 0, "User name and/or password is either null or less than 4 bytes");
                return 0;
        }

        //
        // Authenticate user and password
        //
        res = sqlite_query(ctx,
                           "SELECT activated, deactivated, bl.blid, "
                           "       password, uid "
                           "  FROM openvpn_users ou"
                           "  LEFT JOIN openvpn_blacklist bl USING (username)"
                           " WHERE ou.username = '%q'",
                           uname);

        if( res == NULL ) {
                eurephia_log(ctx, LOG_FATAL, 0, "Could not authenticate user against the database");
                return 0;
        }

        if( sqlite_get_numtuples(res) == 1 ) {
                activated   = sqlite_get_value(res, 0, 0);
                deactivated = sqlite_get_value(res, 0, 1);
                blid        = sqlite_get_value(res, 0, 2);
                dbpwd       = sqlite_get_value(res, 0, 3);
                uid         = atoi_nullsafe(sqlite_get_value(res, 0, 4));

                if( blid != NULL ) {
                        eurephia_log(ctx, LOG_WARNING, 0,
                                     "Your user account is BLACKLISTED.  You have no access.");
                        sqlite_free_results(res);
                        return 0;
                }

                if( activated == NULL ) {
                        eurephia_log(ctx, LOG_WARNING, 0, "Your user account is not yet activated.");
                        sqlite_free_results(res);
                        return 0;
                }

                if( deactivated != NULL ) {
                        eurephia_log(ctx, LOG_WARNING, 0, "Your user account is deactivated.");
                        sqlite_free_results(res);
                        return 0;
                }

                if( dbpwd == NULL ) {
                        eurephia_log(ctx, LOG_WARNING, 0, "Authentication failed. DB error.");
                        sqlite_free_results(res);
                        return 0;
                } else {
                        int pwdok = 0;
                        // Verify the password
                        crpwd = eurephia_pwd_crypt(ctx, pwd, dbpwd);
                        pwdok = ((crpwd != NULL) && (strcmp(crpwd, dbpwd) == 0) ? 1 : 0);
                        memset(crpwd, 0, strlen_nullsafe(crpwd));
                        memset(dbpwd, 0, strlen_nullsafe(dbpwd));
                        free_nullsafe(ctx, crpwd);
                        if( pwdok == 0 ) {
                                eurephia_log(ctx, LOG_WARNING, 0, "Authentication failed.");
                                sleep(2);
                                sqlite_free_results(res);
                                return 0;
                        }
                }
                sqlite_free_results(res);

                // Check if access level is granted
                // (SQLite do not handle advanced joins so well, so we need to
                //  do this check with an extra query)
                res = sqlite_query(ctx,
                                   "SELECT (count(*) = 1) AS access "
                                   "  FROM eurephia_adminaccess"
                                   " WHERE uid = '%i' AND interface = '%c' AND access = '%q'",
                                   uid, interface, req_access);
                if( res == NULL ) {
                        eurephia_log(ctx, LOG_FATAL, 0, "Could not check access level");
                        return 0;
                }
                access = atoi_nullsafe(sqlite_get_value(res, 0, 0));
                sqlite_free_results(res);

                if( access == 0 ) {
                        eurephia_log(ctx, LOG_WARNING, 0, "Your account is lacking privileges for this operation");
                        return 0;
                }
        } else {
                eurephia_log(ctx, LOG_WARNING, 0, "Authentication failed. No unique records found.");
                sqlite_free_results(res);
                sleep(2);
                return 0;
        }

        // If we reach this place, authentication was successful.  Return users uid
        return uid;
}


/**
 * @copydoc eDBadminValidateSession()
 */
int eDBadminValidateSession(eurephiaCTX *ctx, const char *sesskey, const char *req_access) {
        dbresult *res = NULL;
        int valid = 0, access = 0, expire_time = 0;
        char interface;

        DEBUG(ctx, 20, "Function call: eDBadminValidateSession(ctx, '%s, '%s')", sesskey, req_access);
        assert( (ctx != NULL) && (sesskey != NULL) );

        switch( ctx->context_type ) {
        case ECTX_ADMIN_CONSOLE:
                interface = 'C';
                break;
        case ECTX_ADMIN_WEB:
                interface = 'W';
                break;
        default:
                eurephia_log(ctx, LOG_ERROR, 0, "Wrong eurephia context type (0x%04x)", ctx->context_type);
                return 0;
        }

        // Check if the session is still valid (not expired) and that this session are allowed to access
        // the requested access level.
        expire_time = (60 * atoi_nullsafe(defaultValue(eGet_value(ctx->dbc->config, "eurephiadmin_autologout"),
                                                       "10")
                                          )
                       );
        res = sqlite_query(ctx,
                           "SELECT (strftime('%%s',CURRENT_TIMESTAMP)-strftime('%%s',last_action)) > %i AS exp,"
                           "       (access IS NOT NULL) AS access"
                           "  FROM eurephia_adminlog"
                           "  LEFT JOIN eurephia_adminaccess USING(uid,interface)"
                           " WHERE status IN (1,2)"
                           "       AND sessionkey = '%q'"
                           "       AND access = '%q'",
                           expire_time, sesskey, req_access);

        if( (res == NULL) ) {
                eurephia_log(ctx, LOG_FATAL, 0, "Could not validate session");
                return 0;
        }

        valid  = (atoi_nullsafe(sqlite_get_value(res, 0, 0)) == 0);
        access = (atoi_nullsafe(sqlite_get_value(res, 0, 1)) == 1);
        sqlite_free_results(res);

        // If still valid, update last_action
        if( valid && access ) {
                res = sqlite_query(ctx,
                                   "UPDATE eurephia_adminlog"
                                   "   SET last_action = CURRENT_TIMESTAMP, status = 2"
                                   " WHERE sessionkey = '%q'", sesskey);
                if( res == NULL ) {
                        eurephia_log(ctx, LOG_ERROR, 0, "Could not register session activity");
                }
                sqlite_free_results(res);

        } else {
                // If not valid, register session as auto-logged out

                res = sqlite_query(ctx,
                                   "UPDATE eurephia_adminlog"
                                   "   SET logout = CURRENT_TIMESTAMP, status = %i"
                                   " WHERE sessionkey = '%q'",
                                   (access ? 4 : 5), sesskey);
                if( res == NULL ) {
                        eurephia_log(ctx, LOG_ERROR, 0, "Could not register old session as logged out");
                }
                sqlite_free_results(res);

                // Delete session variables
                res = sqlite_query(ctx, "DELETE FROM openvpn_sessions WHERE sessionkey = '%q'",
                                   sesskey);
                if( res == NULL ) {
                        eurephia_log(ctx, LOG_ERROR, 0,
                                     "Could not delete session variables (%s))", sesskey);
                        return 0;
                }
                sqlite_free_results(res);

                if( !access ) {
                        eurephia_log(ctx, LOG_WARNING, 0, "Your user account is lacking privileges");
                }

        }
        return (valid && access);
}


/**
 * @copydoc eDBadminRegisterLogin()
 */
int eDBadminRegisterLogin(eurephiaCTX *ctx, eurephiaSESSION *session) {
        dbresult *res = NULL;
        char interface;
        int uid;

        DEBUG(ctx, 20, "Function call: eDBadminRegisterLogin(ctx, {session}'%s')", session->sessionkey);
        assert((ctx != NULL) && (session != NULL));

        switch( ctx->context_type ) {
        case ECTX_ADMIN_CONSOLE:
                interface = 'C'; break;
        case ECTX_ADMIN_WEB:
                interface = 'W'; break;
        default:
                eurephia_log(ctx, LOG_ERROR, 0, "Wrong eurephia context type (0x%04x)", ctx->context_type);
                return 0;
        }

        // Register login into eurephia_adminlog ... uid, login, interface, sessionkey
        uid = atoi_nullsafe(eGet_value(session->sessvals, "uid"));
        res = sqlite_query(ctx,
                           "INSERT INTO eurephia_adminlog "
                           "       (uid, interface, status, login, last_action, sessionkey) "
                           "VALUES ('%i','%c',1,CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '%q')",
                           uid, interface, session->sessionkey);
        if( !res ) {
                eurephia_log(ctx, LOG_FATAL, 0, "Could not manage to register the session in the database");
                return 0;
        }
        sqlite_free_results(res);
        return 1;
}


/**
 * @copydoc eDBadminLogout()
 */
int eDBadminLogout(eurephiaCTX *ctx, const char *sessionkey) {
        dbresult *res = NULL;

        DEBUG(ctx, 20, "Function call: eDBadminLogout(ctx, '%s')", sessionkey);
        assert((ctx != NULL) && (sessionkey != NULL));

        if( (ctx->context_type != ECTX_ADMIN_CONSOLE) && (ctx->context_type != ECTX_ADMIN_WEB) ) {
                eurephia_log(ctx, LOG_CRITICAL, 0,
                             "eurephia admin function call attempted with wrong context type");
                return 0;
        }

        // Update session as logged out
        res = sqlite_query(ctx,
                           "UPDATE eurephia_adminlog "
                           "   SET logout = CURRENT_TIMESTAMP, status = 3"
                           " WHERE sessionkey = '%q'",
                           sessionkey);
        if( !res ) {
                eurephia_log(ctx, LOG_FATAL, 0, "Could not manage to register the session as logged out");
                return 0;
        }
        sqlite_free_results(res);

        // Delete session variables
        res = sqlite_query(ctx, "DELETE FROM openvpn_sessions WHERE sessionkey = '%q'", sessionkey);
        if( res == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0,
                             "Could not delete session variables (%s))", sessionkey);
                return 0;
        }
        sqlite_free_results(res);

        return 1;
}


/**
 * @copydoc eDBadminGetUserList()
 */
xmlDoc *eDBadminGetUserList(eurephiaCTX *ctx, const char *sortkeys) {
        xmlDoc *userlist = NULL;
        xmlNode *root_n = NULL, *user_n = NULL;
        dbresult *res = NULL;
        char *dbsort = NULL, tmp[34];
        int i = 0;

        DEBUG(ctx, 20, "Function call: eDBadminGetUserList(ctx, '%s')", sortkeys);
        assert((ctx != NULL) && (ctx->dbc != 0));

        if( (ctx->context_type != ECTX_ADMIN_CONSOLE) && (ctx->context_type != ECTX_ADMIN_WEB) ) {
                eurephia_log(ctx, LOG_CRITICAL, 0,
                             "eurephia admin function call attempted with wrong context type");
                return NULL;
        }

        // Convert the input sort keys to the proper database field names
        dbsort = eDBmkSortKeyString(tbl_sqlite_users, sortkeys);

        // Query database for all users
        res = sqlite_query(ctx,
                           "SELECT username, activated, deactivated, last_accessed, uid"
                           "  FROM openvpn_users "
                           "ORDER BY %s", (sortkeys != NULL ? dbsort : "uid"));
        if( res == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Error querying the user database");
                return NULL;
        }

        // Prepare a list with all users
        memset(&tmp, 0, 34);
        eurephiaXML_CreateDoc(ctx, 1, "userlist", &userlist, &root_n);
        snprintf(tmp, 32, "%i", sqlite_get_numtuples(res));
        xmlNewProp(root_n, (xmlChar *)"usercount", (xmlChar *)tmp);

        // Register all records
        for( i = 0; i < sqlite_get_numtuples(res); i++ ) {
                user_n = xmlNewChild(root_n, NULL, (xmlChar *)"user", NULL);
                sqlite_xml_value(user_n, XML_ATTR, "uid",           res, i, 4);
                sqlite_xml_value(user_n, XML_NODE, "username",      res, i, 0);
                sqlite_xml_value(user_n, XML_NODE, "activated",     res, i, 1);
                sqlite_xml_value(user_n, XML_NODE, "deactivated",   res, i, 2);
                sqlite_xml_value(user_n, XML_NODE, "last_accessed", res, i, 3);
        }
        sqlite_free_results(res);

        // Return a user list
        return userlist;
}


/**
 * Internal function.  Adds a child node named \<flag\> to an xmlNode containing a flag value
 *
 * @param node     xmlNode pointer where to add the new flag
 * @param flagname String containing a name of the flag
 * @param flagged  Is the flag set or not.  The tag will only be added if the flag is set
 *
 * @return Returns the \c flagged value
 */
inline int xml_set_flag(xmlNode *node, char *flagname, int flagged) {
        if( flagged ) {
                xmlNewChild(node, NULL, (xmlChar *) "flag", (xmlChar *) flagname);
        }
        return flagged;
}


/**
 * @copydoc eDBadminGetUserInfo()
 */
xmlDoc *eDBadminGetUserInfo(eurephiaCTX *ctx, int infoType, xmlDoc *srch) {
        dbresult *uinf = NULL, *qres = NULL;
        eDBfieldMap *uinfo_map = NULL;
        int flag = 0, uid = 0;
        char *username = NULL;

        xmlDoc *doc = NULL;
        xmlNode *root_n = NULL, *info_n = NULL, *fieldmap = NULL;

        DEBUG(ctx, 20, "Function call: eDBadminGetUserUserInfo(ctx, %i, {xmlDoc})", infoType);
        assert( (ctx != NULL) && (srch != NULL) );

        if( (ctx->context_type != ECTX_ADMIN_CONSOLE) && (ctx->context_type != ECTX_ADMIN_WEB) ) {
                eurephia_log(ctx, LOG_CRITICAL, 0,
                             "eurephia admin function call attempted with wrong context type");
                return NULL;
        }

        fieldmap = eurephiaXML_getRoot(ctx, srch, "fieldMapping", 1);
        uinfo_map = eDBxmlMapping(ctx, tbl_sqlite_users, "u", fieldmap);

        // Query the database, find the user defined in the user map
        uinf = sqlite_query_mapped(ctx, SQL_SELECT,
                                   "SELECT u.username, u.activated, u.deactivated, u.last_accessed, u.uid,"
                                   "       (bl.username IS NOT NULL), opensess, logincount,"
                                   "       (at.attempts > 0)"
                                   "  FROM openvpn_users u"
                                   "  LEFT JOIN openvpn_blacklist bl USING(username)"
                                   "  LEFT JOIN openvpn_attempts at ON(at.username = u.username)"
                                   "  LEFT JOIN (SELECT uid, count(*) AS logincount "
                                   "               FROM openvpn_lastlog"
                                   "              GROUP BY uid) lc"
                                   "         ON (lc.uid = u.uid)"
                                   "  LEFT JOIN (SELECT uid, count(*) > 0 AS opensess"
                                   "               FROM openvpn_lastlog"
                                   "              WHERE sessionstatus = 2"
                                   "              GROUP BY uid) os"
                                   "         ON (os.uid = u.uid)",
                                   NULL, uinfo_map, NULL);

        if( uinf == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Error querying the database for a user");
                return 0;
        }
        eDBfreeMapping(uinfo_map);

        switch( sqlite_get_numtuples(uinf) ) {
        case 0:
                sqlite_free_results(uinf);
                return 0; // No user found

        case 1:
                uid = atoi_nullsafe(sqlite_get_value(uinf, 0, 4));
                username = sqlite_get_value(uinf, 0, 0);

                eurephiaXML_CreateDoc(ctx, 1, "user", &doc, &root_n);
                sqlite_xml_value(root_n, XML_NODE, "username", uinf, 0, 0);
                sqlite_xml_value(root_n, XML_ATTR, "uid", uinf, 0, 4);

                if( (infoType & USERINFO_user) == USERINFO_user ) {
                        info_n = xmlNewChild(root_n, NULL, (xmlChar *) "flags", NULL);

                        // set DEACTIVATED flag, if deactivated field is not NULL
                        xml_set_flag(info_n, "DEACTIVATED", (sqlite_get_value(uinf, 0, 2) != NULL));

                        // set BLACKLISTED flag, if username is found in blacklist table
                        xml_set_flag(info_n, "BLACKLISTED", (atoi_nullsafe(sqlite_get_value(uinf, 0, 5))==1));

                        // set OPENSESSION flag, if user has a lastlog entry with sessionstatus == 2
                        xml_set_flag(info_n, "OPENSESSION", (atoi_nullsafe(sqlite_get_value(uinf, 0, 6))==1));

                        // set ERRATTEMPT flag, if user has an entry in attempts log with attemtps > 0
                        xml_set_flag(info_n, "ERRATTEMPT", (atoi_nullsafe(sqlite_get_value(uinf, 0, 8))==1));

                        // set NEVERUSED flag, if login count == 0 and last_accessed == NULL
                        flag = xml_set_flag(info_n, "NEVERUSED", ((atoi_nullsafe(sqlite_get_value(uinf,0, 7))==0)
                                                                  && (sqlite_get_value(uinf, 0, 3) == NULL)));

                        // set RSETLASTUSED flag, if login count == 0 and last_accessed == NULL
                        xml_set_flag(info_n, "RSETLASTUSED", !flag && (sqlite_get_value(uinf,0,3)) == NULL);

                        // set RSETLOGINCNT flag, if login count == 0 and last_accessed != NULL
                        xml_set_flag(info_n, "RSETLOGINCNT", ((atoi_nullsafe(sqlite_get_value(uinf,0, 7))==0)
                                                              && (sqlite_get_value(uinf,0,3)) != NULL));

                        sqlite_xml_value(root_n, XML_NODE, "activated", uinf, 0, 1);
                        sqlite_xml_value(root_n, XML_NODE, "deactivated", uinf, 0, 2);
                        info_n = sqlite_xml_value(root_n, XML_NODE, "last_accessed", uinf, 0, 3);
                        sqlite_xml_value(info_n, XML_ATTR, "logincount", uinf, 0, 7);
                }

                if( (infoType & USERINFO_certs) == USERINFO_certs ) {
                        // Extract certificate info
                        qres = sqlite_query(ctx,
                                            "SELECT depth, digest, common_name, organisation, email, "
                                            "       c.registered, c.certid,  uc.accessprofile, access_descr,"
                                            "       fw_profile"
                                            "  FROM openvpn_certificates c"
                                            "  LEFT JOIN openvpn_usercerts uc ON (c.certid = uc.certid)"
                                            "  LEFT JOIN openvpn_accesses a "
                                            "         ON (uc.accessprofile = a.accessprofile)"
                                            " WHERE uid = '%i' ORDER BY c.certid DESC", uid);

                        info_n = xmlNewChild(root_n, NULL, (xmlChar *) "certificates", NULL);
                        if( (qres != NULL) && (sqlite_get_numtuples(qres) > 0) ) {
                                int i;
                                xmlNode *cert, *acpr;
                                xmlChar *tmp = NULL;

                                for( i = 0; i < sqlite_get_numtuples(qres); i++ ) {
                                        cert = xmlNewChild(info_n, NULL, (xmlChar *) "certificate", NULL);

                                        sqlite_xml_value(cert, XML_ATTR, "certid",        qres, 0, 6);
                                        sqlite_xml_value(cert, XML_ATTR, "depth",         qres, 0, 0);
                                        sqlite_xml_value(cert, XML_ATTR, "registered",    qres, 0, 5);
                                        sqlite_xml_value(cert, XML_NODE, "digest",        qres, 0, 1);

                                        tmp = (xmlChar *)sqlite_get_value(qres, 0, 2);
                                        xmlReplaceChars(tmp, '_', ' ');
                                        xmlNewChild(cert, NULL, (xmlChar *) "common_name", tmp);

                                        tmp = (xmlChar *)sqlite_get_value(qres, 0, 3);
                                        xmlReplaceChars(tmp, '_', ' ');
                                        xmlNewChild(cert, NULL, (xmlChar *) "organisation", tmp);

                                        sqlite_xml_value(cert, XML_NODE, "email",         qres, 0, 4);

                                        acpr = sqlite_xml_value(cert, XML_NODE, "access_profile", qres, 0, 8);
                                        sqlite_xml_value(acpr, XML_ATTR, "accessprofile",         qres, 0, 7);
                                        sqlite_xml_value(acpr, XML_ATTR, "fwdestination",         qres, 0, 9);
                                }
                        }

                        if( qres != NULL ) {
                                sqlite_free_results(qres);
                        }
                }

                if( (infoType & USERINFO_lastlog) == USERINFO_lastlog ) {
                        int i = 0;
                        xmlNode *lastl = NULL, *sess = NULL, *tmp1 = NULL, *tmp2 = NULL;
                        xmlChar *tmp = NULL;

                        qres = sqlite_query(ctx,
                                            "SELECT llid, ll.certid, protocol, remotehost, remoteport, macaddr,"
                                            "       vpnipaddr, vpnipmask, sessionstatus, sessionkey,"
                                            "       login, logout, session_duration, session_deleted,"
                                            "       bytes_sent, bytes_received, uicid, accessprofile,"
                                            "       access_descr, fw_profile, depth, digest,"
                                            "       common_name, organisation, email"
                                            "  FROM openvpn_lastlog ll"
                                            "  LEFT JOIN openvpn_usercerts USING (uid, certid)"
                                            "  LEFT JOIN openvpn_accesses USING (accessprofile)"
                                            "  LEFT JOIN openvpn_certificates cert ON (ll.certid = cert.certid)"
                                            " WHERE uid = '%i' ORDER BY login, logout", uid);

                        if( qres == NULL ) {
                                eurephia_log(ctx, LOG_ERROR, 0, "Quering the lastlog failed");
                                xmlFreeDoc(doc);
                                return NULL;
                        }

                        lastl = xmlNewChild(root_n, NULL, (xmlChar *) "lastlog", NULL);
                        for( i = 0; i < sqlite_get_numtuples(qres); i++ ) {

                                sess = xmlNewChild(lastl, NULL, (xmlChar*) "session", NULL);
                                sqlite_xml_value(sess, XML_ATTR, "llid",                  qres, i, 0);
                                xmlNewProp(sess, (xmlChar *) "session_status",
                                           (xmlChar *)SESSION_STATUS[atoi_nullsafe(sqlite_get_value(qres, i, 8))]);
                                sqlite_xml_value(sess, XML_ATTR, "session_duration",      qres, i, 12);
                                sqlite_xml_value(sess, XML_NODE, "sessionkey",            qres, i, 9);
                                sqlite_xml_value(sess, XML_NODE, "login",                 qres, i, 10);
                                sqlite_xml_value(sess, XML_NODE, "logout",                qres, i, 11);
                                sqlite_xml_value(sess, XML_NODE, "session_closed",        qres, i, 13);

                                tmp1 = xmlNewChild(sess, NULL, (xmlChar *) "connection", NULL);
                                sqlite_xml_value(tmp1, XML_ATTR, "bytes_sent",            qres, i, 14);
                                sqlite_xml_value(tmp1, XML_ATTR, "bytes_received",        qres, i, 15);
                                sqlite_xml_value(tmp1, XML_NODE, "protocol",              qres, i, 2);
                                sqlite_xml_value(tmp1, XML_NODE, "remote_host",           qres, i, 3);
                                sqlite_xml_value(tmp1, XML_NODE, "remote_port",           qres, i, 4);
                                sqlite_xml_value(tmp1, XML_NODE, "vpn_macaddr",           qres, i, 5);
                                sqlite_xml_value(tmp1, XML_NODE, "vpn_ipaddr" ,           qres, i, 6);
                                sqlite_xml_value(tmp1, XML_NODE, "vpn_netmask",           qres, i, 7);

                                tmp1 = xmlNewChild(sess, NULL, (xmlChar *) "certificate", NULL);
                                sqlite_xml_value(tmp1, XML_ATTR, "certid",                qres, i, 1);
                                sqlite_xml_value(tmp1, XML_ATTR, "uicid",                 qres, i, 16);
                                sqlite_xml_value(tmp1, XML_ATTR, "depth",                 qres, i, 20);
                                sqlite_xml_value(tmp1, XML_NODE, "digest",                qres, i, 21);

                                tmp = (xmlChar *)sqlite_get_value(qres, 0, 22);
                                xmlReplaceChars(tmp, '_', ' ');
                                xmlNewChild(tmp1, NULL, (xmlChar *) "common_name", tmp);

                                tmp = (xmlChar *)sqlite_get_value(qres, 0, 23);
                                xmlReplaceChars(tmp, '_', ' ');
                                xmlNewChild(tmp1, NULL, (xmlChar *) "organisation", tmp);

                                sqlite_xml_value(tmp1, XML_NODE, "email",                 qres, i, 24);

                                tmp2 = sqlite_xml_value(tmp1, XML_NODE, "access_profile", qres, i, 18);
                                sqlite_xml_value(tmp2, XML_ATTR, "accessprofile",         qres, i, 17);
                                sqlite_xml_value(tmp2, XML_ATTR, "fwdestination",         qres, i, 19);
                        }
                        sqlite_free_results(qres);
                }

                if( (infoType & USERINFO_attempts) == USERINFO_attempts ) {
                        xmlNode *atmpt = NULL;

                        qres = sqlite_query(ctx,
                                            "SELECT attempts, registered, last_attempt, atpid"
                                            "  FROM openvpn_attempts "
                                            " WHERE username = '%q'", username);

                        if( (qres == NULL) || (sqlite_get_numtuples(qres) > 1) ) {
                                eurephia_log(ctx, LOG_ERROR, 0, "Quering for login attempts failed");
                                sqlite_free_results(qres);
                                xmlFreeDoc(doc);
                                return NULL;
                        }

                        atmpt = xmlNewChild(root_n, NULL, (xmlChar *) "attempts", NULL);
                        if( sqlite_get_numtuples(qres) == 1 ) {
                                sqlite_xml_value(atmpt, XML_ATTR, "atpid", qres, 0, 3);
                                sqlite_xml_value(atmpt, XML_ATTR, "attempts", qres, 0, 0);
                                sqlite_xml_value(atmpt, XML_NODE, "first_attempt", qres, 0, 1);
                                sqlite_xml_value(atmpt, XML_NODE, "last_attempt", qres, 0, 2);
                        }
                        sqlite_free_results(qres);
                }

                if( (infoType & USERINFO_blacklist) == USERINFO_blacklist ) {
                        xmlNode *atmpt = NULL;

                        qres = sqlite_query(ctx,
                                            "SELECT registered, last_accessed, blid"
                                            "  FROM openvpn_blacklist "
                                            " WHERE username = '%q'", username);

                        if( (qres == NULL) || (sqlite_get_numtuples(qres) > 1) ) {
                                eurephia_log(ctx, LOG_ERROR, 0, "Quering blacklist log failed");
                                sqlite_free_results(qres);
                                xmlFreeDoc(doc);
                                return NULL;
                        }

                        atmpt = xmlNewChild(root_n, NULL, (xmlChar *) "blacklist", NULL);
                        if( sqlite_get_numtuples(qres) == 1 ) {
                                sqlite_xml_value(atmpt, XML_ATTR, "blid", qres, 0, 2);
                                sqlite_xml_value(atmpt, XML_NODE, "blacklisted", qres, 0, 0);
                                sqlite_xml_value(atmpt, XML_NODE, "last_accessed", qres, 0, 1);
                        }
                        sqlite_free_results(qres);
                }

                sqlite_free_results(uinf);
                return doc;
        default:
                sqlite_free_results(uinf);
                eurephia_log(ctx, LOG_ERROR, 0, "Too many user records was found.");
                return NULL;
        }
}


/**
 * @copydoc eDBadminAddUser()
 */
int eDBadminAddUser(eurephiaCTX *ctx, xmlDoc *userinfo) {
        dbresult *res = NULL;
        xmlNode *usrinf_n = NULL;
        eDBfieldMap *usrinf_map = NULL;
        int uid = 0;

        DEBUG(ctx, 20, "Function call: eDBadminAddUser(ctx, xmlDoc)");
        assert( (ctx != NULL) && (userinfo != NULL) );

        if( (ctx->context_type != ECTX_ADMIN_CONSOLE) && (ctx->context_type != ECTX_ADMIN_WEB) ) {
                eurephia_log(ctx, LOG_CRITICAL, 0,
                             "eurephia admin function call attempted with wrong context type");
                return 0;
        }

        // Get the add_user node, and then find the fieldMapping node
        usrinf_n = eurephiaXML_getRoot(ctx, userinfo, "add_user", 1);
        if( usrinf_n == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Could not find proper add user XML document");
                return 0;
        }
        usrinf_n = xmlFindNode(usrinf_n, "fieldMapping");
        if( usrinf_n == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Could not find proper add user XML document");
                return 0;
        }

        // Get a proper field mapping to be used by the database
        usrinf_map = eDBxmlMapping(ctx, tbl_sqlite_users, NULL, usrinf_n);
        assert( usrinf_map != NULL );

        // Register the user
        res = sqlite_query_mapped(ctx, SQL_INSERT, "INSERT INTO openvpn_users", usrinf_map, NULL, NULL);
        if( res == NULL ) {
                eurephia_log(ctx, LOG_FATAL, 0, "Could not register the new user account");
                uid = -1;
        } else {
                uid = res->last_insert_id;
        }
        sqlite_free_results(res);
        eDBfreeMapping(usrinf_map);

        return uid;
}


/**
 * @copydoc eDBadminUpdateUser()
 */
int eDBadminUpdateUser(eurephiaCTX *ctx, const int uid, xmlDoc *userinfo) {
        dbresult *uinf = NULL;
        xmlDoc *srch_xml = NULL;
        xmlNode *root_n = NULL, *srch_n = NULL, *values_n = NULL;
        eDBfieldMap *value_map = NULL, *srch_map = NULL;
        xmlChar *xmluid = 0;

        DEBUG(ctx, 20, "Function call: eDBadminUpdateUser(ctx, %i, xmlDoc)", uid);
        assert( (ctx != NULL) && (userinfo != NULL) );

        if( (ctx->context_type != ECTX_ADMIN_CONSOLE) && (ctx->context_type != ECTX_ADMIN_WEB) ) {
                eurephia_log(ctx, LOG_CRITICAL, 0,
                             "eurephia admin function call attempted with wrong context type");
                return 0;
        }

        // Get the update_user node
        root_n = eurephiaXML_getRoot(ctx, userinfo, "update_user", 1);
        if( root_n == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Could not find proper XML element for user update");
                return 0;
        }

        // Double check that we are going to update the right user
        xmluid = (xmlChar *)xmlGetAttrValue(root_n->properties, "uid");
        if( atoi_nullsafe((char *)xmluid) != uid ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Mismatch between uid given as parameter and uid in XML");
                return 0;
        }

        // Grab the fieldMapping node and create a eDBfieldMap structure for it
        values_n = xmlFindNode(root_n, "fieldMapping");
        value_map = eDBxmlMapping(ctx, tbl_sqlite_users, NULL, values_n);

        // Create an eDBfieldMap structure for the srch_map (used for WHERE clause)
        eurephiaXML_CreateDoc(ctx, 1, "fieldMapping", &srch_xml, &srch_n);
        xmlNewProp(srch_n, (xmlChar *) "table", (xmlChar *) "users");
        xmlNewChild(srch_n, NULL, (xmlChar *) "uid", xmluid);  // Add uid as the only criteria
        srch_map = eDBxmlMapping(ctx, tbl_sqlite_users, NULL, srch_n);
        assert( srch_map != NULL );

        // UPDATE the database
        uinf = sqlite_query_mapped(ctx, SQL_UPDATE, "UPDATE openvpn_users", value_map, srch_map, NULL);

        if( uinf == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Error querying the database for a user");
                return 0;
        }
        sqlite_free_results(uinf);

        eDBfreeMapping(srch_map);
        eDBfreeMapping(value_map);
        xmlFreeDoc(srch_xml);

        return 1;
}

/**
 * @copydoc eDBadminDeleteUser()
 */
int eDBadminDeleteUser(eurephiaCTX *ctx, const int uid, xmlDoc *userinfo) {
        dbresult *res = NULL;
        xmlNode *usrinf_n = NULL;
        char *uid_str = NULL;
        int rc = 0;

        DEBUG(ctx, 20, "Function call: eDBadminDeleteUser(ctx, %i, xmlDoc)", uid);
        assert( (ctx != NULL) && (userinfo != NULL) );

        if( (ctx->context_type != ECTX_ADMIN_CONSOLE) && (ctx->context_type != ECTX_ADMIN_WEB) ) {
                eurephia_log(ctx, LOG_CRITICAL, 0,
                             "eurephia admin function call attempted with wrong context type");
                return 0;
        }

        // Get the delete_user node
        usrinf_n = eurephiaXML_getRoot(ctx, userinfo, "delete_user", 1);
        if( usrinf_n == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Could not find proper delete user XML document");
                return 0;
        }

        // Get the uid from the XML and compare it with the uid in the function argument
        uid_str = xmlGetAttrValue(usrinf_n->properties, "uid");
        if( (uid_str == NULL) || (atoi_nullsafe(uid_str) != uid) ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Could not find proper delete user XML document. (uid mismatch)");
                return 0;
        }

        // Delete the user
        res = sqlite_query(ctx, "DELETE FROM openvpn_users WHERE uid = '%i'", uid);
        if( res == NULL ) {
                eurephia_log(ctx, LOG_FATAL, 0, "Could not delete the user account");
                rc = 0;
        } else {
                rc = 1;
        }
        sqlite_free_results(res);
        return rc;
}


/**
 * @copydoc eDBadminGetCertificateInfo()
 */
xmlDoc *eDBadminGetCertificateInfo(eurephiaCTX *ctx, xmlDoc *srchxml, const char *sortkeys) {
        xmlDoc *certlist = NULL;
        xmlNode *srch_n = NULL, *cert_n = NULL, *tmp_n = NULL;
        eDBfieldMap *srch_map = NULL, *ptr = NULL;
        dbresult *res = NULL;
        xmlChar tmp[2050];
        char *dbsort = NULL;
        int i;

        DEBUG(ctx, 20, "Function call: eDBadminGetCertificateInfo(ctx, xmlDoc, '%s')", sortkeys);
        assert( (ctx != NULL) && (srchxml != NULL) );

        if( (ctx->context_type != ECTX_ADMIN_CONSOLE) && (ctx->context_type != ECTX_ADMIN_WEB) ) {
                eurephia_log(ctx, LOG_CRITICAL, 0,
                             "eurephia admin function call attempted with wrong context type");
                return NULL;
        }

        if( sortkeys != NULL ) {
                dbsort = eDBmkSortKeyString(tbl_sqlite_certs, sortkeys);
        }

        srch_n = eurephiaXML_getRoot(ctx, srchxml, "certificate_info", 1);
        if( srch_n == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Could not find a valid XML for looking up certificates");
                return NULL;
        }

        srch_n = xmlFindNode(srch_n, "fieldMapping");
        if( srch_n == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Could not find a valid XML for looking up certificates");
                return NULL;
        }

        srch_map = eDBxmlMapping(ctx, tbl_sqlite_certs, NULL, srch_n);
        assert( srch_map != NULL );

        // Replace spaces with underscore in common name and
        // in organisation fields, to comply with OpenVPN standards
        for( ptr = srch_map; ptr != NULL; ptr = ptr->next ) {
                if( ptr->field_id & (FIELD_CNAME | FIELD_ORG) ) {
                        xmlReplaceChars((xmlChar *) ptr->value, ' ', '_');
                }
        }

        res = sqlite_query_mapped(ctx, SQL_SELECT,
                                  "SELECT depth, digest, common_name, organisation, email, registered, certid"
                                  "  FROM openvpn_certificates", NULL, srch_map, dbsort);
        if( res == NULL ) {
                eDBfreeMapping(srch_map);
                eurephia_log(ctx, LOG_ERROR, 0, "Could not query the certificate table");
                return NULL;
        }

        memset(&tmp, 0, 2050);
        eurephiaXML_CreateDoc(ctx, 1, "certificates", &certlist, &cert_n);
        xmlStrPrintf(tmp, 64, (xmlChar *) "%i", sqlite_get_numtuples(res));
        xmlNewProp(cert_n, (xmlChar *) "certificates", (xmlChar *) tmp);

        for( i = 0; i < sqlite_get_numtuples(res); i++ ) {
                tmp_n = xmlNewChild(cert_n, NULL, (xmlChar *) "certificate", NULL);

                sqlite_xml_value(tmp_n, XML_ATTR, "certid", res, i, 6);
                sqlite_xml_value(tmp_n, XML_ATTR, "depth", res, i, 0);
                sqlite_xml_value(tmp_n, XML_ATTR, "registered", res, i, 5);
                sqlite_xml_value(tmp_n, XML_NODE, "digest", res, i, 1);

                xmlStrPrintf(tmp, 2048, (xmlChar *) "%.2048s", sqlite_get_value(res, i, 2));
                xmlReplaceChars(tmp, '_', ' ');
                xmlNewChild(tmp_n, NULL, (xmlChar *) "common_name", tmp);

                xmlStrPrintf(tmp, 2048, (xmlChar *) "%.2048s", sqlite_get_value(res, i, 3));
                xmlReplaceChars(tmp, '_', ' ');
                xmlNewChild(tmp_n, NULL, (xmlChar *) "organisation", tmp);

                sqlite_xml_value(tmp_n, XML_NODE, "email", res, i, 4);
        }
        sqlite_free_results(res);
        eDBfreeMapping(srch_map);

        return certlist;
}


/**
 * @copydoc eDBadminAddCertificate()
 */
int eDBadminAddCertificate(eurephiaCTX *ctx, xmlDoc *certinfo_xml) {
        xmlNode *crtinf_n = NULL;
        eDBfieldMap *crtinf_map = NULL, *ptr = NULL;
        dbresult *res = NULL;
        int certid = 0;

        DEBUG(ctx, 20, "Function call: eDBadminAddCertificate(ctx, xmlDoc)");
        assert( (ctx != NULL) && (certinfo_xml != NULL) );

        if( (ctx->context_type != ECTX_ADMIN_CONSOLE) && (ctx->context_type != ECTX_ADMIN_WEB) ) {
                eurephia_log(ctx, LOG_CRITICAL, 0,
                             "eurephia admin function call attempted with wrong context type");
                return 0;
        }

        crtinf_n = eurephiaXML_getRoot(ctx, certinfo_xml, "register_certificate", 1);
        if( crtinf_n == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Could not find a valid XML for registering certificate");
                return 0;
        }

        crtinf_n = xmlFindNode(crtinf_n, "fieldMapping");
        if( crtinf_n == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Could not find a valid XML for registering certificate");
                return 0;
        }

        crtinf_map = eDBxmlMapping(ctx, tbl_sqlite_certs, NULL, crtinf_n);
        assert( crtinf_map != NULL );

        // Replace spaces with underscore in common name and
        // in organisation fields, to comply with OpenVPN standards
        for( ptr = crtinf_map; ptr != NULL; ptr = ptr->next ) {
                if( ptr->field_id & (FIELD_CNAME | FIELD_ORG) ) {
                        xmlReplaceChars((xmlChar *) ptr->value, ' ', '_');
                }
        }

        // Register the certificate
        res = sqlite_query_mapped(ctx, SQL_INSERT, "INSERT INTO openvpn_certificates", crtinf_map, NULL, NULL);
        if( res == NULL ) {
                eurephia_log(ctx, LOG_FATAL, 0, "Could not register the certificate");
                certid = -1;
        } else {
                certid = res->last_insert_id;
        }
        sqlite_free_results(res);
        eDBfreeMapping(crtinf_map);

        return certid;
}


/**
 * @copydoc eDBadminDeleteCertificate()
 */
int eDBadminDeleteCertificate(eurephiaCTX *ctx, xmlDoc *certinfo_xml) {
        int rc = 0;
        xmlNode *crtinf_n = NULL;
        eDBfieldMap *crtinf_map = NULL, *ptr = NULL;
        dbresult *res = NULL;

        DEBUG(ctx, 20, "Function call: eDBadminDeleteCertificate(ctx, xmlDoc)");
        assert( (ctx != NULL) && (certinfo_xml != NULL) );

        if( (ctx->context_type != ECTX_ADMIN_CONSOLE) && (ctx->context_type != ECTX_ADMIN_WEB) ) {
                eurephia_log(ctx, LOG_CRITICAL, 0,
                             "eurephia admin function call attempted with wrong context type");
                return 0;
        }

        crtinf_n = eurephiaXML_getRoot(ctx, certinfo_xml, "delete_certificate", 1);
        if( crtinf_n == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Could not find a valid XML for the delete certificate request");
                return 0;
        }

        crtinf_n = xmlFindNode(crtinf_n, "fieldMapping");
        if( crtinf_n == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Could not find a valid XML for the delete certificate request");
                return 0;
        }

        crtinf_map = eDBxmlMapping(ctx, tbl_sqlite_certs, NULL, crtinf_n);
        assert( crtinf_map != NULL );

        // Replace spaces with underscore in common name and
        // in organisation fields, to comply with OpenVPN standards
        for( ptr = crtinf_map; ptr != NULL; ptr = ptr->next ) {
                if( ptr->field_id & (FIELD_CNAME | FIELD_ORG) ) {
                        xmlReplaceChars((xmlChar *) ptr->value, ' ', '_');
                }
        }

        // Register the certificate
        res = sqlite_query_mapped(ctx, SQL_DELETE, "DELETE FROM openvpn_certificates", NULL, crtinf_map, NULL);
        if( res == NULL ) {
                eurephia_log(ctx, LOG_FATAL, 0, "Could not complete the delete certificate request");
                rc = 0;
        } else {
                rc = 1;
        }
        sqlite_free_results(res);
        eDBfreeMapping(crtinf_map);

        return rc;
}


/**
 * @copydoc eDBadminGetAdminAccess()
 */
xmlDoc *eDBadminGetAdminAccess(eurephiaCTX *ctx, xmlDoc *srch_xml) {
        dbresult *res = NULL;
        eDBfieldMap *fmap = NULL;
        int last_uid = -1, i = 0;

        xmlDoc *doc = NULL;
        xmlNode *root_n = NULL, *fieldmap_n = NULL, *rec_n = NULL, *acl_n = NULL, *tmp_n;

        DEBUG(ctx, 20, "Function call: eDBadminGetAdminAccess(ctx, {xmlDoc})");
        assert( (ctx != NULL) && (srch_xml != NULL) );

        if( (ctx->context_type != ECTX_ADMIN_CONSOLE) && (ctx->context_type != ECTX_ADMIN_WEB) ) {
                eurephia_log(ctx, LOG_CRITICAL, 0,
                             "eurephia admin function call attempted with wrong context type");
                return 0;
        }

        tmp_n = eurephiaXML_getRoot(ctx, srch_xml, "admin_access", 1);
        fieldmap_n = xmlFindNode(tmp_n, "fieldMapping");
        fmap = eDBxmlMapping(ctx, tbl_sqlite_eurephiaadmacc, "eac", fieldmap_n);

        // Query the database, find the user defined in the user map
        res = sqlite_query_mapped(ctx, SQL_SELECT,
                                  "SELECT eac.uid, username, interface, access"
                                  "  FROM eurephia_adminaccess eac"
                                  "  LEFT JOIN openvpn_users USING(uid)",
                                  NULL, fmap, "uid, interface, access");
        if( res == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Error querying the database for a access levels");
                return 0;
        }
        eDBfreeMapping(fmap);

        eurephiaXML_CreateDoc(ctx, 1, "admin_access_list", &doc, &root_n);

        for( i = 0; i < sqlite_get_numtuples(res); i++ ) {
                if( last_uid != atoi_nullsafe(sqlite_get_value(res, i, 0)) ) {
                        // Create a new block element when we get a new uid
                        rec_n = xmlNewChild(root_n, NULL, (xmlChar *) "user_access", NULL);
                        last_uid = atoi_nullsafe(sqlite_get_value(res, i, 0));

                        tmp_n = sqlite_xml_value(rec_n, XML_NODE, "username", res, i, 1);
                        sqlite_xml_value(tmp_n, XML_ATTR, "uid", res, i, 0);

                        acl_n = xmlNewChild(rec_n, NULL, (xmlChar *) "access_levels", NULL);
                }

                tmp_n = sqlite_xml_value(acl_n, XML_NODE, "access", res, i, 3);
                sqlite_xml_value(tmp_n, XML_ATTR, "interface", res, i, 2);
        }

        sqlite_free_results(res);
        return doc;
}


/**
 * @copydoc eDBadminEditAdminAccess()
 */
int eDBadminEditAdminAccess(eurephiaCTX *ctx, xmlDoc *grant_xml) {
        dbresult *res = NULL;
        xmlNode *grant_n = NULL, *fmap_n = NULL;
        eDBfieldMap *grant_m = NULL;
        char *mode = NULL;
        int rc = 0;

        DEBUG(ctx, 20, "Function call: eDBadminEditAdminAccess(ctx, xmlDoc)");
        assert( (ctx != NULL) && (grant_xml != NULL) );

        if( (ctx->context_type != ECTX_ADMIN_CONSOLE) && (ctx->context_type != ECTX_ADMIN_WEB) ) {
                eurephia_log(ctx, LOG_CRITICAL, 0,
                             "eurephia admin function call attempted with wrong context type");
                return 0;
        }

        grant_n = eurephiaXML_getRoot(ctx, grant_xml, "edit_admin_access", 1);
        if( grant_n == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Could not find a valid XML for the user-certs link request");
                return 0;
        }
        mode = xmlGetAttrValue(grant_n->properties, "mode");
        if( mode == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Invalid edit admin access request (1).");
                return 0;
        }

        fmap_n = xmlFindNode(grant_n, "fieldMapping");
        if( fmap_n == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Invalid edit admin access request (2).");
                return 0;
        }

        grant_m = eDBxmlMapping(ctx, tbl_sqlite_eurephiaadmacc, NULL, fmap_n);
        assert(grant_m != NULL);

        if( strcmp(mode, "grant") == 0 ) {
                res = sqlite_query_mapped(ctx, SQL_INSERT, "INSERT INTO eurephia_adminaccess",
                                          grant_m, NULL, NULL);
                rc = res->last_insert_id;
        } else if( strcmp(mode, "revoke") == 0 ) {
                res = sqlite_query_mapped(ctx, SQL_DELETE, "DELETE FROM eurephia_adminaccess",
                                          NULL, grant_m, NULL);
                rc = 1;
        }

        if( res == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Failed to update admin access");
                rc = -1;
        } else {
                sqlite_free_results(res);
        }
        eDBfreeMapping(grant_m);

        return rc;
}


/**
 * @copydoc eDBadminGetLastlog()
 */
xmlDoc *eDBadminGetLastlog(eurephiaCTX *ctx, xmlDoc *srch_xml, const char *sortkeys)
{
        dbresult *res = NULL;
        eDBfieldMap *fmap = NULL, *fptr = NULL;
        int i = 0;

        xmlDoc *doc = NULL;
        xmlNode *fieldmap_n = NULL, *lastl = NULL, *sess = NULL, *tmp1 = NULL, *tmp2 = NULL;

        DEBUG(ctx, 20, "Function call: eDBadminGetLastLog(ctx, {xmlDoc})");
        assert( (ctx != NULL) && (srch_xml != NULL) );

        if( (ctx->context_type != ECTX_ADMIN_CONSOLE) && (ctx->context_type != ECTX_ADMIN_WEB) ) {
                eurephia_log(ctx, LOG_CRITICAL, 0,
                             "eurephia admin function call attempted with wrong context type");
                return NULL;
        }

        tmp1 = eurephiaXML_getRoot(ctx, srch_xml, "lastlog_query", 1);
        fieldmap_n = xmlFindNode(tmp1, "fieldMapping");
        fmap = eDBxmlMapping(ctx, tbl_sqlite_lastlog, "ll", fieldmap_n);

        // HACK: Remove table alias for some fields in the field mapping
        for( fptr = fmap; fptr != NULL; fptr = fptr->next) {
                switch( fptr->field_id ) {
                case FIELD_UNAME:
                        free_nullsafe(ctx, fptr->table_alias);
                default:
                        break;
                }
        }

        // Query the database, find the user defined in the user map
        res = sqlite_query_mapped(ctx, SQL_SELECT,
                                  "SELECT llid, ll.certid, protocol, remotehost, remoteport, macaddr,"
                                  "       vpnipaddr, vpnipmask, sessionstatus, sessionkey,"
                                  "       login, logout, session_duration, session_deleted,"
                                  "       bytes_sent, bytes_received, uicid, accessprofile,"
                                  "       access_descr, fw_profile, depth, digest,"
                                  "       common_name, organisation, email, username, ll.uid"
                                  "  FROM openvpn_lastlog ll"
                                  "  LEFT JOIN openvpn_usercerts USING (uid, certid)"
                                  "  LEFT JOIN openvpn_accesses USING (accessprofile)"
                                  "  LEFT JOIN openvpn_users users ON( ll.uid = users.uid)"
                                  "  LEFT JOIN openvpn_certificates cert ON (ll.certid = cert.certid)",
                                  NULL, fmap, sortkeys);
        eDBfreeMapping(fmap);
        xmlFreeDoc(doc);
        if( res == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Quering the lastlog failed");
                return NULL;
        }
        eurephiaXML_CreateDoc(ctx, 1, "lastlog", &doc, &lastl);
        assert( (doc != NULL) && (lastl != NULL) );
        for( i = 0; i < sqlite_get_numtuples(res); i++ ) {
                xmlChar *tmp = NULL;
                sess = xmlNewChild(lastl, NULL, (xmlChar*) "session", NULL);
                sqlite_xml_value(sess, XML_ATTR, "llid",                  res, i, 0);
                xmlNewProp(sess, (xmlChar *) "session_status",
                           (xmlChar *)SESSION_STATUS[atoi_nullsafe(sqlite_get_value(res, i, 8))]);
                sqlite_xml_value(sess, XML_ATTR, "session_duration",      res, i, 12);
                sqlite_xml_value(sess, XML_NODE, "sessionkey",            res, i, 9);
                sqlite_xml_value(sess, XML_NODE, "login",                 res, i, 10);
                sqlite_xml_value(sess, XML_NODE, "logout",                res, i, 11);
                sqlite_xml_value(sess, XML_NODE, "session_closed",        res, i, 13);

                tmp1 = xmlNewChild(sess, NULL, (xmlChar *) "connection", NULL);
                sqlite_xml_value(tmp1, XML_ATTR, "bytes_sent",            res, i, 14);
                sqlite_xml_value(tmp1, XML_ATTR, "bytes_received",        res, i, 15);
                sqlite_xml_value(tmp1, XML_NODE, "protocol",              res, i, 2);
                sqlite_xml_value(tmp1, XML_NODE, "remote_host",           res, i, 3);
                sqlite_xml_value(tmp1, XML_NODE, "remote_port",           res, i, 4);
                sqlite_xml_value(tmp1, XML_NODE, "vpn_macaddr",           res, i, 5);
                sqlite_xml_value(tmp1, XML_NODE, "vpn_ipaddr" ,           res, i, 6);
                sqlite_xml_value(tmp1, XML_NODE, "vpn_netmask",           res, i, 7);

                tmp1 = sqlite_xml_value(sess, XML_NODE, "username",       res, i, 25);
                sqlite_xml_value(tmp1, XML_ATTR, "uid",                   res, i, 26);

                tmp1 = xmlNewChild(sess, NULL, (xmlChar *) "certificate", NULL);
                sqlite_xml_value(tmp1, XML_ATTR, "certid",                res, i, 1);
                sqlite_xml_value(tmp1, XML_ATTR, "uicid",                 res, i, 16);
                sqlite_xml_value(tmp1, XML_ATTR, "depth",                 res, i, 20);
                sqlite_xml_value(tmp1, XML_NODE, "digest",                res, i, 21);

                tmp = (xmlChar *)sqlite_get_value(res, i, 22);
                xmlReplaceChars(tmp, '_', ' ');
                xmlNewChild(tmp1, NULL, (xmlChar *) "common_name", tmp);

                tmp = (xmlChar *)sqlite_get_value(res, i, 23);
                xmlReplaceChars(tmp, '_', ' ');
                xmlNewChild(tmp1, NULL, (xmlChar *) "organisation", tmp);

                sqlite_xml_value(tmp1, XML_NODE, "email",                 res, i, 24);

                tmp2 = sqlite_xml_value(tmp1, XML_NODE, "access_profile", res, i, 18);
                sqlite_xml_value(tmp2, XML_ATTR, "accessprofile",         res, i, 17);
                sqlite_xml_value(tmp2, XML_ATTR, "fwdestination",         res, i, 19);
        }
        sqlite_free_results(res);
        return doc;
}
#endif