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