summaryrefslogtreecommitdiffstats
path: root/xlators/nfs/server/src/netgroups.c
blob: 1003b72ef8ce2b21acc55d83de62b0513ea3b3a7 (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
/*
   Copyright 2014-present Facebook. All Rights Reserved

   This file is part of GlusterFS.

   Author :
   Shreyas Siravara <shreyas.siravara@gmail.com>

   This file is licensed to you under your choice of the GNU Lesser
   General Public License, version 3 or any later version (LGPLv3 or
   later), or the GNU General Public License, version 2 (GPLv2),in all
   cases as published by the Free Software Foundation.
*/

#include "netgroups.h"
#include "parse-utils.h"
#include "nfs-messages.h"

static void _nge_print (const struct netgroup_entry *nge);
static void _netgroup_entry_deinit (struct netgroup_entry *ptr);
static void _netgroup_host_deinit (struct netgroup_host *host);

static dict_t *__deleted_entries;
static struct parser *ng_file_parser;
static struct parser *ng_host_parser;

/**
 * _ng_init_parser -- Initialize the parsers used in this file
 *
 * @return: success: 0 (on success the parsers are initialized)
 *          failure: -1
 */
static int
_ng_init_parsers ()
{
        int ret = -1;

        /* Initialize the parsers. The only reason this should
         * ever fail is because of 1) memory allocation errors
         * 2) the regex in netgroups.h has been changed and no
         * longer compiles.
         */
        ng_file_parser = parser_init (NG_FILE_PARSE_REGEX);
        if (!ng_file_parser)
                goto out;

        ng_host_parser = parser_init (NG_HOST_PARSE_REGEX);
        if (!ng_host_parser)
                goto out;

        ret = 0;
out:
        return ret;
}

/**
 * _ng_deinit_parsers - Free the parsers used in this file
 */
static void
_ng_deinit_parsers ()
{
        parser_deinit (ng_file_parser);
        parser_deinit (ng_host_parser);
}

/**
 * _netgroups_file_init - allocate a netgroup file struct
 * @return: success: Pointer to an allocated netgroup file struct
 *          failure: NULL
 *
 * Not for external use.
 */
static struct netgroups_file *
_netgroups_file_init ()
{
        struct netgroups_file *file  = GF_MALLOC (sizeof (*file),
                                                  gf_common_mt_nfs_netgroups);

        if (!file)
                goto out;

        file->filename     = NULL;
        file->ng_file_dict = NULL;
out:
        return file;
}

/**
 * __ngf_free_walk - walk the netgroup file dict and free each element
 *
 * This is passed as a function pointer to dict_foreach ()
 *
 * @dict: the dict we are walking
 * @key : the key we are processing in the dict
 * @val : the corresponding value in the dict
 * @tmp : Pointer to additional data that may be passed in (not used)
 *
 * @return : Nothing
 *
 * Not for external use.
 */
static int
__ngf_free_walk (dict_t *dict, char *key, data_t *val, void *tmp)
{
        struct netgroup_entry        *nge = NULL;

        if (val) {
                nge = (struct netgroup_entry *)val->data;
                _netgroup_entry_deinit (nge);
                val->data = NULL;
                dict_del (dict, key); /* Remove the key from this dict */
        }
        return 0;
}

/**
 * __deleted_entries_free_walk - free the strings in the temporary dict
 *
 * This is passed as a function pointer to dict_foreach ()
 *
 * @dict: the dict we are walking
 * @key : the key we are processing in the dict
 * @val : the corresponding value in the dict
 * @tmp : Pointer to additional data that may be passed in (not used)
 *
 * @return : Nothing
 *
 * Not for external use.
 */
static int
__deleted_entries_free_walk (dict_t *dict, char *key, data_t *val, void *tmp)
{
        dict_del (dict, key);
        return 0;
}

/**
 * ng_file_deinit - Free the netgroup file struct and any memory
 * that is allocated for its members.
 *
 * @ngfile : Pointer to the netgroup file structure that needs to be freed
 * @return : Nothing
 *
 * External facing function.
 *
 * Should be called by the caller of ng_file_parse () in order to free
 * the memory allocated when parsing the file.
 */
void
ng_file_deinit (struct netgroups_file *ngfile)
{
        GF_VALIDATE_OR_GOTO (GF_NG, ngfile, out);

        __deleted_entries = dict_new ();
        GF_VALIDATE_OR_GOTO (GF_NG, __deleted_entries, out);

        GF_FREE (ngfile->filename);
        dict_foreach (ngfile->ng_file_dict, __ngf_free_walk, NULL);
        dict_unref (ngfile->ng_file_dict);
        GF_FREE (ngfile);

        /* Clean up temporary dict we used to store "freed" names */
        dict_foreach (__deleted_entries, __deleted_entries_free_walk, NULL);
        dict_unref (__deleted_entries);
        __deleted_entries = NULL;
out:
        return;
}

/**
 * _netgroup_entry_init - Initializes a netgroup entry struct.
 * A netgroup entry struct represents a single line in a netgroups file.
 *
 * @return : success: Pointer to a netgroup entry struct
 *         : failure: NULL
 *
 * Not for external use.
 */
static struct netgroup_entry *
_netgroup_entry_init ()
{
        struct netgroup_entry *entry = GF_CALLOC (1, sizeof (*entry),
                                                  gf_common_mt_nfs_netgroups);
        return entry;
}

/**
 * __ngh_free_walk - walk the netgroup host dict and free the host
 * structure associated with the key.
 *
 * This is passed as a function pointer to dict_foreach ()
 *
 * @dict: the dict we are walking
 * @key : the key we are processing in the dict
 * @val : the corresponding value in the dict
 * @tmp : Pointer to additional data that may be passed in (not used)
 *
 * @return : Nothing
 *
 * Not for external use.
 */
static int
__ngh_free_walk (dict_t *dict, char *key, data_t *val, void *tmp)
{
        struct netgroup_host *ngh = NULL;

        if (val) {
                ngh = (struct netgroup_host *)val->data;
                _netgroup_host_deinit (ngh);
                val->data = NULL;
                dict_del (dict, key);
        }
        return 0;
}

/**
 * __nge_free_walk - walk the netgroup entry dict and free the netgroup entry
 * structure associated with the key.
 *
 * This is passed as a function pointer to dict_foreach ()
 *
 * @dict: the dict we are walking
 * @key : the key we are processing in the dict
 * @val : the corresponding value in the dict
 * @tmp : Pointer to additional data that may be passed in (not used)
 *
 * @return : Nothing
 *
 * Not for external use.
 */
static int
__nge_free_walk (dict_t *dict, char *key, data_t *val, void *tmp)
{
        struct netgroup_entry *nge = NULL;

        GF_VALIDATE_OR_GOTO (GF_NG, dict, out);

        if (val) {
                nge = (struct netgroup_entry *)val->data;
                if (!dict_get (__deleted_entries, key)) {
                        _netgroup_entry_deinit (nge);
                        val->data = NULL;
                }
                dict_del (dict, key);
        }

out:
        return 0;
}

/**
 * _netgroup_entry_deinit - Free memory pointed to by the parameter
 *                          and any memory allocated for members
 *                          in the struct. This function walks the
 *                          netgroups and hosts dicts if they
 *                          are allocated and frees them.
 *
 * @ngentry: Pointer to a netgroup entry struct that needs to be freed
 *
 * @return : Nothing
 *
 * Not for external use.
 */
static void
_netgroup_entry_deinit (struct netgroup_entry *ngentry)
{
        dict_t  *ng_dict   = NULL;
        dict_t  *host_dict = NULL;
        char    *name      = NULL;
        data_t  *dint      = NULL;

        if (!ngentry)
                return;

        ng_dict = ngentry->netgroup_ngs;
        host_dict = ngentry->netgroup_hosts;

        if (ng_dict) {
                /* Free the dict of netgroup entries */
                dict_foreach (ng_dict, __nge_free_walk, NULL);
                dict_unref (ng_dict);
                ngentry->netgroup_ngs = NULL;
        }

        if (host_dict) {
                /* Free the dict of host entries */
                dict_foreach (host_dict, __ngh_free_walk, NULL);
                dict_unref (host_dict);
                ngentry->netgroup_hosts = NULL;
        }

        if (ngentry->netgroup_name) {
                /* Keep track of the netgroup names we've deallocated
                 * We need to do this because of the nature of this data
                 * structure. This data structure may hold multiple
                 * pointers to an already freed object, but these are
                 * uniquely identifiable by the name. We keep track
                 * of these names so when we encounter a key who has
                 * an association to an already freed object, we don't
                 * free it twice.
                 */
                name = strdupa (ngentry->netgroup_name);

                dint = int_to_data (1);
                dict_set (__deleted_entries, name, dint);

                GF_FREE (ngentry->netgroup_name);
                ngentry->netgroup_name = NULL;
        }

        GF_FREE (ngentry);
}

/**
 * _netgroup_host_init - Initializes a netgroup host structure.
 * A netgroup host struct represents an item in a line of a netgroups file that
 * looks like this : (hostname,user,domain)
 *
 * @return : success: Pointer to a netgroup host struct
 *         : failure: NULL
 *
 * Not for external use.
 */
static struct netgroup_host *
_netgroup_host_init ()
{
        struct netgroup_host *host = GF_CALLOC (1, sizeof (*host),
                                                gf_common_mt_nfs_netgroups);
        return host;
}

/**
 * _netgroup_host_deinit - Free memory pointed to by the parameter
 * and any memory allocated for members in the struct.
 *
 * @nghost : Pointer to a netgroup host struct that needs to be freed
 *
 * @return : Nothing
 *
 * Not for external use.
 */
static void
_netgroup_host_deinit (struct netgroup_host *host)
{
        /* Validate args */
        GF_VALIDATE_OR_GOTO (GF_NG, host, err);

        GF_FREE (host->hostname);
        host->hostname = NULL;

        GF_FREE (host->user);
        host->user = NULL;

        GF_FREE (host->domain);
        host->domain = NULL;

        GF_FREE (host);
err:
        return;
}

/**
 * _nge_dict_get - Lookup a netgroup entry from the dict based
 *                 on the netgroup name.
 *
 * @dict   : The dict we are looking up from. This function makes the
 *           assumption that the type of underlying data in the dict is of type
 *           struct netgroup_entry. The behavior is not defined otherwise.
 *
 * @ngname : Key used to lookup in the dict.
 *
 * @return : success: Pointer to a netgroup entry
 *           failure: NULL (if no such key exists in the dict)
 *
 * Not for external use.
 */
static struct netgroup_entry *
_nge_dict_get (dict_t *dict, const char *ngname)
{
        data_t *ngdata = NULL;

        /* Validate args */
        GF_VALIDATE_OR_GOTO (GF_NG, dict, err);
        GF_VALIDATE_OR_GOTO (GF_NG, ngname, err);

        ngdata = dict_get (dict, (char *)ngname);
        if (ngdata)
                return (struct netgroup_entry *)ngdata->data;
err:
        return NULL;
}

/**
 * _nge_dict_insert - Insert a netgroup entry into the dict using
 *                    the netgroup name as the key.
 *
 * @dict   : The dict we are inserting into.
 *
 * @nge    : The data to insert into the dict.
 *
 * @return : nothing
 *
 * Not for external use.
 */
static void
_nge_dict_insert (dict_t *dict, struct netgroup_entry *nge)
{
        data_t *ngdata = NULL;

        GF_VALIDATE_OR_GOTO (GF_NG, dict, err);
        GF_VALIDATE_OR_GOTO (GF_NG, nge, err);

        ngdata = bin_to_data (nge, sizeof (*nge));
        dict_set (dict, nge->netgroup_name, ngdata);
err:
        return;
}

/**
 * _ngh_dict_get - Lookup a netgroup host entry from the dict based
 *                 on the hostname.
 *
 * @dict   : The dict we are looking up from. This function makes the
 *           assumption that the type of underlying data in the dict is of type
 *           struct netgroup_host. The behavior is not defined otherwise.
 *
 * @ngname : Key used to lookup in the dict.
 *
 * @return : success: Pointer to a netgroup host entry
 *           failure: NULL (if no such key exists in the dict)
 *
 * Externally usable.
 */
struct netgroup_host *
ngh_dict_get (dict_t *dict, const char *hostname)
{
        data_t *ngdata = NULL;

        GF_VALIDATE_OR_GOTO (GF_NG, dict, err);
        GF_VALIDATE_OR_GOTO (GF_NG, hostname, err);

        ngdata = dict_get (dict, (char *)hostname);
        if (!ngdata)
                goto err;

        return (struct netgroup_host *)ngdata->data;

err:
        return NULL;
}

/**
 * _ngh_dict_insert - Insert a netgroup host entry into the dict using
 *                    the netgroup name as the key.
 *
 * @dict   : The dict we are inserting into.
 *
 * @nge    : The data to insert into the dict.
 *
 * @return : nothing
 *
 * Not for external use.
 */
static void
_ngh_dict_insert (dict_t *dict, struct netgroup_host *ngh)
{
        data_t *ngdata = NULL;

        /* Validate args */
        GF_VALIDATE_OR_GOTO (GF_NG, dict, err);
        GF_VALIDATE_OR_GOTO (GF_NG, ngh, err);

        ngdata = bin_to_data (ngh, sizeof (*ngh));
        dict_set (dict, ngh->hostname, ngdata);
err:
        return;
}

/**
 * _ngh_print - Prints the netgroup host in the
 *              format '(hostname,user,domain)'
 *
 * @ngh    : The netgroup host to print out
 *
 * @return : nothing
 *
 * Not for external use.
 */
static void
_ngh_print (const struct netgroup_host *ngh)
{
        /* Validate args */
        GF_VALIDATE_OR_GOTO (GF_NG, ngh, err);

        printf ("(%s,%s,%s)", ngh->hostname, ngh->user ? ngh->user : "",
                ngh->domain ? ngh->domain : "");
err:
        return;
}

/**
 * __nge_print_walk - walk the netgroup entry dict and print each entry
 *                    associated with the key. This function prints
 *                    entries of type 'struct netgroup_entry'.
 *
 * This is passed as a function pointer to dict_foreach ()
 *
 * @dict: the dict we are walking
 * @key : the key we are processing in the dict
 * @val : the corresponding value in the dict
 * @tmp : Pointer to additional data that may be passed in (not used)
 *
 * @return : Nothing
 *
 * Not for external use.
 */
static int
__nge_print_walk (dict_t *dict, char *key, data_t *val, void *tmp)
{
        if (val)
                _nge_print ((struct netgroup_entry *)val->data);

        return 0;
}

/**
 * __ngh_print_walk - walk the netgroup entry dict and print each entry
 *                    associated with the key. This function prints entries
 *                    of type 'struct netgroup_host'
 *
 * This is passed as a function pointer to dict_foreach (),
 * which is called from _nge_print ().
 *
 * @dict: the dict we are walking
 * @key : the key we are processing in the dict
 * @val : the corresponding value in the dict
 * @tmp : Pointer to additional data that may be passed in (not used)
 *
 * @return : Nothing
 *
 * Not for external use.
 */
static int
__ngh_print_walk (dict_t *dict, char *key, data_t *val, void *tmp)
{
        if (val)
                _ngh_print ((struct netgroup_host *)val->data);

        return 0;
}

/**
 * _nge_print - Prints the netgroup entry in the
 *              format '<netgroup name> <following entries>'
 *
 * @ngh    : The netgroup entry to print out
 *
 * @return : nothing
 *
 * Not for external use.
 */
static void
_nge_print (const struct netgroup_entry *nge)
{
        /* Validate args */
        GF_VALIDATE_OR_GOTO (GF_NG, nge, err);

        printf ("%s ", nge->netgroup_name);
        if (nge->netgroup_ngs)
                dict_foreach (nge->netgroup_ngs, __nge_print_walk, NULL);

        if (nge->netgroup_hosts)
                dict_foreach (nge->netgroup_hosts, __ngh_print_walk, NULL);

err:
        return;
}

/**
 * __ngf_print_walk - walk through each entry in the netgroups file and print it
 *                    out. This calls helper functions _nge_print () to print
 *                    the netgroup entries.
 *
 * This is passed as a function pointer to dict_foreach (),
 * which is called from ng_file_print ().
 *
 * @dict: the dict we are walking
 * @key : the key we are processing in the dict
 * @val : the corresponding value in the dict
 * @tmp : Pointer to additional data that may be passed in (not used)
 *
 * @return : Nothing
 *
 * Not for external use.
 */
static int
__ngf_print_walk (dict_t *dict, char *key, data_t *val, void *tmp)
{
        struct netgroup_entry *snge = NULL;

        if (val) {
                snge = (struct netgroup_entry *)val->data;
                _nge_print (snge);
                printf ("\n");
        }
        return 0;
}

/**
 * ng_file_print - Prints the netgroup file in the
 *              format '<netgroup name> <following entries>', etc.
 *              The netgroup file is a dict of netgroup entries
 *              which, in turn is a combination of a other 'sub' netgroup
 *              entries and host entries. This function prints
 *              all of that out by calling the corresponding print functions
 *
 * @ngfile : The netgroup file to print out
 *
 * @return : nothing
 *
 * External facing function.
 *
 * Can be called on any valid 'struct netgroups_file *' type.
 */
void
ng_file_print (const struct netgroups_file *ngfile)
{
     dict_foreach (ngfile->ng_file_dict, __ngf_print_walk, NULL);
}

/**
 * ng_file_get_netgroup - Look up a netgroup entry from the netgroups file
 *                        based on the netgroup name and return a pointer
 *                        to the netgroup entry.
 *
 * @ngfile   : The netgroup file to lookup from.
 * @netgroup : The netgroup name used to lookup from the netgroup file.
 *
 * @return : nothing
 *
 * External facing function.
 *
 * Can be called on any valid 'struct netgroups_file *' type with a valid 'char
 * *' as the lookup key.
 */
struct netgroup_entry *
ng_file_get_netgroup (const struct netgroups_file *ngfile, const char *netgroup)
{
        data_t *ndata = NULL;

        GF_VALIDATE_OR_GOTO (GF_NG, ngfile, err);
        GF_VALIDATE_OR_GOTO (GF_NG, netgroup, err);

        ndata = dict_get (ngfile->ng_file_dict,
                          (char *)netgroup);
        if (!ndata)
                goto err;

        return (struct netgroup_entry *)ndata->data;

err:
        return NULL;
}

/**
 * __check_host_entry_str - Check if the host string which should be
 *                          in the format '(host,user,domain)' is
 *                          valid to be parsed. Currently checks
 *                          if the # of commas is correct and there
 *                          are no spaces in the string, but more
 *                          checks can be added.
 *
 * @host_str : String to check
 * @return   : success: TRUE if valid
 *             failure: FALSE if not
 *
 * Not for external use.
 */
static gf_boolean_t
__check_host_entry_str (const char *host_str)
{
        unsigned int comma_count = 0;
        unsigned int i           = 0;
        gf_boolean_t str_valid   = _gf_true;

        GF_VALIDATE_OR_GOTO (GF_NG, host_str, out);

        for (i = 0; i < strlen (host_str); i++) {
                if (host_str[i] == ',')
                        comma_count++;

                /* Spaces are not allowed in this string. e.g, (a,b,c) is valid
                 * but (a, b,c) is not.
                 */
                if (host_str[i] == ' ') {
                        str_valid = _gf_false;
                        goto out;
                }
        }

        str_valid = (comma_count == 2);
out:
        return str_valid;
}

/**
 * _parse_ng_host - Parse the netgroup host string into a netgroup host struct.
 *                  The netgroup host string is structured as follows:
 *                  (host, user, domain)
 *
 * @ng_str   : String to parse
 * @return   : success: 0 if the parsing succeeded
 *             failure: -EINVAL for bad args, -ENOMEM for allocation errors,
 *                      1 for parsing errors.
 *
 * Not for external use.
 */
static int
_parse_ng_host (char *ng_str, struct netgroup_host **ngh)
{
        struct netgroup_host *ng_host  = NULL;
        unsigned int          parts    = 0;
        char                 *match    = NULL;
        int                   ret      = -EINVAL;

        GF_VALIDATE_OR_GOTO (GF_NG, ng_str, out);
        GF_VALIDATE_OR_GOTO (GF_NG, ngh, out);

        if (!__check_host_entry_str (ng_str)) {
                ret = 1; /* Parse failed */
                goto out;
        }

        ret = parser_set_string (ng_host_parser, ng_str);
        if (ret < 0)
                goto out;

        gf_msg_trace (GF_NG, 0, "parsing host string: %s", ng_str);

        ng_host = _netgroup_host_init ();
        GF_CHECK_ALLOC (ng_host, ret, free_and_out); /* Sets ret to -ENOMEM on
                                                      * failure.
                                                      */
        while ((match = parser_get_next_match (ng_host_parser)) != NULL) {
                gf_msg_trace (GF_NG, 0, "found match: %s (parts=%d)", match,
                              parts);

                switch (parts) {
                case 0:
                        ng_host->hostname = match;
                        break;
                case 1:
                        ng_host->user = match;
                        break;
                case 2:
                        ng_host->domain = match;
                        break;
                default:
                        GF_FREE (match);
                        break;
                };

                /* We only allow three parts in the host string;
                 * The format for the string is (a,b,c)
                 */
                parts++;
                if (parts > 2)
                        break;
        }

        /* Set the parameter */
        *ngh = ng_host;
        ret = 0;

free_and_out:
        parser_unset_string (ng_host_parser);
out:
        return ret;
}

/**
 * _ng_handle_host_part - Parse the host string that looks like this :
 *                        '(dev1763.prn2.facebook.com,,)' into a host
 *                        struct and insert it into the parent netgroup's
 *                        host dict.
 * @match : The host string
 * @ngp   : The parent netgroup
 *
 * @return: success: 0 if parsing succeeded
 *          failure: -EINVAL for bad args, other errors bubbled up
 *                   from _parse_ng_host.
 *
 *
 * Not for external use.
 */
static int
_ng_handle_host_part (char *match, struct netgroup_entry *ngp)
{
        struct netgroup_host *ngh = NULL;
        int                   ret = -EINVAL;

        GF_VALIDATE_OR_GOTO (GF_NG, match, out);
        GF_VALIDATE_OR_GOTO (GF_NG, ngp, out);

        if (!ngp->netgroup_name) {
                gf_msg (GF_NG, GF_LOG_WARNING, EINVAL, NFS_MSG_INVALID_ENTRY,
                        "Invalid: Line starts with hostname!");
                goto out;
        }

        /* Parse the host string and get a struct for it */
        ret = _parse_ng_host (match, &ngh);
        if (ret < 0) {
                gf_msg (GF_NG, GF_LOG_CRITICAL, -ret, NFS_MSG_PARSE_FAIL,
                        "Critical error : %s", strerror (-ret));
                goto out;
        }
        if (ret != 0) {
                /* Cannot change to gf_msg
                 * gf_msg not giving output to STDOUT
                 * Bug id : BZ1215017
                 */
                gf_log (GF_NG, GF_LOG_WARNING,
                        "Parse error for: %s", match);
                goto out;
        }


        /* Make dict for the parent entry's netgroup hosts */
        if (!ngp->netgroup_hosts) {
                ngp->netgroup_hosts = dict_new ();
                GF_CHECK_ALLOC (ngp->netgroup_hosts, ret,
                                out);
        }

        /* Insert this entry into the parent netgroup dict */
        _ngh_dict_insert (ngp->netgroup_hosts, ngh);

out:
        return ret;
}

/**
 * _ng_handle_netgroup_part - Parse the netgroup string that should just be one
 *                            string. This may insert the netgroup into the file
 *                            struct if it does not already exist. Frees the
 *                            parameter match if the netgroup was already found
 *                            in the file.
 *
 * @match    : The netgroup string
 * @ngp      : The netgroup file we may insert the entry into
 * @ng_entry : Double pointer to the netgroup entry we want to allocate and set.
 *
 * @return: success: 0 if parsing succeeded
 *          failure: -EINVAL for bad args, other errors bubbled up
 *                   from _parse_ng_host.
 *
 *
 * Not for external use.
 */
static int
_ng_setup_netgroup_entry (char *match, struct netgroups_file *file,
                          struct netgroup_entry **ng_entry)
{
        struct netgroup_entry *nge           = NULL;
        int                    ret           = -EINVAL;

        GF_VALIDATE_OR_GOTO (GF_NG, match, out);
        GF_VALIDATE_OR_GOTO (GF_NG, file, out);
        GF_VALIDATE_OR_GOTO (GF_NG, ng_entry, out);

        nge = _netgroup_entry_init ();
        GF_CHECK_ALLOC (nge, ret, out);

        nge->netgroup_name = match;

        /* Insert this new entry into the file dict */
        _nge_dict_insert (file->ng_file_dict, nge);

        *ng_entry = nge;

        ret = 0;
out:
        return ret;
}

/**
 * _parse_ng_line - Parse a line in the netgroups file into a netgroup entry
 *                  struct. The netgroup line is structured as follows:
 *                  'netgroupx netgroupy (hosta,usera,domaina)...' OR
 *                  'netgroupx netgroupy netgroupz...'  OR
 *                  'netgroupx (hosta,usera,domaina) (hostb,userb,domainb)'
 *                  This function parses this into a netgroup entry
 *                  which will hold either a dict of netgroups and/or
 *                  a dict of hosts that make up this netgroup.
 *
 * In general terms, the data structure to represent a netgroups file
 * is a set of nested dictionaries. Each line in the netgroups file
 * is compiled into a struct netgroup_entry structure that holds a dict
 * of netgroups and a dict of hostnames. The first string in the netgroups
 * line is the parent netgroup entry and the rest of the items in the line
 * are the children of that parent netgroup entry. (Hence variables ngp
 * and nge).
 *
 * A sample netgroup file may look like this:
 *
 * async async.ash3 async.ash4
 * async.ash3 async.04.ash3
 * async04.ash3 (async001.ash3.facebook.com,,) (async002.ash3.facebook.com,,)
 *
 * _parse_ng_line will get called on each line, so on the first call to this
 * function, our data structure looks like this:
 *
 *
 * dict [
 *       'async'   --> dict [
 *                              'async.ash3'
 *                              'async.ash4'
 *                          ]
 *      ]
 *
 * On the second call to the function with the second line, our data structure
 * looks like this:
 *
 * dict [
 *       'async' --> dict [
 *                              'async.ash3' -> dict [ 'async.04.ash3' ]
 *                              'async.ash4'      ^
 *                        ]                       |
 *                                                |
 *      'async.ash3' ------------------------------
 *      ]
 *
 * And so on.
 *
 * The obvious answer to storing this file in a data structure may be a tree
 * but lookups from a tree are expensive and since we may be looking up stuff
 * in this file in the I/O path, we can't afford expensive lookups.
 *
 * @ng_str   : String to parse
 * @file     : Netgroup file to put the parsed line into
 * @ng_entry : Double pointer to struct that we are going to allocate and fill
 *
 * The string gets parsed into a structure pointed to by
 * the parameter 'ng_entry'
 *
 * @return   : success: 0 if parsing succeeded
 *             failure: NULL if not
 *
 * Not for external use.
 */
static int
_parse_ng_line (char *ng_str, struct netgroups_file *file,
                struct netgroup_entry **ng_entry)
{
        struct netgroup_entry  *ngp         = NULL; /* Parent netgroup entry */
        struct netgroup_entry  *nge         = NULL; /* Generic netgroup entry */
        char                   *match       = NULL;
        int                     ret         = -EINVAL;
        unsigned int            num_entries = 0;

        /* Validate arguments */
        GF_VALIDATE_OR_GOTO (GF_NG, ng_str, out);
        GF_VALIDATE_OR_GOTO (GF_NG, file, out);

        if (*ng_str == ' ' || *ng_str == '\0' || *ng_str == '\n') {
                ret = 0;
                goto out;
        }

        ret = parser_set_string (ng_file_parser, ng_str);
        if (ret < 0)
                goto out;

        /* This is the first name in the line, and should be the
         * parent netgroup entry.
         */
        match = parser_get_next_match (ng_file_parser);
        if (!match) {
                ret = 1;
                gf_msg (GF_NG, GF_LOG_WARNING, 0,
                        NFS_MSG_FIND_FIRST_MATCH_FAIL, "Unable to find "
                        "first match.");
                gf_msg (GF_NG, GF_LOG_WARNING, 0, NFS_MSG_PARSE_FAIL,
                        "Error parsing str: %s", ng_str);
                goto out;
        }

        /* Lookup to see if the match already exists,
         * if not, set the parent.
         */
        ngp = _nge_dict_get (file->ng_file_dict, match);
        if (!ngp) {
                ret = _ng_setup_netgroup_entry (match, file, &ngp);
                if (ret < 0) {
                        /* Bubble up error to caller. We don't need to free ngp
                         * here because this can only fail if allocating the
                         * struct fails.
                         */
                        goto out;
                }
        } else
                GF_FREE (match);

        if (!ngp->netgroup_ngs) {
                /* If a netgroup dict has not been allocated
                 * for this parent, allocate it.
                 */
                ngp->netgroup_ngs = dict_new ();
                GF_CHECK_ALLOC (ngp->netgroup_ngs, ret, out);
                /* No need to free anything here since ngp is already
                 * a part of the file. When the file gets
                 * deallocated, we will free ngp.
                 */
        }

        while ((match = parser_get_next_match (ng_file_parser)) != NULL) {
                num_entries++;
                /* This means that we hit a host entry in the line */
                if (*match == '(') {
                        ret = _ng_handle_host_part (match, ngp);
                        GF_FREE (match);
                        if (ret != 0) {
                                /* If parsing the host fails, bubble the error
                                 * code up to the caller.
                                 */
                                goto out;
                        }
                } else {
                        nge = _nge_dict_get (file->ng_file_dict, match);
                        if (!nge) {
                                ret = _ng_setup_netgroup_entry (match, file,
                                                                &nge);
                                if (ret < 0) {
                                        /* Bubble up error to caller. We don't
                                         * need to free nge here because this
                                         * can only fail if allocating the
                                         * struct fails.
                                         */
                                        goto out;
                                }
                        } else
                                GF_FREE (match);

                        /* Insert the netgroup into the parent's dict */
                        _nge_dict_insert (ngp->netgroup_ngs, nge);
                }
        }

        /* If there are no entries on the RHS, log an error, but continue */
        if (!num_entries) {
                /* Cannot change to gf_msg
                 * gf_msg not giving output to STDOUT
                 * Bug id : BZ1215017
                 */
                gf_log (GF_NG, GF_LOG_WARNING,
                        "No netgroups were specified except for the parent.");
        }

        *ng_entry = ngp;
        ret = 0;

out:
        parser_unset_string (ng_file_parser);
        return ret;
}

/**
 * ng_file_parse - Parse a netgroups file into a the netgroups file struct.
 *                 This is the external facing function that must be called
 *                 to parse a netgroups file. This function returns a netgroup
 *                 file struct that is allocated and must be freed using
 *                 ng_file_deinit.
 *
 * @filepath : Path to the netgroups file we need to parse
 *
 * @return   : success: Pointer to a netgroup file struct if parsing succeeded
 *             failure: NULL if not
 *
 * Externally facing function
 */
struct netgroups_file *
ng_file_parse (const char *filepath)
{
        FILE                  *fp    = NULL;
        size_t                 len   = 0;
        size_t                 read  = 0;
        char                  *line  = NULL;
        struct netgroups_file *file  = NULL;
        struct netgroup_entry *nge   = NULL;
        int                    ret   = 0;

        GF_VALIDATE_OR_GOTO (GF_NG, filepath, err);

        fp = fopen (filepath, "r");
        if (!fp)
                goto err;

        file = _netgroups_file_init ();
        if (!file)
                goto err;

        file->ng_file_dict = dict_new ();
        if (!file->ng_file_dict) {
                gf_msg (GF_NG, GF_LOG_CRITICAL, ENOMEM, NFS_MSG_NO_MEMORY,
                        "Failed to allocate netgroup file dict");
                goto err;
        }

        file->filename = gf_strdup (filepath);
        if (!file->filename) {
                gf_msg (GF_NG, GF_LOG_CRITICAL, errno, NFS_MSG_FILE_OP_FAILED,
                        "Failed to duplicate filename");
                goto err;
        }

        ret = _ng_init_parsers ();
        if (ret < 0)
                goto err;

        /* Read the file line-by-line and parse it */
        while ((read = getline (&line, &len, fp)) != -1) {
                if (*line == '#') /* Lines starting with # are comments */
                        continue;

                /* Parse the line into a netgroup entry */
                ret = _parse_ng_line (line, file, &nge);
                if (ret == -ENOMEM) {
                        gf_msg (GF_NG, GF_LOG_CRITICAL, ENOMEM,
                                NFS_MSG_NO_MEMORY, "Allocation error "
                                "while parsing line!");
                        ng_file_deinit (file);
                        GF_FREE (line);
                        goto err;
                }
                if (ret != 0) {
                        gf_msg_debug (GF_NG, 0, "Failed to parse line %s",
                                      line);
                        continue;
                }
        }

        /* line got allocated through getline(), don't use GF_FREE() for it */
        free (line);

        if (fp)
                fclose(fp);

        return file;

err:
        if (file)
                ng_file_deinit (file);

        _ng_deinit_parsers ();

        if (fp)
                fclose (fp);
        return NULL;
}