summaryrefslogtreecommitdiffstats
path: root/eurephiadm/commands/users.c
blob: 50f979044cbc299aa7ba8e76c39ece94b4b46b53 (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
/* users.c  --  eurephiadm command - User Account Management
 *
 *  GPLv2 - Copyright (C) 2008  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.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>

#ifdef HAVE_LIBXML2
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
#endif

#define MODULE "eurephia::Users"
#include <eurephia_nullsafe.h>
#include <eurephia_context.h>
#include <eurephia_log.h>
#include <eurephia_xml.h>
#include <eurephia_values_struct.h>
#include <eurephiadb_session_struct.h>
#include <eurephia_admin_struct.h>
#include <eurephiadb_mapping.h>
#include <eurephiadb_driver.h>

#include "../argparser.h"
#include "../get_console_input.h"

inline void field_print_int(char *label, int val) {
        printf("%25.25s: %i\n", label, val);
}

inline void field_print_str(char *label, char *val) {
        printf("%25.25s: %s\n", label, (val == NULL ? "-" : val));
}

void display_users_help(int page) {
        printf("\n%s -- Administer user accounts\n\n", MODULE);

        switch( page ) {
        case 'l':
                printf("The list mode can accept one parameter:\n\n"
                       "     -S | --sort <sort key>     Decide the sort order of the user list\n"
                       "\n"
                       "Available sort keys are: uid, username, activated, deactivated and lastaccess\n\n");
                break;

        case 's':
                printf("The show mode shows more information about a user account.\n"
                       "The needed arguments are one of the following arguments:\n\n"
                       "     -i | --uid              Numeric user ID\n"
                       "     -u | --username         User name\n"
                       "     -l | --lastlog          Show users lastlog entries\n"
                       "     -L | --lastlog-details  Show a more verbose lastlog\n"
                       "     -a | --attempts         Show users failed attempts and blaclisting\n"
                       "     -b | --blacklist        Alias for --attempts\n"
                       "\n");
                break;

        case 'a':
                printf("The activate mode activates an account which not activated or deactivated.\n"
                       "The needed arguments are one of the following arguments:\n\n"
                       "     -i | --uid          Numeric user ID\n"
                       "     -u | --username     User name\n\n");
                break;

        case 'd':
                printf("The deactivate mode deactivates a user account.\n"
                       "The needed arguments are one of the following arguments:\n\n"
                       "     -i | --uid          Numeric user ID\n"
                       "     -u | --username     User name\n\n");
                break;

        case 'A':
                printf("The add user mode registers a new user account.\n"
                       "\n"
                       "     -u | --username     User name to use for the new account (required)\n"
                       "     -P | --password     Assign a new password via the command line\n\n"
                       "(not implemented yet) To register this new account against a certificate\n"
                       "you can use the following arguments.  These arguments cannot be used together.\n\n"
                       "     -C | --certid       Use already registered certificate, identified by certid\n"
                       "     -D | --digest       Use already registered certificate, identified by digest\n"
                       "     -c | --certfile     Use the given certificate file and register it along with\n"
                       "                         the account\n\n");
                break;

        case 'D':
                printf("Delete user mode\n");
                break;

        case 'p':
                printf("Change password mode\n");
                break;

        default:
                printf("Available modes:\n"
                       "     -l | --list         List all user accounts\n"
                       "     -s | --show         Show user account details\n"
                       "     -a | --activate     Activate a user account\n"
                       "     -d | --deactivate   Deactivate a user account\n"
                       "     -A | --add          Add a new user account\n"
                       "     -D | --delete       Delete a user account\n"
                       "     -p | --password     Change password on a users account\n"
                       "     -h | --help <mode>  Further help for these modes\n\n");
                break;
        }
}

int help_Users2(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        e_options helpargs[] = {
                {"--list", "-l", 0},
                {"--show", "-s", 0},
                {"--activate", "-a", 0},
                {"--deactivate", "-d", 0},
                {"--add", "-A", 0},
                {"--delete", "-D", 0},
                {"--password", "-p", 0},
                {NULL, NULL, 0}
        };

        int i = 1;
        display_users_help(eurephia_getopt(&i, argc, argv, helpargs));
        return 0;
}

void help_Users() {
        display_users_help(0);
}


int list_users(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        xmlDoc *userlist = NULL;
        xmlNode *users_n = NULL;
        int i = 0;
        char *sortkeys = NULL;

        e_options listargs[] = {
                {"--sort", "-S", 1},
                {"--help", "-h", 0},
                {NULL, NULL, 0}
        };

        assert((ctx != NULL) && (ctx->dbc != NULL) && (ctx->dbc->config != NULL));

        // Parse arguments
        for( i = 1; i < argc; i++ ) {
                switch( eurephia_getopt(&i, argc, argv, listargs) ) {
                case 'S':
                        sortkeys = optargs[0];
                        i++;
                        break;

                case 'h':
                        display_users_help('l');
                        return 0;

                default:
                        return 1;
                }
        }

        // Retrieve the user list - as an XML document
        userlist = eDBadminGetUserList(ctx, sortkeys);
        if( userlist == NULL ) {
                fprintf(stderr, "Error retrieving user list\n");
                return 1;
        }

        fprintf(stdout, " %3s %-20.32s %-16.16s %-16.16s %-16.16s\n",
                "ID", "Username", "Activated","Deactivated","Last access");
        fprintf(stdout, " ----------------------------------------------------------------------------\n");

        // Find the user list node in the XML doc
        users_n = eurephiaXML_getRoot(ctx, userlist, "userlist", 1);
        if( users_n == NULL ) {
                fprintf(stderr, "Could not retrieve valid data\n");
                xmlFreeDoc(userlist);
                return 1;
        }
        users_n = users_n->children;

        // Loop through the user list
        for( ; users_n != NULL; users_n = users_n->next ) {
                fprintf(stdout, " %3.3s %-20.32s %-16.16s %-16.16s %-16.16s\n",
                        xmlGetAttrValue(users_n->properties, "uid"),
                        xmlGetNodeContent(users_n, "username"),
                        defaultValue(xmlGetNodeContent(users_n, "activated"), "(Not activated)"),
                        defaultValue(xmlGetNodeContent(users_n, "deactivated"), "-"),
                        defaultValue(xmlGetNodeContent(users_n, "last_accessed"), "-"));
        }
        fprintf(stdout, " ----------------------------------------------------------------------------\n");
        xmlFreeDoc(userlist);
        return 0;
}

char *xmlFlags2str(xmlXPathContext *xpathCTX, const char *xpath) {
        xmlXPathObject *flagsObj = NULL;
        int i = 0;
        static char flagstr[8194];

        memset(&flagstr, 0, 8194);

        // Find the flag nodes given in the XPath query
        flagsObj = xmlXPathEvalExpression((xmlChar *)xpath, xpathCTX);
        if( flagsObj == NULL ) {
                fprintf(stderr,"Error: unable to evaluate xpath expression \"%s\"\n", xpath);
                return flagstr;
        }

        // Loop through all nodes and build up a string of all flags
        for( i = 0; i < flagsObj->nodesetval->nodeNr; i++ ) {
                char *flag = xmlExtractContent(flagsObj->nodesetval->nodeTab[i]);
                if( flag != NULL ) {
                        strncat(flagstr, flag, 8191-strlen_nullsafe(flagstr));
                        strcat(flagstr, " ");
                }
        }
        xmlXPathFreeObject(flagsObj);
        return flagstr;
}

void xmlPrint_certs(xmlXPathContext *certsXP, const char *xpath) {
        xmlXPathObject *certsObj = NULL;
        xmlNode *certnode = NULL;
        int i = 0;

        // Find the certificates in the given XPath query
        certsObj = xmlXPathEvalExpression((xmlChar *)xpath, certsXP);
        if( certsObj == NULL ) {
                fprintf(stderr,"Error: unable to evaluate xpath expression \"%s\"\n", xpath);
                return;
        }

        // If no certs were found, inform and exit
        if( certsObj->nodesetval->nodeNr == 0 ) {
                field_print_str("Associated certificates", "None");
                printf("\n");
                xmlXPathFreeObject(certsObj);
                return;
        }

        // Parse all certificates found
        field_print_int("Associated certificates", certsObj->nodesetval->nodeNr);
        printf("\n");
        printf(" %3s (D) %-35.35s %33.33s\n         %-49.49s %19.19s\n",
               "ID", "Common name", "Organisation", "e-mail", "Registered");
#ifdef FIREWALL
        printf("         %-44.44s %24.24s\n", "Firewall access profile", "FW Destination");
#endif
        printf(" --------------------------------------------------------------------"
               "----------\n");

        for( i = 0; i < certsObj->nodesetval->nodeNr; i++ ) {
                xmlNode *acpr = NULL;

                certnode = certsObj->nodesetval->nodeTab[i];
                if( certnode->type != XML_ELEMENT_NODE) {
                        // Skip nodes which is not element nodes
                        continue;
                }
                if( xmlStrcmp(certnode->name, (xmlChar *)"certificate") != 0 ) {
                        // Skip nodes which is not a certificate "collection"
                        continue;
                }

                acpr = xmlFindNode(certnode, "access_profile");

                printf(" %3s (%1s) %-35.35s %33.33s\n         %-49.49s %19.19s\n",
                       xmlGetAttrValue(certnode->properties, "certid"),
                       xmlGetAttrValue(certnode->properties, "depth"),
                       xmlGetNodeContent(certnode, "common_name"),
                       xmlGetNodeContent(certnode, "organisation"),
                       xmlGetNodeContent(certnode, "email"),
                       xmlGetAttrValue(certnode->properties, "registered"));
#ifdef FIREWALL
                printf("         %-44.44s %24.24s\n",
                       defaultValue(xmlExtractContent(acpr), "(not set)"),
                       defaultValue(xmlGetAttrValue(acpr->properties, "fwdestination"), "-"));
#endif
                if( (i+1) < certsObj->nodesetval->nodeNr ) {
                        printf("\n");
                }
        }
        printf(" --------------------------------------------------------------------"
               "----------\n");

        xmlXPathFreeObject(certsObj);
}

void xmlPrint_lastlog(xmlXPathContext *xpathCTX, int verb, const char *xpath) {
        xmlXPathObject *lastlogObj = NULL;
        int i = 0;
        char tmp[66];

        // Find the certificates in the given XPath query
        lastlogObj = xmlXPathEvalExpression((xmlChar *)xpath, xpathCTX);
        if( lastlogObj == NULL ) {
                fprintf(stderr,"Error: unable to evaluate xpath expression \"%s\"\n", xpath);
                return;
        }

        // If no certs were found, inform and exit
        if( lastlogObj->nodesetval->nodeNr == 0 ) {
                printf("No lastlog entries found.\n");
                printf("\n");
                xmlXPathFreeObject(lastlogObj);
                return;
        }

        memset(&tmp, 0, 66);
        printf(" %-10.10s %-22.22s   %19.19s   %19.19s\n",
               "Status", "Login", "Logout", "Session closed");
        if( verb == 1 ) {
                printf(" %-10.10s %-22.22s   %19.19s   %19.19s\n",
                       "Protocol", "Remote:port", "VPN MAC", "VPN IP");
                printf(" %-37.37s   %37.37s\n", "Common name", "Organisation");
#ifdef FIREWALL
                printf(" %-37.37s   %37.37s\n", "Firewall access profile", "FW Destination");
#endif
        }
        printf("---------------------------------------------------------------------"
               "----------\n");

        for( i = 0; i < lastlogObj->nodesetval->nodeNr; i++ ) {
                xmlNode *session_n = lastlogObj->nodesetval->nodeTab[i];
                xmlNode *conn = NULL, *cert = NULL, *acpr;

                if( (session_n == NULL) || (session_n->type != XML_ELEMENT_NODE) ) {
                        continue;
                }

                conn = xmlFindNode(session_n, "connection");
                cert = xmlFindNode(session_n, "certificate");
                acpr = xmlFindNode(cert, "access_profile");

                printf(" %-10.10s %-22.22s   %19.19s   %19.19s\n",
                       xmlGetAttrValue(session_n->properties, "session_status"),
                       xmlGetNodeContent(session_n, "login"),
                       defaultValue(xmlGetNodeContent(session_n, "logout"), "-"),
                       defaultValue(xmlGetNodeContent(session_n, "session_closed"), "-")
                       );

                if( verb == 1 ) {
                        snprintf(tmp, 64, "%s:%s",
                                 xmlGetNodeContent(conn, "remote_host"),
                                 xmlGetNodeContent(conn, "remote_port"));
                        printf(" %-10.10s %-22.22s   %19.19s   %19.19s\n",
                               xmlGetNodeContent(conn, "protocol"),
                               tmp,
                               defaultValue(xmlGetNodeContent(conn, "vpn_macaddr"), "(not available)"),
                               xmlGetNodeContent(conn, "vpn_ipaddr")
                               );

                        printf(" %-37.37s   %37.37s\n",
                               xmlGetNodeContent(cert, "common_name"),
                               xmlGetNodeContent(cert, "organisation")
                               );
#ifdef FIREWALL
                        printf(" %-37.37s   %37.37s\n",
                               defaultValue(xmlExtractContent(acpr), "(not set)"),
                               defaultValue(xmlGetAttrValue(acpr->properties, "fwdestination"), "-")
                               );
#endif
                        if( (i+1) < lastlogObj->nodesetval->nodeNr ) {
                                printf("\n");
                        }
                }
        }

        printf("---------------------------------------------------------------------"
               "----------\n");

        xmlXPathFreeObject(lastlogObj);
}


// Show account information for a particular user
int show_user(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        xmlXPathContext *user_XP = NULL;
        int i, crit_set = 0, lastlog_verb = 0;
        long int show_info = USERINFO_user | USERINFO_certs;
        xmlDoc *user_xml = NULL, *srch_xml = NULL;
        xmlNode *srch_root = NULL, *user_n = NULL;

        e_options activargs[] = {
                {"--uid", "-i", 1},
                {"--username", "-u", 1},
                {"--lastlog", "-l", 0},
                {"--lastlog-details", "-L", 0},
                {"--attempts", "-a", 0},
                {"--blacklist", "-b", 0}, // Alias for -a | --attempts
                {"--help", "-h", 0},
                {NULL, NULL, 0}
        };

        assert((ctx != NULL) && (ctx->dbc != NULL) && (ctx->dbc->config != NULL));

        // Create a fieldMapping XML document, used for searching the user database
        eurephiaXML_CreateDoc(ctx, 1, "fieldMapping", &srch_xml, &srch_root);
        xmlNewProp(srch_root, (xmlChar *) "table", (xmlChar *)"users"); // Which table to search in


        // Argument parsing
        crit_set = 0;
        for( i = 1; i < argc; i++ ) {
                switch( eurephia_getopt(&i, argc, argv, activargs) ) {
                case 'i':
                        if( atoi_nullsafe(optargs[0]) == 0 ) {
                                fprintf(stderr, "%s: Invalid user id\n", MODULE);
                                return 1;
                        }
                        xmlNewChild(srch_root, NULL, (xmlChar *)"uid", (xmlChar *) optargs[0]);
                        crit_set++;
                        break;

                case 'u':
                        if( strlen_nullsafe(optargs[0]) < 3 ) {
                                fprintf(stderr, "%s: User name too short\n", MODULE);
                                return 1;
                        }
                        xmlNewChild(srch_root, NULL, (xmlChar *)"username", (xmlChar *)optargs[0]);
                        crit_set++;
                        break;

                case 'a':
                case 'b':
                        show_info = USERINFO_attempts | USERINFO_blacklist;
                        break;

                case 'L':
                        lastlog_verb = 1;
                case 'l':
                        show_info = USERINFO_lastlog;
                        break;

                case 'h':
                        display_users_help('s');
                        return 0;

                default:
                        return 1;
                }
        }

        // Check if we have the needed search criterias
        if( crit_set == 0 ) {
                fprintf(stderr,
                        "%s:  Missing required parameter.  You must provide either user id or user name\n",
                        MODULE);
                xmlFreeDoc(srch_xml);
                return 1;
        }

        if( crit_set > 1 ) {
                fprintf(stderr,
                        "%s: You cannot have several search criterias (-i | -u)\n", MODULE);
                xmlFreeDoc(srch_xml);
                return 1;
        }

        // Search and find the user which was requested
        if( (user_xml = eDBadminGetUserInfo(ctx, show_info, srch_xml)) == NULL )  {
                fprintf(stderr, "%s: User not found\n", MODULE);
                return 1;
        }
        xmlFreeDoc(srch_xml);

        user_n = eurephiaXML_getRoot(ctx, user_xml, "user", 1);
        if( user_n == NULL ) {
                fprintf(stderr, "Could not retrieve valid data\n");
                xmlFreeDoc(user_xml);
                return 1;
        }

        // Create a XPath context for functions which users XPath to locate info
        user_XP = xmlXPathNewContext(user_xml);
        if( user_XP == NULL ) {
                fprintf(stderr,"Error: unable to create new XPath context\n");
                return 1;
        }

        if( show_info & USERINFO_user ) {
                xmlNode *lastacc = NULL;

                lastacc = xmlFindNode(user_n, "last_accessed");

                field_print_str("User id",       xmlGetAttrValue(user_n->properties, "uid"));
                field_print_str("User name",     xmlGetNodeContent(user_n, "username"));
                field_print_str("Login count",   xmlGetAttrValue(lastacc->properties, "logincount"));
                field_print_str("Last accessed", xmlExtractContent(lastacc));
                field_print_str("Activated",     xmlGetNodeContent(user_n, "activated"));
                field_print_str("Dectivated",    xmlGetNodeContent(user_n, "deactivated"));
                field_print_str("Flags",         xmlFlags2str(user_XP, "/eurephia/user/flags/flag"));
                printf("\n");
        }

        // Show associated certificates if we was asked to show this info
        if( show_info & USERINFO_certs ) {
                xmlPrint_certs(user_XP, "/eurephia/user/certificates/certificate");
        }

        if( show_info & USERINFO_lastlog ) {
                printf("** Lastlog entries for %s\n\n", xmlGetNodeContent(user_n, "username"));
                xmlPrint_lastlog(user_XP, lastlog_verb, "/eurephia/user/lastlog/session");
        }

        if( (show_info & USERINFO_attempts) || (show_info & USERINFO_blacklist) ) {
                xmlNode *atmpt = NULL, *blackl = NULL;

                atmpt  = xmlFindNode(user_n, "attempts");
                blackl = xmlFindNode(user_n, "blacklist");

                if( atmpt->children != NULL ) {
                        field_print_str("Login attempt information","");
                              field_print_str("Failed attempts", xmlGetAttrValue(atmpt->properties, "attempts"));
                        field_print_str("First attempt",   xmlGetNodeContent(atmpt, "first_attempt"));
                        field_print_str("Last attempt",    xmlGetNodeContent(atmpt, "last_attempt"));
                } else {
                        field_print_str("Login attempt information","Nothing registered");
                }
                printf("\n");

                if( blackl->children != NULL) {
                        field_print_str("Blacklist information","");
                        field_print_str("Blacklisted",     xmlGetNodeContent(blackl, "blacklisted"));
                        field_print_str("Last attempt",    xmlGetNodeContent(blackl, "last_accessed"));
                } else {
                        field_print_str("Blacklist information","Nothing registered");
                }
                printf("\n");
        }

        // Clean up
        xmlXPathFreeContext(user_XP);
        xmlFreeDoc(user_xml);

        return 0;
}


// This function handles activation, deactivation and deletion of an account
int account_activation(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        xmlDoc *user_xml = NULL, *update_xml = NULL, *srch_xml = NULL;
        xmlNode *user_n = NULL, *update_n = NULL, *srch_root = NULL, *tmp = NULL;
        char *uid_str = NULL, *activated = NULL, *deactivated = NULL, *actmode_str = NULL;
        int i, actmode = 0, rc = 0, crit_set = 0;

        e_options activargs[] = {
                {"--uid", "-i", 1},
                {"--username", "-u", 1},
                {"--help", "-h", 0},
                {NULL, NULL, 0}
        };

        assert((ctx != NULL) && (ctx->dbc != NULL) && (ctx->dbc->config != NULL));

        if( (strcmp(argv[0], "--activate") == 0) || (strcmp(argv[0], "-a") == 0) ) {
                actmode = 'a';
                actmode_str = "activated";
        } else if( (strcmp(argv[0], "--deactivate") == 0) || (strcmp(argv[0], "-d") == 0) ) {
                actmode = 'd';
                actmode_str = "deactivated";
        } else if( (strcmp(argv[0], "--delete") == 0) || (strcmp(argv[0], "-D") == 0) ) {
                actmode = 'D';
                actmode_str = "deleted";
        } else {
                fprintf(stderr, "%s: System error - illegal users mode'%s'\n", MODULE, argv[0]);
                return 1;
        }

        // Create a fieldMapping XML document, used for searching the user database
        eurephiaXML_CreateDoc(ctx, 1, "fieldMapping", &srch_xml, &srch_root);
        xmlNewProp(srch_root, (xmlChar *) "table", (xmlChar *)"users"); // Which table to search in

        // Argument parsing
        crit_set = 0;
        for( i = 1; i < argc; i++ ) {
                switch( eurephia_getopt(&i, argc, argv, activargs) ) {
                case 'i':
                        if( atoi_nullsafe(optargs[0]) == 0 ) {
                                fprintf(stderr, "%s: Invalid user id\n", MODULE);
                                return 1;
                        }
                        xmlNewChild(srch_root, NULL, (xmlChar *)"uid", (xmlChar *) optargs[0]);
                        crit_set++;
                        break;

                case 'u':
                        if( strlen_nullsafe(optargs[0]) < 3 ) {
                                fprintf(stderr, "%s: User name too short\n", MODULE);
                                return 1;
                        }
                        xmlNewChild(srch_root, NULL, (xmlChar *)"username", (xmlChar *)optargs[0]);
                        crit_set++;
                        break;

                case 'h':
                        display_users_help(actmode);
                        return 0;

                default:
                        return 1;
                }
        }

        // Check if we have the needed search criterias
        if( crit_set == 0 ) {
                fprintf(stderr,
                        "%s:  Missing required parameter.  You must provide either user id or user name\n",
                        MODULE);
                xmlFreeDoc(srch_xml);
                return 1;
        }

        if( crit_set > 1 ) {
                fprintf(stderr,
                        "%s: You cannot have several search criterias (-i | -u)\n", MODULE);
                xmlFreeDoc(srch_xml);
                return 1;
        }

        // Search and find the user which was requested
        if( (user_xml = eDBadminGetUserInfo(ctx, USERINFO_user, srch_xml)) == NULL )  {
                fprintf(stderr, "%s: User not found\n", MODULE);
                xmlFreeDoc(srch_xml);
                return 1;
        }
        xmlFreeDoc(srch_xml);

        // Parse the user information we received
        user_n = eurephiaXML_getRoot(ctx, user_xml, "user", 1);
        if( user_n == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "%s: Could not find user node in the XML document", MODULE);
                xmlFreeDoc(user_xml);
                return 1;
        }

        uid_str     = xmlGetAttrValue(user_n->properties, "uid");
        activated   = defaultValue(xmlGetNodeContent(user_n, "activated"), NULL);
        deactivated = defaultValue(xmlGetNodeContent(user_n, "deactivated"), NULL);

        // Create a new XML document which will be used to update the user account
        eurephiaXML_CreateDoc(ctx, 1, "update_user", &update_xml, &update_n);
        assert( (update_xml != NULL) && (update_n != NULL) );
        xmlNewProp(update_n, (xmlChar *) "uid", (xmlChar *) uid_str);

        // Add fieldMapping - to correctly map eurephia fields into the database fields
        update_n = xmlNewChild(update_n, NULL, (xmlChar *) "fieldMapping", NULL);
        xmlNewProp(update_n, (xmlChar *) "table", (xmlChar *) "users");

        switch( actmode ) {
        case 'a':  // Activate a user account
                if( (activated != NULL)  && (deactivated == NULL) ) {
                        printf("User account is already active\n");
                        goto exit;
                } else {
                        // Set activated field to now()
                        xmlNewChild(update_n, NULL,
                                     (xmlChar *) "activated", (xmlChar *) "CURRENT_TIMESTAMP");

                        // Remove deactivated flag
                        tmp = xmlNewChild(update_n, NULL,(xmlChar *) "deactivated", NULL);
                        xmlNewProp(tmp, (xmlChar *) "setnull", (xmlChar *) "1");
                }

                // Do the update of the user account
                rc = eDBadminUpdateUser(ctx, atoi_nullsafe(uid_str), update_xml);
                break;

        case 'd':  // Deactivate a user account
                if( (activated != NULL)  && (deactivated != NULL) ) {
                        printf("User account is already deactived\n");
                        goto exit;
                } else if( (activated != NULL) ) {
                        // Set deactivated to now()
                        xmlNewChild(update_n, NULL,
                                     (xmlChar *) "deactivated", (xmlChar *) "CURRENT_TIMESTAMP");

                } else {
                        fprintf(stderr, "%s: User account is not activated yet\n", MODULE);
                        goto exit;
                }

                // Do the update of the user account
                rc = eDBadminUpdateUser(ctx, atoi_nullsafe(uid_str), update_xml);
                break;

        case 'D':  // Delete user account
                xmlFreeDoc(update_xml); // We need another XML doc to delete users

                eurephiaXML_CreateDoc(ctx, 1, "delete_user", &update_xml, &update_n);
                xmlNewProp(update_n, (xmlChar *) "uid", (xmlChar *) uid_str);

                rc = eDBadminDeleteUser(ctx, atoi_nullsafe(uid_str), update_xml);
                break;
        }

        if( rc == 1 ) {
                printf("User account is %s\n", actmode_str);
        } else {
                fprintf(stderr, "%s: Operation failed\n", MODULE);
        }

 exit:
        xmlFreeDoc(user_xml);
        xmlFreeDoc(update_xml);
        return (rc != 1);
}

int add_user(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        xmlDoc *user_xml = NULL;
        xmlNode *node = NULL, *node2 = NULL;
        struct stat cert_stat;
        int i = 0, certid = 0, rc = 0;
        char *uname = NULL, *passwd = NULL, *certfile = NULL, *digest = NULL;

        e_options addu_args[] = {
                {"--username", "-u", 1},
                {"--password", "-P", 1},
                {"--certid",   "-C", 1},
                {"--certfile", "-c", 1},
                {"--digest",   "-d", 1},
                {"--help", "-h", 0},
                {NULL, NULL, 0}
        };

        assert((ctx != NULL) && (ctx->dbc != NULL) && (ctx->dbc->config != NULL));

        // Parse arguments
        for( i = 1; i < argc; i++ ) {
                switch( eurephia_getopt(&i, argc, argv, addu_args) ) {
                case 'u':
                        if( strlen_nullsafe(optargs[0]) < 3 ) {
                                fprintf(stderr, "%s: username is too short\n", MODULE);
                                return 1;
                        }
                        uname = optargs[0];
                        break;

                case 'P':
                        if( strlen_nullsafe(optargs[0]) < 4 ) {
                                fprintf(stderr, "%s: password is too short\n", MODULE);
                                return 1;
                        }
                        passwd = strdup_nullsafe(optargs[0]);
                        break;

                case 'C':
                        if( (certid = atoi_nullsafe(optargs[0])) < 1 ) {
                                fprintf(stderr, "%s: Invalid certid (numeric value > 0)\n", MODULE);
                                return 1;
                        }
                        break;

                case 'c': // Check if certfile exists and is readable for us
                        if( strlen_nullsafe(optargs[0]) < 1 ) {
                                fprintf(stderr, "%s: certfile is too short\n", MODULE);
                                return 1;
                        }
                        certfile = optargs[0];

                        if( stat(certfile, &cert_stat) == -1 ) {
                                fprintf(stderr, "%s: Could not access certfile: %s (%s)\n", MODULE,
                                        certfile, strerror(errno));
                                return 1;
                        }

                        if( cert_stat.st_size == 0 ) {
                                fprintf(stderr, "%s: certfile '%s' is empty\n", MODULE, certfile);
                                return 1;
                        }
                        break;

                case 'd':
                        if( strlen_nullsafe(optargs[0]) < 59 ) {
                                fprintf(stderr, "%s: Certificate digest is too short\n", MODULE);
                                return 1;
                        }
                        digest = optargs[0];
                        break;

                case 'h':
                        display_users_help('A');
                        return 0;

                default:
                        return 1;
                }
        }

        // Make sure received arguments are sane
        if( uname == NULL ) {
                fprintf(stderr, "%s: Missing user name\n", MODULE);
                return 1;
        }

        if( ((certid > 0) && (digest != NULL))
            || ((certid > 0) && (certfile != NULL))
            || ((digest != NULL) && (certfile != NULL)) ) {
                fprintf(stderr, "%s: --certid, --certfile and --digest cannot be used together\n", MODULE);
                return 1;
        }

        // If we do not have a password .... ask for password via console
        if( passwd == NULL ) {
                char *chkpwd = NULL;

                passwd = (char *) malloc(66);
                assert(passwd != NULL);
                memset(passwd, 0, 66);

                chkpwd = (char *) malloc(66);
                assert(chkpwd != NULL);
                memset(chkpwd, 0, 66);

                get_console_input(passwd, 64, "Password for user:", 1);
                if( strlen_nullsafe(passwd) < 4 ) {
                        free_nullsafe(passwd);
                        fprintf(stderr, "%s: Password is too short\n", MODULE);
                        return 1;
                }

                get_console_input(chkpwd, 64, "Verify password for user:", 1);
                if( strcmp(passwd, chkpwd) != 0 ) {
                        free_nullsafe(passwd);
                        free_nullsafe(chkpwd);
                        fprintf(stderr, "%s: Passwords didn't match\n", MODULE);
                        return 1;
                }
                free_nullsafe(chkpwd);
        }


        // Prepare add user XML document with fieldMapping
        eurephiaXML_CreateDoc(ctx, 1, "add_user", &user_xml, &node);
        node = xmlNewChild(node, NULL, (xmlChar *) "fieldMapping", NULL);
        xmlNewProp(node, (xmlChar *) "table", (xmlChar *) "users");

        xmlNewChild(node, NULL, (xmlChar *) "username", (xmlChar *) uname);
        node2 = xmlNewChild(node, NULL, (xmlChar *) "password", (xmlChar *) passwd);
        xmlNewProp(node2, (xmlChar *) "pwhash", (xmlChar *) "none");

        // Add the user
        rc = eDBadminAddUser(ctx, user_xml);
        fprintf(stdout, "%s: %s\n", MODULE,
                (rc == 1 ? "User registered successfully" : "Failed to register user"));
        memset(passwd, 0, strlen_nullsafe(passwd));
        free_nullsafe(passwd);
        xmlFreeDoc(user_xml);

        return (rc != 1);
}


int cmd_Users(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        char **mode_argv;
        int i, mode_argc = 0, rc = 0;
        int (*mode_fnc) (eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv);

        e_options modeargs[] = {
                {"--list", "-l", 0},
                {"--show", "-s", 0},
                {"--activate", "-a", 0},
                {"--deactivate", "-d", 0},
                {"--add", "-A", 0},
                {"--delete", "-D", 0},
                {"--password", "-p", 0},
                {"--help", "-h", 0},
                {NULL, NULL, 0}
        };

        assert((ctx != NULL) && (ctx->dbc != NULL) && (ctx->dbc->config != NULL));
        mode_fnc = NULL;
        for( i = 1; i < argc; i++ ) {
                switch( eurephia_getopt(&i, argc, argv, modeargs) ) {
                case 'l':
                        mode_fnc = list_users;
                        break;

                case 's':
                        mode_fnc = show_user;
                        break;

                case 'a':
                        mode_fnc = account_activation;
                        break;

                case 'd':
                        mode_fnc = account_activation;
                        break;

                case 'h':
                        mode_fnc = help_Users2;
                        break;

                case 'A':
                        mode_fnc = add_user;
                        break;

                case 'D':
                        mode_fnc = account_activation;
                        break;
                default:
                        break;
                }
                if( mode_fnc != NULL ) {
                        break;
                }
        }

        // If we do not have any known mode defined, exit with error
        if( mode_fnc == NULL )  {
                fprintf(stderr, "Unknown argument.  No mode given\n");
                return 1;
        }

        // Allocate memory for our arguments being sent to the mode function
        mode_argv = (char **) calloc(sizeof(char *), (argc - i)+2);
        assert(mode_argv != NULL);

        // Copy over only the arguments needed for the mode
        mode_argc = eurephia_arraycp(i, argc, argv, mode_argv, (argc - i));

        // Call the mode function
        rc = mode_fnc(ctx, sess, cfg, mode_argc, mode_argv);
        free_nullsafe(mode_argv);

        return rc;
}