2008-06-24 [colin] 3.4.0cvs108
[claws.git] / src / ldif.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 2001-2007 Match Grun and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 /*
21  * Functions necessary to access LDIF files (LDAP Data Interchange Format
22  * files).
23  */
24
25 #include <glib.h>
26 #include <glib/gi18n.h>
27 #include <string.h>
28 #include <sys/stat.h>
29
30 #include "mgutils.h"
31 #include "ldif.h"
32 #include "addritem.h"
33 #include "addrcache.h"
34
35 #include "base64.h"
36 #include "utils.h"
37
38 #define LDIF_SEP_TAG    ':'
39 #define LDIF_LANG_TAG   ';'
40
41 /**
42  * Create new object.
43  * \return Initialized LDIF file object.
44  */
45 LdifFile *ldif_create() {
46         LdifFile *ldifFile;
47         ldifFile = g_new0( LdifFile, 1 );
48         ldifFile->path = NULL;
49         ldifFile->file = NULL;
50         ldifFile->hashFields = g_hash_table_new( g_str_hash, g_str_equal );
51         ldifFile->tempList = NULL;
52         ldifFile->dirtyFlag = TRUE;
53         ldifFile->accessFlag = FALSE;
54         ldifFile->retVal = MGU_SUCCESS;
55         ldifFile->cbProgress = NULL;
56         ldifFile->importCount = 0;
57         return ldifFile;
58 }
59
60 /**
61  * Specify full file specification of LDIF file.
62  * \param ldifFile LDIF import control object.
63  * \param value    Value of access flag.
64  */
65 void ldif_set_file( LdifFile *ldifFile, const gchar *value ) {
66         g_return_if_fail( ldifFile != NULL );
67
68         if( ldifFile->path ) {
69                 if( strcmp( ldifFile->path, value ) != 0 )
70                         ldifFile->dirtyFlag = TRUE;
71         }
72         else {
73                 ldifFile->dirtyFlag = TRUE;
74         }
75         ldifFile->path = mgu_replace_string( ldifFile->path, value );
76         g_strstrip( ldifFile->path );
77         ldifFile->importCount = 0;
78 }
79
80 /**
81  * Set the file access indicator.
82  * \param ldifFile LDIF import control object.
83  * \param value    File specification.
84  */
85 void ldif_set_accessed( LdifFile *ldifFile, const gboolean value ) {
86         g_return_if_fail( ldifFile != NULL );
87         ldifFile->accessFlag = value;
88 }
89
90 /**
91  * Create field record object.
92  * \return Initialized LDIF field object.
93  */
94 static Ldif_FieldRec *ldif_create_fieldrec( const gchar *field ) {
95         Ldif_FieldRec *rec = g_new0( Ldif_FieldRec, 1 );
96         rec->tagName = g_strdup( field );
97         rec->userName = NULL;
98         rec->reserved = FALSE;
99         rec->selected = FALSE;
100         return rec;
101 }
102
103 /**
104  * Free field record object.
105  * \param rec LDIF field object.
106  */
107 static void ldif_free_fieldrec( Ldif_FieldRec *rec ) {
108         if( rec ) {
109                 g_free( rec->tagName );
110                 g_free( rec->userName );
111                 rec->tagName = NULL;
112                 rec->userName = NULL;
113                 rec->reserved = FALSE;
114                 rec->selected = FALSE;
115                 g_free( rec );
116         }
117 }
118
119 /**
120  * Set user name for field record.
121  * \param rec   LDIF field object.
122  * \param value User name to set. Note that reserved fields cannot be
123  *              named.
124  */
125 void ldif_field_set_name( Ldif_FieldRec *rec, const gchar *value ) {
126         g_return_if_fail( rec != NULL );
127
128         if( ! rec->reserved ) {
129                 rec->userName = mgu_replace_string( rec->userName, value );
130                 g_strstrip( rec->userName );
131         }
132 }
133
134 /**
135  * Specify selection for field record.
136  * \param rec   LDIF field object.
137  * \param value Set to <i>TRUE</i> to select field. Note that reserved
138  *              fields cannot be unselected.
139  */
140 void ldif_field_set_selected( Ldif_FieldRec *rec, const gboolean value ) {
141         g_return_if_fail( rec != NULL );
142
143         if( ! rec->reserved ) {
144                 rec->selected = value;
145         }
146 }
147
148 /**
149  * Toggle selection for field record. Note that reserved fields cannot be
150  * toggled.
151  * \param rec   LDIF field object.
152  */
153 void ldif_field_toggle( Ldif_FieldRec *rec ) {
154         g_return_if_fail( rec != NULL );
155
156         if( ! rec->reserved ) {
157                 rec->selected = !rec->selected;
158         }
159 }
160
161 /**
162  * Free hash table entry visitor function.
163  * \param  key   Key.
164  * \param  value Value (the LDIF field record).
165  * \param  data  User data.
166  * \return <code>-1</code>.
167 */
168 static gint ldif_hash_free_vis( gpointer key, gpointer value, gpointer data ) {
169         ldif_free_fieldrec( ( Ldif_FieldRec * ) value );
170         value = NULL;
171         key = NULL;
172         return -1;
173 }
174
175 /**
176  * Free up object by releasing internal memory.
177  * \param ldifFile LDIF import control object.
178  */
179 void ldif_free( LdifFile *ldifFile ) {
180         g_return_if_fail( ldifFile != NULL );
181
182         /* Close file */
183         if( ldifFile->file ) fclose( ldifFile->file );
184
185         /* Free internal stuff */
186         g_free( ldifFile->path );
187
188         /* Free field list */
189         g_hash_table_foreach_remove( ldifFile->hashFields, ldif_hash_free_vis, NULL );
190         g_hash_table_destroy( ldifFile->hashFields );
191         ldifFile->hashFields = NULL;
192
193         /* Clear pointers */
194         ldifFile->file = NULL;
195         ldifFile->path = NULL;
196         ldifFile->retVal = MGU_SUCCESS;
197         ldifFile->tempList = NULL;
198         ldifFile->dirtyFlag = FALSE;
199         ldifFile->accessFlag = FALSE;
200         ldifFile->cbProgress = NULL;
201
202         /* Now release file object */
203         g_free( ldifFile );
204 }
205
206 /**
207  * Open file for read.
208  * \param  ldifFile LDIF import control object.
209  * \return <i>TRUE</i> if file opened successfully.
210  */
211 static gint ldif_open_file( LdifFile* ldifFile ) {
212         /* g_print( "Opening file\n" ); */
213         if( ldifFile->path ) {
214                 ldifFile->file = g_fopen( ldifFile->path, "rb" );
215                 if( ! ldifFile->file ) {
216                         /* g_print( "can't open %s\n", ldifFile->path ); */
217                         ldifFile->retVal = MGU_OPEN_FILE;
218                         return ldifFile->retVal;
219                 }
220         }
221         else {
222                 /* g_print( "file not specified\n" ); */
223                 ldifFile->retVal = MGU_NO_FILE;
224                 return ldifFile->retVal;
225         }
226
227         /* Setup a buffer area */
228         ldifFile->retVal = MGU_SUCCESS;
229         return ldifFile->retVal;
230 }
231
232 /**
233  * Close file.
234  * \param  ldifFile LDIF import control object.
235  */
236 static void ldif_close_file( LdifFile *ldifFile ) {
237         g_return_if_fail( ldifFile != NULL );
238         if( ldifFile->file ) fclose( ldifFile->file );
239         ldifFile->file = NULL;
240 }
241
242 /**
243  * Read line of text from file.
244  * \param  ldifFile LDIF import control object.
245  * \return ptr to buffer where line starts.
246  */
247 static gchar *ldif_get_line( LdifFile *ldifFile ) {
248         gchar *buf = g_malloc(LDIFBUFSIZE);
249         gint ch;
250         int i = 0;
251         int cur_alloc = LDIFBUFSIZE;
252
253         if( feof( ldifFile->file ) ) 
254                 return NULL;
255
256         while( i < cur_alloc-1 ) {
257                 ch = fgetc( ldifFile->file );
258                 if (ferror( ldifFile->file ))
259                         ldifFile->retVal = MGU_ERROR_READ;
260                 if( ch == '\0' || ch == EOF ) {
261                         if( i == 0 ) return NULL;
262                         break;
263                 }
264 #if HAVE_DOSISH_SYSTEM
265 #else
266                 if( ch == '\r' ) 
267                         continue;
268 #endif
269                 if( ch == '\n' ) 
270                         break;
271                 buf[i] = ch;
272                 i++;
273                 if (i == cur_alloc-1 && cur_alloc < LDIFBUFSIZE * 32) {
274                         cur_alloc += LDIFBUFSIZE;
275                         buf = g_realloc(buf, cur_alloc);
276                 }
277         }
278         buf[i] = '\0';
279
280         /* Return a copy of buffer */
281         return g_strdup( buf );
282 }
283
284 /**
285  * Parse tag name from line buffer.
286  * \param  line Buffer.
287  * \param  flag64 Base-64 encoder flag.
288  * \return Buffer containing the tag name, or NULL if no delimiter char found.
289  *         If a double delimiter (::) is found, flag64 is set.
290  */
291 static gchar *ldif_get_tagname( char* line, gboolean *flag64 ) {
292         gint len = 0;
293         gchar *tag = NULL;
294         gchar *lptr = line;
295         gchar *sptr = NULL;
296
297         while( *lptr++ ) {
298                 /* Check for language tag */
299                 if( *lptr == LDIF_LANG_TAG ) {
300                         if( sptr == NULL ) sptr = lptr;
301                 }
302
303                 /* Check for delimiter */
304                 if( *lptr == LDIF_SEP_TAG ) {
305                         if( sptr ) {
306                                 len = sptr - line;
307                         }
308                         else {
309                                 len = lptr - line;
310                         }
311
312                         /* Base-64 encoding? */
313                         if( * ++lptr == LDIF_SEP_TAG ) *flag64 = TRUE;
314
315                         tag = g_strndup( line, len+1 );
316                         tag[ len ] = '\0';
317                         g_strdown( tag );
318                         return tag;
319                 }
320         }
321         return tag;
322 }
323
324 /**
325  * Parse tag value from line buffer.
326  * \param  line Buffer.
327  * \return Buffer containing the tag value. Empty string is returned if
328  *         no delimiter char found.
329  */
330 static gchar *ldif_get_tagvalue( gchar* line ) {
331         gchar *value = NULL;
332         gchar *start = NULL;
333         gchar *lptr;
334         gint len = 0;
335
336         for( lptr = line; *lptr; lptr++ ) {
337                 if( *lptr == LDIF_SEP_TAG ) {
338                         if( ! start )
339                                 start = lptr + 1;
340                 }
341         }
342         if( start ) {
343                 if( *start == LDIF_SEP_TAG ) start++;
344                 len = lptr - start;
345                 value = g_strndup( start, len+1 );
346                 g_strstrip( value );
347         }
348         else {
349                 /* Ensure that we get an empty string */
350                 value = g_strndup( "", 1 );
351         }
352         value[ len ] = '\0';
353         return value;
354 }
355
356 /**
357  * Parsed address data record.
358  */
359 typedef struct _Ldif_ParsedRec_ Ldif_ParsedRec;
360 struct _Ldif_ParsedRec_ {
361         GSList *listCName;
362         GSList *listFName;
363         GSList *listLName;
364         GSList *listNName;
365         GSList *listAddress;
366         GSList *listID;
367         GSList *userAttr;
368 };
369
370 /**
371  * User attribute data record.
372  */
373 typedef struct _Ldif_UserAttr_ Ldif_UserAttr;
374 struct _Ldif_UserAttr_ {
375         gchar *name;
376         gchar *value;
377 };
378
379 /**
380  * Build an address list entry and append to list of address items in the
381  * address cache. Name is formatted as "<first-name> <last-name>".
382  * \param ldifFile LDIF import control object.
383  * \param rec      LDIF field object.
384  * \param cache    Address cache to be populated with data.
385  */
386 static void ldif_build_items(
387                 LdifFile *ldifFile, Ldif_ParsedRec *rec, AddressCache *cache )
388 {
389         GSList *nodeFirst;
390         GSList *nodeAddress;
391         GSList *nodeAttr;
392         gchar *firstName = NULL, *lastName = NULL, *fullName = NULL;
393         gchar *nickName = NULL;
394         gint iLen = 0, iLenT = 0;
395         ItemPerson *person;
396         ItemEMail *email;
397
398         nodeAddress = rec->listAddress;
399 //      if( nodeAddress == NULL ) return;
400
401         /* Find longest first name in list */
402         nodeFirst = rec->listFName;
403         while( nodeFirst ) {
404                 if( firstName == NULL ) {
405                         firstName = nodeFirst->data;
406                         iLen = strlen( firstName );
407                 }
408                 else {
409                         if( ( iLenT = strlen( nodeFirst->data ) ) > iLen ) {
410                                 firstName = nodeFirst->data;
411                                 iLen = iLenT;
412                         }
413                 }
414                 nodeFirst = g_slist_next( nodeFirst );
415         }
416
417         /* Format name */
418         if( rec->listLName ) {
419                 lastName = rec->listLName->data;
420         }
421
422         if( firstName ) {
423                 if( lastName ) {
424                         fullName = g_strdup_printf(
425                                 "%s %s", firstName, lastName );
426                 }
427                 else {
428                         fullName = g_strdup_printf( "%s", firstName );
429                 }
430         }
431         else {
432                 if( lastName ) {
433                         fullName = g_strdup_printf( "%s", lastName );
434                 }
435         }
436         
437         if (!fullName || strlen(fullName) == 0) {
438                 g_free(fullName);
439                 fullName = NULL;
440                 if (rec->listCName)
441                         fullName = g_strdup(rec->listCName->data);
442         }
443         
444         if( fullName ) {
445                 g_strchug( fullName ); g_strchomp( fullName );
446         }
447
448         if( rec->listNName ) {
449                 nickName = rec->listNName->data;
450         }
451
452         person = addritem_create_item_person();
453         addritem_person_set_common_name( person, fullName );
454         addritem_person_set_first_name( person, firstName );
455         addritem_person_set_last_name( person, lastName );
456         addritem_person_set_nick_name( person, nickName );
457         addrcache_id_person( cache, person );
458         addrcache_add_person( cache, person );
459         ++ldifFile->importCount;
460
461         /* Add address item */
462         while( nodeAddress ) {
463                 email = addritem_create_item_email();
464                 addritem_email_set_address( email, nodeAddress->data );
465                 addrcache_id_email( cache, email );
466                 addrcache_person_add_email( cache, person, email );
467                 nodeAddress = g_slist_next( nodeAddress );
468         }
469         g_free( fullName );
470         fullName = firstName = lastName = NULL;
471
472         /* Add user attributes */
473         nodeAttr = rec->userAttr;
474         while( nodeAttr ) {
475                 Ldif_UserAttr *attr = nodeAttr->data;
476                 UserAttribute *attrib = addritem_create_attribute();
477                 addritem_attrib_set_name( attrib, attr->name );
478                 addritem_attrib_set_value( attrib, attr->value );
479                 addritem_person_add_attribute( person, attrib );
480                 nodeAttr = g_slist_next( nodeAttr );
481         }
482         nodeAttr = NULL;
483 }
484
485 /**
486  * Add selected field as user attribute.
487  * \param rec       LDIF field object.
488  * \param tagName   LDIF tag name.
489  * \param tagValue  Data value.
490  * \param hashField Hash table to populate.
491  */
492 static void ldif_add_user_attr(
493                 Ldif_ParsedRec *rec, gchar *tagName, gchar *tagValue,
494                 GHashTable *hashField )
495 {
496         Ldif_FieldRec *fld = NULL;
497         Ldif_UserAttr *attr = NULL;
498         gchar *name;
499
500         fld = g_hash_table_lookup( hashField, tagName );
501         if( fld ) {
502                 if( ! fld->selected ) return;
503
504                 name = fld->tagName;
505                 if( fld->userName ) {
506                         name = fld->userName;
507                 }
508                 attr = g_new0( Ldif_UserAttr, 1 );
509                 attr->name = g_strdup( name );
510                 attr->value = g_strdup( tagValue );
511                 rec->userAttr = g_slist_append( rec->userAttr, attr );
512         }
513 }
514
515 /**
516  * Add value to parsed data.
517  * \param rec       LDIF field object.
518  * \param tagName   LDIF tag name.
519  * \param tagValue  Data value.
520  * \param hashField Hash table to populate.
521  */
522 static void ldif_add_value(
523                Ldif_ParsedRec *rec, gchar *tagName, gchar *tagValue,
524                GHashTable *hashField )
525 {
526         gchar *nm, *val;
527
528         nm = g_strdup( tagName );
529         g_strdown( nm );
530         if( tagValue ) {
531                 val = g_strdup( tagValue );
532         }
533         else {
534                 val = g_strdup( "" );
535         }
536         g_strstrip( val );
537
538         if( g_utf8_collate( nm, LDIF_TAG_COMMONNAME ) == 0 ) {
539                 rec->listCName = g_slist_append( rec->listCName, val );
540         }
541         else if( g_utf8_collate( nm, LDIF_TAG_FIRSTNAME ) == 0 ) {
542                 rec->listFName = g_slist_append( rec->listFName, val );
543         }
544         else if( g_utf8_collate( nm, LDIF_TAG_LASTNAME ) == 0 ) {
545                 rec->listLName = g_slist_append( rec->listLName, val );
546         }
547         else if( g_utf8_collate( nm, LDIF_TAG_NICKNAME ) == 0 ) {
548                 rec->listNName = g_slist_append( rec->listNName, val );
549         }
550         else if( g_utf8_collate( nm, LDIF_TAG_EMAIL ) == 0 ) {
551                 rec->listAddress = g_slist_append( rec->listAddress, val );
552         }
553         else {
554                 /* Add field as user attribute */
555                 ldif_add_user_attr( rec, tagName, tagValue, hashField );
556         }
557         g_free( nm );
558 }
559
560 /**
561  * Clear parsed data record.
562  * \param rec LDIF field object.
563  */
564 static void ldif_clear_rec( Ldif_ParsedRec *rec ) {
565         GSList *list;
566
567         /* Free up user attributes */
568         list = rec->userAttr;
569         while( list ) {
570                 Ldif_UserAttr *attr = list->data;
571                 g_free( attr->name );
572                 g_free( attr->value );
573                 g_free( attr );
574                 list = g_slist_next( list );
575         }
576         g_slist_free( rec->userAttr );
577
578         g_slist_free( rec->listCName );
579         g_slist_free( rec->listFName );
580         g_slist_free( rec->listLName );
581         g_slist_free( rec->listNName );
582         g_slist_free( rec->listAddress );
583         g_slist_free( rec->listID );
584
585         rec->userAttr = NULL;
586         rec->listCName = NULL;
587         rec->listFName = NULL;
588         rec->listLName = NULL;
589         rec->listNName = NULL;
590         rec->listAddress = NULL;
591         rec->listID = NULL;
592 }
593
594 /**
595  * Read file data into address cache.
596  * Note that one LDIF record identifies one entity uniquely with the
597  * distinguished name (dn) tag. Each person can have multiple E-Mail
598  * addresses. Also, each person can have many common name (cn) tags.
599  *
600  * \param  ldifFile LDIF import control object.
601  * \param  cache    Address cache to be populated with data.
602  */
603 static void ldif_read_file( LdifFile *ldifFile, AddressCache *cache ) {
604         gchar *tagName = NULL, *tagValue = NULL;
605         gchar *lastTag = NULL, *fullValue = NULL;
606         GSList *listValue = NULL;
607         gboolean flagEOF = FALSE, flagEOR = FALSE;
608         gboolean flag64 = FALSE, last64 = FALSE;
609         Ldif_ParsedRec *rec;
610         long posEnd = 0L;
611         long posCur = 0L;
612         GHashTable *hashField;
613
614         hashField = ldifFile->hashFields;
615         rec = g_new0( Ldif_ParsedRec, 1 );
616         ldif_clear_rec( rec );
617
618         /* Find EOF for progress indicator */
619         fseek( ldifFile->file, 0L, SEEK_END );
620         posEnd = ftell( ldifFile->file );
621         fseek( ldifFile->file, 0L, SEEK_SET );
622
623         while( ! flagEOF ) {
624                 gchar *line =  ldif_get_line( ldifFile );
625
626                 posCur = ftell( ldifFile->file );
627                 if( ldifFile->cbProgress ) {
628                         /* Call progress indicator */
629                         ( ldifFile->cbProgress ) ( ldifFile, & posEnd, & posCur );
630                 }
631
632                 flag64 = FALSE;
633                 if( line == NULL ) {
634                         flagEOF = flagEOR = TRUE;
635                 }
636                 else if( *line == '\0' ) {
637                         flagEOR = TRUE;
638                 }
639
640                 if( flagEOR ) {
641                         /* EOR, Output address data */
642                         if( lastTag ) {
643                                 /* Save record */
644                                 fullValue = mgu_list_coalesce( listValue );
645                                 if (fullValue && last64) {
646                                         gchar *out = g_malloc(strlen(fullValue));
647                                         int len = 0;
648                                         if ((len = base64_decode(out, fullValue,
649                                                         strlen(fullValue))) >= 0) {
650                                                 g_free(fullValue);
651                                                 fullValue = out;
652                                                 fullValue[len] = '\0';
653                                         } else
654                                                 g_free(out);
655                                 }
656                                 /* Base-64 encoded data */
657                                 /*
658                                 if( last64 ) {
659                                         ldif_dump_b64( fullValue );
660                                 }
661                                 */
662
663                                 ldif_add_value( rec, lastTag, fullValue, hashField );
664                                 /* ldif_print_record( rec, stdout ); */
665                                 ldif_build_items( ldifFile, rec, cache );
666                                 ldif_clear_rec( rec );
667                                 g_free( lastTag );
668                                 mgu_free_list( listValue );
669                                 lastTag = NULL;
670                                 listValue = NULL;
671                                 last64 = FALSE;
672                         }
673                 }
674                 if( line ) {
675                         flagEOR = FALSE;
676                         if( *line == ' ' ) {
677                                 /* Continuation line */
678                                 listValue = g_slist_append(
679                                         listValue, g_strdup( line+1 ) );
680                         }
681                         else if( *line == '=' ) {
682                                 /* Base-64 encoded continuation field */
683                                 listValue = g_slist_append(
684                                         listValue, g_strdup( line ) );
685                         }
686                         else {
687                                 /* Parse line */
688                                 tagName = ldif_get_tagname( line, &flag64 );
689                                 if( tagName ) {
690                                         tagValue = ldif_get_tagvalue( line );
691                                         if( tagValue ) {
692                                                 if( lastTag ) {
693                                                         /* Save data */
694                                                         fullValue =
695                                                                 mgu_list_coalesce( listValue );
696                                                         if (fullValue && last64) {
697                                                                 gchar *out = g_malloc(strlen(fullValue));
698                                                                 int len = 0;
699                                                                 if ((len = base64_decode(out, fullValue,
700                                                                                 strlen(fullValue))) >= 0) {
701                                                                         g_free(fullValue);
702                                                                         fullValue = out;
703                                                                         fullValue[len] = '\0';
704                                                                 } else
705                                                                         g_free(out);
706                                                         }
707                                                         /* Base-64 encoded data */
708                                                         /*
709                                                         if( last64 ) {
710                                                                 ldif_dump_b64( fullValue );
711                                                         }
712                                                         */
713
714                                                         ldif_add_value(
715                                                                 rec, lastTag, fullValue,
716                                                                 hashField );
717                                                         g_free( lastTag );
718                                                         mgu_free_list( listValue );
719                                                         lastTag = NULL;
720                                                         listValue = NULL;
721                                                         last64 = FALSE;
722                                                 }
723
724                                                 lastTag = g_strdup( tagName );
725                                                 listValue = g_slist_append(
726                                                         listValue,
727                                                         g_strdup( tagValue ) );
728                                                 g_free( tagValue );
729                                                 last64 = flag64;
730                                         }
731                                         g_free( tagName );
732                                 }
733                         }
734                 }
735                 g_free( line );
736         }
737
738         /* Release data */
739         ldif_clear_rec( rec );
740         g_free( rec );
741         g_free( lastTag );
742         mgu_free_list( listValue );
743 }
744
745 /**
746  * Add list of field names to hash table.
747  * \param table Hashtable.
748  * \param list  List of fields.
749  */
750 static void ldif_hash_add_list( GHashTable *table, GSList *list ) {
751         GSList *node = list;
752
753         /* mgu_print_list( list, stdout ); */
754         while( node ) {
755                 gchar *tag = node->data;
756                 if( ! g_hash_table_lookup( table, tag ) ) {
757                         Ldif_FieldRec *rec = NULL;
758                         gchar *key = g_strdup( tag );
759
760                         rec = ldif_create_fieldrec( tag );
761                         if( g_utf8_collate( tag, LDIF_TAG_DN ) == 0 ) {
762                                 rec->reserved = rec->selected = TRUE;
763                                 rec->userName = g_strdup( "dn" );
764                         }
765                         else if( g_utf8_collate( tag, LDIF_TAG_COMMONNAME ) == 0 ) {
766                                 rec->reserved = rec->selected = TRUE;
767                                 rec->userName = g_strdup( _( "Display Name" ) );
768                         }
769                         else if( g_utf8_collate( tag, LDIF_TAG_FIRSTNAME ) == 0 ) {
770                                 rec->reserved = rec->selected = TRUE;
771                                 rec->userName = g_strdup( _( "First Name" ) );
772                         }
773                         else if( g_utf8_collate( tag, LDIF_TAG_LASTNAME ) == 0 ) {
774                                 rec->reserved = rec->selected = TRUE;
775                                 rec->userName = g_strdup( _( "Last Name" ) );
776                         }
777                         else if( g_utf8_collate( tag, LDIF_TAG_NICKNAME ) == 0 ) {
778                                 rec->reserved = rec->selected = TRUE;
779                                 rec->userName = g_strdup( _( "Nick Name" ) );
780                         }
781                         else if( g_utf8_collate( tag, LDIF_TAG_EMAIL ) == 0 ) {
782                                 rec->reserved = rec->selected = TRUE;
783                                 rec->userName = g_strdup( _( "Email Address" ) );
784                         }
785                         g_hash_table_insert( table, key, rec );
786                 }
787                 node = g_slist_next( node );
788         }
789 }
790
791 /**
792  * Sorted list comparison function.
793  * \param  ptr1 First field.
794  * \param  ptr2 Second field.
795  * \return <code>-1, 0, +1</code> if first record less than, equal,
796  *         greater than second.
797  */
798 static gint ldif_field_compare( gconstpointer ptr1, gconstpointer ptr2 ) {
799         const Ldif_FieldRec *rec1 = ptr1;
800         const Ldif_FieldRec *rec2 = ptr2;
801
802         if( rec1->reserved ) {
803                 if( ! rec2->reserved ) {
804                         return +1;
805                 }
806         }
807         else {
808                 if( rec2->reserved ) {
809                         return -1;
810                 }
811         }
812         return g_utf8_collate( rec1->tagName, rec2->tagName );
813 }
814
815 /*
816  * Append hash table entry to list - visitor function.
817  * \param key   Key.
818  * \param value Data value.
819  * \param data  User data (the LDIF import control object).
820  */
821 static void ldif_hash2list_vis( gpointer key, gpointer value, gpointer data ) {
822         LdifFile *ldf = data;
823         ldf->tempList =
824                 g_list_insert_sorted( ldf->tempList, value, ldif_field_compare );
825 }
826
827 /**
828  * Read tag names for file data.
829  * \param  ldifFile LDIF import control object.
830  */
831 static void ldif_read_tag_list( LdifFile *ldifFile ) {
832         gchar *tagName = NULL;
833         GSList *listTags = NULL;
834         gboolean flagEOF = FALSE, flagEOR = FALSE, flagMail = FALSE;
835         gboolean flag64 = FALSE;
836         long posEnd = 0L;
837         long posCur = 0L;
838
839         /* Clear hash table */
840         g_hash_table_foreach_remove(
841                 ldifFile->hashFields, ldif_hash_free_vis, NULL );
842
843         /* Find EOF for progress indicator */
844         fseek( ldifFile->file, 0L, SEEK_END );
845         posEnd = ftell( ldifFile->file );
846         fseek( ldifFile->file, 0L, SEEK_SET );
847
848         if (posEnd == 0) {
849                 ldifFile->retVal = MGU_EOF;
850                 return;
851         }
852                 
853         /* Process file */
854         while( ! flagEOF ) {
855                 gchar *line = ldif_get_line( ldifFile );
856                 posCur = ftell( ldifFile->file );
857                 if( ldifFile->cbProgress ) {
858                         /* Call progress indicator */
859                         ( ldifFile->cbProgress ) ( ldifFile, & posEnd, & posCur );
860                 }
861
862                 flag64 = FALSE;
863                 if( line == NULL ) {
864                         flagEOF = flagEOR = TRUE;
865                 }
866                 else if( *line == '\0' ) {
867                         flagEOR = TRUE;
868                 }
869
870                 if( flagEOR ) {
871                         /* EOR, Output address data */
872                         /* Save field list to hash table */
873                         if( flagMail ) {
874                                 ldif_hash_add_list(
875                                         ldifFile->hashFields, listTags );
876                         }
877                         mgu_free_list( listTags );
878                         listTags = NULL;
879                         flagMail = FALSE;
880                 }
881                 if( line ) {
882                         flagEOR = FALSE;
883                         if( *line == ' ' ) {
884                                 /* Continuation line */
885                         }
886                         else if( *line == '=' ) {
887                                 /* Base-64 encoded continuation field */
888                         }
889                         else {
890                                 /* Parse line */
891                                 tagName = ldif_get_tagname( line, &flag64 );
892                                 if( tagName ) {
893                                         /* Add tag to list */
894                                         listTags = g_slist_append( listTags, tagName );
895
896                                         if( g_utf8_collate(
897                                                 tagName, LDIF_TAG_EMAIL ) == 0 )
898                                         {
899                                                 flagMail = TRUE;
900                                         }
901                                 } else {
902                                         g_strstrip(line);
903                                         if (*line != '\0') {
904                                                 debug_print("ldif: bad format: '%s'\n", line);
905                                                 ldifFile->retVal = MGU_BAD_FORMAT;
906                                         }
907                                 }
908                         }
909                 }
910                 g_free( line );
911         }
912
913         /* Release data */
914         mgu_free_list( listTags );
915         listTags = NULL;
916 }
917
918 /**
919  * Read file into list. Main entry point
920  * \param  ldifFile LDIF import control object.
921  * \param  cache    Address cache to load.
922  * \return Status code.
923  */
924 gint ldif_import_data( LdifFile *ldifFile, AddressCache *cache ) {
925         g_return_val_if_fail( ldifFile != NULL, MGU_BAD_ARGS );
926         ldifFile->retVal = MGU_SUCCESS;
927         addrcache_clear( cache );
928         cache->dataRead = FALSE;
929         ldif_open_file( ldifFile );
930         if( ldifFile->retVal == MGU_SUCCESS ) {
931                 /* Read data into the cache */
932                 ldif_read_file( ldifFile, cache );
933                 ldif_close_file( ldifFile );
934
935                 /* Mark cache */
936                 cache->modified = FALSE;
937                 cache->dataRead = TRUE;
938         }
939         return ldifFile->retVal;
940 }
941
942 /**
943  * Process entire file reading list of unique fields. List of fields may be
944  * accessed with the <code>ldif_get_fieldlist()</code> function.
945  * \param  ldifFile LDIF import control object.
946  * \return Status code.
947  */
948 gint ldif_read_tags( LdifFile *ldifFile ) {
949         g_return_val_if_fail( ldifFile != NULL, MGU_BAD_ARGS );
950         ldifFile->retVal = MGU_SUCCESS;
951         if( ldifFile->dirtyFlag ) {
952                 ldif_open_file( ldifFile );
953                 if( ldifFile->retVal == MGU_SUCCESS ) {
954                         /* Read data into the cache */
955                         ldif_read_tag_list( ldifFile );
956                         ldif_close_file( ldifFile );
957                         ldifFile->dirtyFlag = FALSE;
958                         ldifFile->accessFlag = TRUE;
959                 }
960         }
961         return ldifFile->retVal;
962 }
963
964 /**
965  * Return list of fields for LDIF file.
966  * \param  ldifFile LDIF import control object.
967  * \return Linked list of <code>Ldif_FieldRec</code> objects. This list may be
968  *         <code>g_free()</code>. Note that the objects in the list should not
969  *         be freed since they refer to objects inside the internal cache.
970  *         These objects will be freed when LDIF file object is freed.
971  */
972 GList *ldif_get_fieldlist( LdifFile *ldifFile ) {
973         GList *list = NULL;
974
975         g_return_val_if_fail( ldifFile != NULL, NULL );
976         if( ldifFile->hashFields ) {
977                 ldifFile->tempList = NULL;
978                 g_hash_table_foreach( ldifFile->hashFields, ldif_hash2list_vis, ldifFile );
979                 list = ldifFile->tempList;
980                 ldifFile->tempList = NULL;
981         }
982         return list;
983 }
984
985 /**
986  * Output LDIF name-value pair to stream. Only non-empty names and values will
987  * be output to file.
988  * \param stream File output stream.
989  * \param name   Name.
990  * \param value  Data value.
991  * \return <i>TRUE</i> if data output.
992  */
993 gboolean ldif_write_value( FILE *stream, const gchar *name, const gchar *value ) {
994         if( name == NULL ) return FALSE;
995         if( value == NULL ) return FALSE;
996         if( strlen( name ) < 1 ) return FALSE;
997         if( strlen( value ) < 1 ) return FALSE;
998         fprintf( stream, "%s: ", name );
999         fprintf( stream, "%s\n", value );
1000         return TRUE;
1001 }
1002
1003 /**
1004  * Output LDIF End of Record to stream.
1005  * \param stream File output stream.
1006  * \return <i>TRUE</i> if data output.
1007  */
1008 void ldif_write_eor( FILE *stream ) {
1009         /* Simple but caller should not need to know how to end record. */
1010         fprintf( stream, "\n" );
1011 }
1012
1013 /*
1014  * ============================================================================
1015  * End of Source.
1016  * ============================================================================
1017  */
1018