*Remove the damn file already
[claws.git] / src / jpilot.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 2001-2012 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 JPilot database files.
22  * JPilot is Copyright(c) by Judd Montgomery.
23  * Visit http://www.jpilot.org for more details.
24  */
25
26 #ifdef HAVE_CONFIG_H
27 #  include "config.h"
28 #include "claws-features.h"
29 #endif
30
31 #ifdef USE_JPILOT
32
33 #include <glib.h>
34 #include <time.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <sys/stat.h>
39 #include <netinet/in.h>
40
41 #ifdef HAVE_LIBPISOCK_PI_ARGS_H
42 #  include <libpisock/pi-args.h>
43 #  include <libpisock/pi-appinfo.h>
44 #  include <libpisock/pi-address.h>
45 #  include <libpisock/pi-version.h>
46 #else
47 #  include <pi-args.h>
48 #  include <pi-appinfo.h>
49 #  include <pi-address.h>
50 #  include <pi-version.h>
51 #endif
52
53 #include "mgutils.h"
54 #include "addritem.h"
55 #include "addrcache.h"
56 #include "jpilot.h"
57 #include "codeconv.h"
58 #include "adbookbase.h"
59 #include "utils.h"
60
61 #define JPILOT_DBHOME_DIR   ".jpilot"
62 #define JPILOT_DBHOME_FILE  "AddressDB.pdb"
63 #define PILOT_LINK_LIB_NAME "libpisock.so"
64
65 #define IND_LABEL_LASTNAME  0   /* Index of last name in address data */
66 #define IND_LABEL_FIRSTNAME 1   /* Index of first name in address data */
67 #define IND_PHONE_EMAIL     4   /* Index of E-Mail address in phone labels */
68 #define OFFSET_PHONE_LABEL  3   /* Offset to phone data in address data */
69 #define IND_CUSTOM_LABEL    14  /* Offset to custom label names */
70 #define NUM_CUSTOM_LABEL    4   /* Number of custom labels */
71
72 /* Shamelessly copied from JPilot (libplugin.h) */
73 typedef struct {
74         unsigned char db_name[32];
75         unsigned char flags[2];
76         unsigned char version[2];
77         unsigned char creation_time[4];
78         unsigned char modification_time[4];
79         unsigned char backup_time[4];
80         unsigned char modification_number[4];
81         unsigned char app_info_offset[4];
82         unsigned char sort_info_offset[4];
83         unsigned char type[4];/*Database ID */
84         unsigned char creator_id[4];/*Application ID */
85         unsigned char unique_id_seed[4];
86         unsigned char next_record_list_id[4];
87         unsigned char number_of_records[2];
88 } RawDBHeader;
89
90 /* Shamelessly copied from JPilot (libplugin.h) */
91 typedef struct {
92         char db_name[32];
93         unsigned int flags;
94         unsigned int version;
95         time_t creation_time;
96         time_t modification_time;
97         time_t backup_time;
98         unsigned int modification_number;
99         unsigned int app_info_offset;
100         unsigned int sort_info_offset;
101         char type[5];/*Database ID */
102         char creator_id[5];/*Application ID */
103         char unique_id_seed[5];
104         unsigned int next_record_list_id;
105         unsigned int number_of_records;
106 } DBHeader;
107
108 /* Shamelessly copied from JPilot (libplugin.h) */
109 typedef struct {
110         unsigned char Offset[4];  /*4 bytes offset from BOF to record */
111         unsigned char attrib;
112         unsigned char unique_ID[3];
113 } record_header;
114
115 /* Shamelessly copied from JPilot (libplugin.h) */
116 typedef struct mem_rec_header_s {
117         unsigned int rec_num;
118         unsigned int offset;
119         unsigned int unique_id;
120         unsigned char attrib;
121         struct mem_rec_header_s *next;
122 } mem_rec_header;
123
124 /* Shamelessly copied from JPilot (libplugin.h) */
125 #define SPENT_PC_RECORD_BIT     256
126
127 typedef enum {
128         PALM_REC = 100L,
129         MODIFIED_PALM_REC = 101L,
130         DELETED_PALM_REC = 102L,
131         NEW_PC_REC = 103L,
132         DELETED_PC_REC = SPENT_PC_RECORD_BIT + 104L,
133         DELETED_DELETED_PALM_REC = SPENT_PC_RECORD_BIT + 105L
134 } PCRecType;
135
136 /* Shamelessly copied from JPilot (libplugin.h) */
137 typedef struct {
138         PCRecType rt;
139         unsigned int unique_id;
140         unsigned char attrib;
141         void *buf;
142         int size;
143 } buf_rec;
144
145 /* Shamelessly copied from JPilot (libplugin.h) */
146 typedef struct {
147         unsigned long header_len;
148         unsigned long header_version;
149         unsigned long rec_len;
150         unsigned long unique_id;
151         unsigned long rt; /* Record Type */
152         unsigned char attrib;
153 } PC3RecordHeader;
154
155 enum {
156         FAMILY_LAST = 0,
157         FAMILY_FIRST = 1
158 } name_order;
159
160 gboolean convert_charcode = TRUE;
161
162 static const gchar *jpilot_get_charset(void)
163 {
164         static const gchar *charset = NULL;
165
166         if (charset == NULL)
167                 charset = getenv("PILOT_CHARSET");
168
169         if (charset == NULL)
170                 charset = CS_CP1252;
171         
172         return charset;
173 }
174
175 /*
176 * Create new pilot file object.
177 * \return Initialized JPilot file object.
178 */
179 JPilotFile *jpilot_create() {
180         JPilotFile *pilotFile;
181         pilotFile = g_new0( JPilotFile, 1 );
182         pilotFile->type = ADBOOKTYPE_JPILOT;
183         pilotFile->addressCache = addrcache_create();
184         pilotFile->retVal = MGU_SUCCESS;
185
186         pilotFile->file = NULL;
187         pilotFile->path = NULL;
188         pilotFile->readMetadata = FALSE;
189         pilotFile->customLabels = NULL;
190         pilotFile->labelInd = NULL;
191         pilotFile->havePC3 = FALSE;
192         pilotFile->pc3ModifyTime = 0;
193         return pilotFile;
194 }
195
196 /**
197  * Create new pilot file object for specified file.
198  * \param path Path to JPilot address book.
199  * \return Initialized JPilot file object.
200  */
201 JPilotFile *jpilot_create_path( const gchar *path ) {
202         JPilotFile *pilotFile;
203         pilotFile = jpilot_create();
204         jpilot_set_file( pilotFile, path );
205         return pilotFile;
206 }
207
208 /*
209 * Properties...
210 */
211 void jpilot_set_name( JPilotFile* pilotFile, const gchar *value ) {
212         cm_return_if_fail( pilotFile != NULL );
213         addrcache_set_name( pilotFile->addressCache, value );
214 }
215 void jpilot_set_file( JPilotFile* pilotFile, const gchar *value ) {
216         cm_return_if_fail( pilotFile != NULL );
217         addrcache_refresh( pilotFile->addressCache );
218         pilotFile->readMetadata = FALSE;
219         pilotFile->path = mgu_replace_string( pilotFile->path, value );
220 }
221 void jpilot_set_accessed( JPilotFile *pilotFile, const gboolean value ) {
222         cm_return_if_fail( pilotFile != NULL );
223         pilotFile->addressCache->accessFlag = value;
224 }
225
226 gint jpilot_get_status( JPilotFile *pilotFile ) {
227         cm_return_val_if_fail( pilotFile != NULL, -1 );
228         return pilotFile->retVal;
229 }
230 ItemFolder *jpilot_get_root_folder( JPilotFile *pilotFile ) {
231         cm_return_val_if_fail( pilotFile != NULL, NULL );
232         return addrcache_get_root_folder( pilotFile->addressCache );
233 }
234 gchar *jpilot_get_name( JPilotFile *pilotFile ) {
235         cm_return_val_if_fail( pilotFile != NULL, NULL );
236         return addrcache_get_name( pilotFile->addressCache );
237 }
238
239 /*
240  * Test whether file was read.
241  * \param pilotFile  JPilot control data.
242  * \return <i>TRUE</i> if file was read.
243  */
244 gboolean jpilot_get_read_flag( JPilotFile *pilotFile ) {
245         cm_return_val_if_fail( pilotFile != NULL, FALSE );
246         return pilotFile->addressCache->dataRead;
247 }
248
249 /**
250  * Free up custom label list.
251  * \param pilotFile  JPilot control data.
252  */
253 void jpilot_clear_custom_labels( JPilotFile *pilotFile ) {
254         GList *node;
255
256         cm_return_if_fail( pilotFile != NULL );
257
258         /* Release custom labels */
259         mgu_free_dlist( pilotFile->customLabels );
260         pilotFile->customLabels = NULL;
261
262         /* Release indexes */
263         node = pilotFile->labelInd;
264         while( node ) {
265                 node->data = NULL;
266                 node = g_list_next( node );
267         }
268         g_list_free( pilotFile->labelInd );
269         pilotFile->labelInd = NULL;
270
271         /* Force a fresh read */
272         addrcache_refresh( pilotFile->addressCache );
273 }
274
275 /**
276  * Append a custom label, representing an E-Mail address field to the
277  * custom label list.
278  * \param pilotFile  JPilot control data.
279  */
280 void jpilot_add_custom_label( JPilotFile *pilotFile, const gchar *labelName ) {
281         cm_return_if_fail( pilotFile != NULL );
282
283         if( labelName ) {
284                 gchar *labelCopy = g_strdup( labelName );
285                 g_strstrip( labelCopy );
286                 if( *labelCopy == '\0' ) {
287                         g_free( labelCopy );
288                 }
289                 else {
290                         pilotFile->customLabels = g_list_append( pilotFile->customLabels, labelCopy );
291                         /* Force a fresh read */
292                         addrcache_refresh( pilotFile->addressCache );
293                 }
294         }
295 }
296
297 /**
298  * Get list of custom labels.
299  * \param pilotFile  JPilot control data.
300  * \return List of labels. Must use g_free() when done.
301  */
302 GList *jpilot_get_custom_labels( JPilotFile *pilotFile ) {
303         GList *retVal = NULL;
304         GList *node;
305
306         cm_return_val_if_fail( pilotFile != NULL, NULL );
307
308         node = pilotFile->customLabels;
309         while( node ) {
310                 retVal = g_list_append( retVal, g_strdup( node->data ) );
311                 node = g_list_next( node );
312         }
313         return retVal;
314 }
315
316 /**
317  * Return filespec of PC3 file corresponding to JPilot PDB file.
318  * \param pilotFile  JPilot control data.
319  * \return File specification; should be g_free() when done.
320  */
321 static gchar *jpilot_get_pc3_file( JPilotFile *pilotFile ) {
322         gchar *fileSpec, *r;
323         gint i, len, pos;
324
325         if( pilotFile == NULL ) return NULL;
326         if( pilotFile->path == NULL ) return NULL;
327
328         fileSpec = g_strdup( pilotFile->path );
329         len = strlen( fileSpec );
330         pos = -1;
331         r = NULL;
332         for( i = len; i > 0; i-- ) {
333                 if( *(fileSpec + i) == '.' ) {
334                         pos = i + 1;
335                         r = fileSpec + pos;
336                         break;
337                 }
338         }
339         if( r ) {
340                 if( len - pos == 3 ) {
341                         *r++ = 'p'; *r++ = 'c'; *r = '3';
342                         return fileSpec;
343                 }
344         }
345         g_free( fileSpec );
346         return NULL;
347 }
348
349 /**
350  * Save PC3 file time to cache.
351  * \param pilotFile  JPilot control data.
352  * \return <i>TRUE</i> if time marked.
353  */
354 static gboolean jpilot_mark_files( JPilotFile *pilotFile ) {
355         gboolean retVal = FALSE;
356         struct stat filestat;
357         gchar *pcFile;
358
359         /* Mark PDB file cache */
360         retVal = addrcache_mark_file( pilotFile->addressCache, pilotFile->path );
361
362         /* Now mark PC3 file */
363         pilotFile->havePC3 = FALSE;
364         pilotFile->pc3ModifyTime = 0;
365         pcFile = jpilot_get_pc3_file( pilotFile );
366         if( pcFile == NULL ) return retVal;
367         if( 0 == g_stat( pcFile, &filestat ) ) {
368                 pilotFile->havePC3 = TRUE;
369                 pilotFile->pc3ModifyTime = filestat.st_mtime;
370                 retVal = TRUE;
371         }
372         g_free( pcFile );
373         return retVal;
374 }
375
376 /**
377  * Check whether JPilot PDB or PC3 file has changed by comparing
378  * with cached data.
379  * \param pilotFile  JPilot control data.
380  * \return <i>TRUE</i> if file has changed.
381  */
382 static gboolean jpilot_check_files( JPilotFile *pilotFile ) {
383         gboolean retVal = TRUE;
384         struct stat filestat;
385         gchar *pcFile;
386
387         /* Check main file */
388         if( addrcache_check_file( pilotFile->addressCache, pilotFile->path ) )
389                 return TRUE;
390
391         /* Test PC3 file */
392         if( ! pilotFile->havePC3 ) return FALSE;
393         pcFile = jpilot_get_pc3_file( pilotFile );
394         if( pcFile == NULL ) return FALSE;
395
396         if( 0 == g_stat( pcFile, &filestat ) ) {
397                 if( filestat.st_mtime == pilotFile->pc3ModifyTime ) retVal = FALSE;
398         }
399         g_free( pcFile );
400         return retVal;
401 }
402
403 /*
404 * Test whether file was modified since last access.
405 * Return: TRUE if file was modified.
406 */
407 gboolean jpilot_get_modified( JPilotFile *pilotFile ) {
408         cm_return_val_if_fail( pilotFile != NULL, FALSE );
409         pilotFile->addressCache->modified = jpilot_check_files( pilotFile );
410         return pilotFile->addressCache->modified;
411 }
412 gboolean jpilot_get_accessed( JPilotFile *pilotFile ) {
413         cm_return_val_if_fail( pilotFile != NULL, FALSE );
414         return pilotFile->addressCache->accessFlag;
415 }
416
417 /**
418  * Free up pilot file object by releasing internal memory.
419  * \param pilotFile  JPilot control data.
420  */
421 void jpilot_free( JPilotFile *pilotFile ) {
422         cm_return_if_fail( pilotFile != NULL );
423
424         /* Release custom labels */
425         jpilot_clear_custom_labels( pilotFile );
426
427         /* Clear cache */
428         addrcache_clear( pilotFile->addressCache );
429         addrcache_free( pilotFile->addressCache );
430
431         /* Free internal stuff */
432         g_free( pilotFile->path );
433
434         pilotFile->file = NULL;
435         pilotFile->path = NULL;
436         pilotFile->readMetadata = FALSE;
437         pilotFile->havePC3 = FALSE;
438         pilotFile->pc3ModifyTime = 0;
439
440         pilotFile->type = ADBOOKTYPE_NONE;
441         pilotFile->addressCache = NULL;
442         pilotFile->retVal = MGU_SUCCESS;
443
444         /* Now release file object */
445         g_free( pilotFile );
446 }
447
448 /* Shamelessly copied from JPilot (libplugin.c) */
449 static unsigned int bytes_to_bin(unsigned char *bytes, unsigned int num_bytes) {
450 unsigned int i, n;
451         n=0;
452         for (i=0;i<num_bytes;i++) {
453                 n = n*256+bytes[i];
454         }
455         return n;
456 }
457
458 /* Shamelessly copied from JPilot (utils.c) */
459 /* These next 2 functions were copied from pi-file.c in the pilot-link app */
460 /* Exact value of "Jan 1, 1970 0:00:00 GMT" - "Jan 1, 1904 0:00:00 GMT" */
461 #define PILOT_TIME_DELTA (unsigned)(2082844800)
462
463 static time_t pilot_time_to_unix_time ( unsigned long raw_time ) {
464    return (time_t)(raw_time - PILOT_TIME_DELTA);
465 }
466
467 /* Shamelessly copied from JPilot (libplugin.c) */
468 static int raw_header_to_header(RawDBHeader *rdbh, DBHeader *dbh) {
469         unsigned long temp;
470
471         strncpy(dbh->db_name, rdbh->db_name, 31);
472         dbh->db_name[31] = '\0';
473         dbh->flags = bytes_to_bin(rdbh->flags, 2);
474         dbh->version = bytes_to_bin(rdbh->version, 2);
475         temp = bytes_to_bin(rdbh->creation_time, 4);
476         dbh->creation_time = pilot_time_to_unix_time(temp);
477         temp = bytes_to_bin(rdbh->modification_time, 4);
478         dbh->modification_time = pilot_time_to_unix_time(temp);
479         temp = bytes_to_bin(rdbh->backup_time, 4);
480         dbh->backup_time = pilot_time_to_unix_time(temp);
481         dbh->modification_number = bytes_to_bin(rdbh->modification_number, 4);
482         dbh->app_info_offset = bytes_to_bin(rdbh->app_info_offset, 4);
483         dbh->sort_info_offset = bytes_to_bin(rdbh->sort_info_offset, 4);
484         strncpy(dbh->type, rdbh->type, 4);
485         dbh->type[4] = '\0';
486         strncpy(dbh->creator_id, rdbh->creator_id, 4);
487         dbh->creator_id[4] = '\0';
488         strncpy(dbh->unique_id_seed, rdbh->unique_id_seed, 4);
489         dbh->unique_id_seed[4] = '\0';
490         dbh->next_record_list_id = bytes_to_bin(rdbh->next_record_list_id, 4);
491         dbh->number_of_records = bytes_to_bin(rdbh->number_of_records, 2);
492         return 0;
493 }
494
495 /* Shamelessly copied from JPilot (libplugin.c) */
496 /* returns 1 if found */
497 /*         0 if eof */
498 static int find_next_offset( mem_rec_header *mem_rh, long fpos,
499         unsigned int *next_offset, unsigned char *attrib, unsigned int *unique_id )
500 {
501         mem_rec_header *temp_mem_rh;
502         unsigned char found = 0;
503         unsigned long found_at;
504
505         found_at=0xFFFFFF;
506         for (temp_mem_rh=mem_rh; temp_mem_rh; temp_mem_rh = temp_mem_rh->next) {
507                 if ((temp_mem_rh->offset > fpos) && (temp_mem_rh->offset < found_at)) {
508                         found_at = temp_mem_rh->offset;
509                         /* *attrib = temp_mem_rh->attrib; */
510                         /* *unique_id = temp_mem_rh->unique_id; */
511                 }
512                 if ((temp_mem_rh->offset == fpos)) {
513                         found = 1;
514                         *attrib = temp_mem_rh->attrib;
515                         *unique_id = temp_mem_rh->unique_id;
516                 }
517         }
518         *next_offset = found_at;
519         return found;
520 }
521
522 /* Shamelessly copied from JPilot (libplugin.c) */
523 static void free_mem_rec_header(mem_rec_header **mem_rh) {
524         mem_rec_header *h, *next_h;
525         for (h=*mem_rh; h; h=next_h) {
526                 next_h=h->next;
527                 free(h);
528         }
529         *mem_rh = NULL;
530 }
531
532 /* Shamelessly copied from JPilot (libplugin.c) */
533 /* Read file size */
534 static int jpilot_get_info_size( FILE *in, int *size ) {
535         RawDBHeader rdbh;
536         DBHeader dbh;
537         unsigned int offset;
538         record_header rh;
539         int r;
540
541         fseek(in, 0, SEEK_SET);
542         r = fread(&rdbh, sizeof(RawDBHeader), 1, in);
543         if (r < 1)
544                 return MGU_ERROR_READ;
545         if (feof(in)) {
546                 return MGU_EOF;
547         }
548
549         raw_header_to_header(&rdbh, &dbh);
550         if (dbh.app_info_offset==0) {
551                 *size=0;
552                 return MGU_SUCCESS;
553         }
554         if (dbh.sort_info_offset!=0) {
555                 *size = dbh.sort_info_offset - dbh.app_info_offset;
556                 return MGU_SUCCESS;
557         }
558         if (dbh.number_of_records==0) {
559                 fseek(in, 0, SEEK_END);
560                 *size=ftell(in) - dbh.app_info_offset;
561                 return MGU_SUCCESS;
562         }
563
564         r = fread(&rh, sizeof(record_header), 1, in);
565         if (r < 1)
566                 return MGU_ERROR_READ;
567
568         offset = ((rh.Offset[0]*256+rh.Offset[1])*256+rh.Offset[2])*256+rh.Offset[3];
569         *size=offset - dbh.app_info_offset;
570
571         return MGU_SUCCESS;
572 }
573
574 /*
575  * Read address file into address list. Based on JPilot's
576  * libplugin.c (jp_get_app_info)
577  */
578 static gint jpilot_get_file_info( JPilotFile *pilotFile, unsigned char **buf, int *buf_size ) {
579         FILE *in;
580         int num;
581         unsigned int rec_size;
582         RawDBHeader rdbh;
583         DBHeader dbh;
584
585         if( ( !buf_size ) || ( ! buf ) ) {
586                 return MGU_BAD_ARGS;
587         }
588
589         *buf = NULL;
590         *buf_size=0;
591
592         if( pilotFile->path ) {
593                 in = g_fopen( pilotFile->path, "rb" );
594                 if( !in ) {
595                         return MGU_OPEN_FILE;
596                 }
597         }
598         else {
599                 return MGU_NO_FILE;
600         }
601
602         num = fread( &rdbh, sizeof( RawDBHeader ), 1, in );
603         if( num != 1 ) {
604                 if( ferror(in) ) {
605                         fclose(in);
606                         return MGU_ERROR_READ;
607                 }
608         }
609         if (feof(in)) {
610                 fclose(in);
611                 return MGU_EOF;
612         }
613
614         /* Convert header into something recognizable */
615         raw_header_to_header(&rdbh, &dbh);
616
617         num = jpilot_get_info_size(in, &rec_size);
618         if (num) {
619                 fclose(in);
620                 return MGU_ERROR_READ;
621         }
622
623         fseek(in, dbh.app_info_offset, SEEK_SET);
624         *buf = ( char * ) malloc(rec_size);
625         if (!(*buf)) {
626                 fclose(in);
627                 return MGU_OO_MEMORY;
628         }
629         num = fread(*buf, rec_size, 1, in);
630         if (num != 1) {
631                 if (ferror(in)) {
632                         fclose(in);
633                         free(*buf);
634                         return MGU_ERROR_READ;
635                 }
636         }
637         fclose(in);
638
639         *buf_size = rec_size;
640
641         return MGU_SUCCESS;
642 }
643
644 /* Shamelessly copied from JPilot (libplugin.c) */
645 static int unpack_header(PC3RecordHeader *header, unsigned char *packed_header) {
646         unsigned char *p;
647         guint32 l;
648
649         p = packed_header;
650
651         memcpy(&l, p, sizeof(l));
652         header->header_len=ntohl(l);
653         p+=sizeof(l);
654
655         memcpy(&l, p, sizeof(l));
656         header->header_version=ntohl(l);
657         p+=sizeof(l);
658
659         memcpy(&l, p, sizeof(l));
660         header->rec_len=ntohl(l);
661         p+=sizeof(l);
662
663         memcpy(&l, p, sizeof(l));
664         header->unique_id=ntohl(l);
665         p+=sizeof(l);
666
667         memcpy(&l, p, sizeof(l));
668         header->rt=ntohl(l);
669         p+=sizeof(l);
670
671         memcpy(&(header->attrib), p, sizeof(unsigned char));
672         p+=sizeof(unsigned char);
673
674         return 0;
675 }
676
677 /* Shamelessly copied from JPilot (libplugin.c) */
678 static int read_header(FILE *pc_in, PC3RecordHeader *header) {
679         guint32 l;
680         unsigned long len;
681         unsigned char packed_header[256];
682         int num;
683
684         memset(header, 0, sizeof(PC3RecordHeader));
685
686         num = fread(&l, sizeof(l), 1, pc_in);
687         if (feof(pc_in)) {
688                 return -1;
689         }
690         if (num!=1) {
691                 return num;
692         }
693         memcpy(packed_header, &l, sizeof(l));
694         len=ntohl(l);
695         if (len > 255) {
696                 return -1;
697         }
698         num = fread(packed_header+sizeof(l), len-sizeof(l), 1, pc_in);
699         if (feof(pc_in)) {
700                 return -1;
701         }
702         if (num!=1) {
703                 return num;
704         }
705         unpack_header(header, packed_header);
706         return 1;
707 }
708
709 /**
710  * Read next record from PC3 file. Based on JPilot function
711  * <code>pc_read_next_rec()</code> (libplugin.c)
712  *
713  * \param in File handle.
714  * \param br Record buffer.
715  * \return Status/error code. <code>MGU_SUCCESS</code> if data read
716  *         successfully.
717  */
718 static gint jpilot_read_next_pc( FILE *in, buf_rec *br ) {
719         PC3RecordHeader header;
720         int rec_len, num;
721         char *record;
722
723         if( feof( in ) ) {
724                 return MGU_EOF;
725         }
726         num = read_header( in, &header );
727         if( num < 1 ) {
728                 if( ferror( in ) )
729                         return MGU_ERROR_READ;
730                 else if( feof( in ) )
731                         return MGU_EOF;
732                 else
733                         return -1;
734         }
735         rec_len = header.rec_len;
736         record = malloc( rec_len );
737         if( ! record ) {
738                 return MGU_OO_MEMORY;
739         }
740         num = fread( record, rec_len, 1, in );
741         if( num != 1 ) {
742                 if( ferror( in ) ) {
743                         free( record );
744                         return MGU_ERROR_READ;
745                 }
746         }
747         br->rt = header.rt;
748         br->unique_id = header.unique_id;
749         br->attrib = header.attrib;
750         br->buf = record;
751         br->size = rec_len;
752
753         return MGU_SUCCESS;
754 }
755
756 /**
757  * Read address file into a linked list. Based on JPilot function
758  * <code>jp_read_DB_files()</code> (from libplugin.c)
759  *
760  * \param pilotFile  JPilot control data.
761  * \param records Pointer to linked list of records read.
762  * \return Status/error code. <code>MGU_SUCCESS</code> if data read
763  *         successfully.
764  */
765 static gint jpilot_read_db_files( JPilotFile *pilotFile, GList **records ) {
766         FILE *in, *pc_in;
767         char *buf;
768         GList *temp_list;
769         int num_records, recs_returned, i, num, r;
770         unsigned int offset, prev_offset, next_offset = 0, rec_size;
771         int out_of_order;
772         long fpos;  /*file position indicator */
773         unsigned char attrib = '\0';
774         unsigned int unique_id = 0;
775         mem_rec_header *mem_rh, *temp_mem_rh, *last_mem_rh;
776         record_header rh;
777         RawDBHeader rdbh;
778         DBHeader dbh;
779         buf_rec *temp_br;
780         gchar *pcFile;
781
782         mem_rh = last_mem_rh = NULL;
783         *records = NULL;
784         recs_returned = 0;
785
786         if( pilotFile->path == NULL ) {
787                 return MGU_BAD_ARGS;
788         }
789
790         in = g_fopen( pilotFile->path, "rb" );
791         if (!in) {
792                 return MGU_OPEN_FILE;
793         }
794
795         /* Read the database header */
796         num = fread( &rdbh, sizeof( RawDBHeader ), 1, in );
797         if( num != 1 ) {
798                 if( ferror( in ) ) {
799                         fclose( in );
800                         return MGU_ERROR_READ;
801                 }
802                 if( feof( in ) ) {
803                         fclose( in );
804                         return MGU_EOF;
805                 }
806         }
807         raw_header_to_header( &rdbh, &dbh );
808
809         /* Read each record entry header */
810         num_records = dbh.number_of_records;
811         out_of_order = 0;
812         prev_offset = 0;
813
814         for( i = 1; i < num_records + 1; i++ ) {
815                 num = fread( &rh, sizeof( record_header ), 1, in );
816                 if( num != 1 ) {
817                         if( ferror( in ) ) {
818                                 break;
819                         }
820                         if( feof( in ) ) {
821                                 fclose( in );
822                                 return MGU_EOF;
823                         }
824                 }
825
826                 offset =
827                         ( ( rh.Offset[0] * 256 + rh.Offset[1] ) * 256
828                         + rh.Offset[2] ) * 256
829                         + rh.Offset[3];
830                 if( offset < prev_offset ) {
831                         out_of_order = 1;
832                 }
833                 prev_offset = offset;
834                 temp_mem_rh = ( mem_rec_header * ) malloc( sizeof( mem_rec_header ) );
835                 if( ! temp_mem_rh ) {
836                         break;
837                 }
838                 temp_mem_rh->next = NULL;
839                 temp_mem_rh->rec_num = i;
840                 temp_mem_rh->offset = offset;
841                 temp_mem_rh->attrib = rh.attrib;
842                 temp_mem_rh->unique_id =
843                         ( rh.unique_ID[0] * 256 + rh.unique_ID[1] ) * 256
844                         + rh.unique_ID[2];
845                 if( mem_rh == NULL ) {
846                         mem_rh = temp_mem_rh;
847                         last_mem_rh = temp_mem_rh;
848                 }
849                 else {
850                         last_mem_rh->next = temp_mem_rh;
851                         last_mem_rh = temp_mem_rh;
852                 }
853         }
854
855         temp_mem_rh = mem_rh;
856
857         if( num_records ) {
858                 if( out_of_order ) {
859                         find_next_offset(
860                                 mem_rh, 0, &next_offset, &attrib, &unique_id );
861                 }
862                 else {
863                         if( mem_rh ) {
864                                 next_offset = mem_rh->offset;
865                                 attrib = mem_rh->attrib;
866                                 unique_id = mem_rh->unique_id;
867                         }
868                 }
869                 fseek( in, next_offset, SEEK_SET );
870                 while( ! feof( in ) ) {
871                         fpos = ftell( in );
872                         if( out_of_order ) {
873                                 find_next_offset(
874                                         mem_rh, fpos, &next_offset, &attrib,
875                                         &unique_id );
876                         } else {
877                                 next_offset = 0xFFFFFF;
878                                 if( temp_mem_rh ) {
879                                         attrib = temp_mem_rh->attrib;
880                                         unique_id = temp_mem_rh->unique_id;
881                                         if ( temp_mem_rh->next ) {
882                                                 temp_mem_rh = temp_mem_rh->next;
883                                                 next_offset = temp_mem_rh->offset;
884                                         }
885                                 }
886                         }
887                         rec_size = next_offset - fpos;
888                         buf = malloc( rec_size );
889                         if( ! buf ) break;
890                         num = fread( buf, rec_size, 1, in );
891                         if( ( num != 1 ) ) {
892                                 if( ferror( in ) ) {
893                                         free( buf );
894                                         break;
895                                 }
896                         }
897
898                         temp_br = malloc( sizeof( buf_rec ) );
899                         if( ! temp_br ) {
900                                 free( buf );
901                                 break;
902                         }
903                         temp_br->rt = PALM_REC;
904                         temp_br->unique_id = unique_id;
905                         temp_br->attrib = attrib;
906                         temp_br->buf = buf;
907                         temp_br->size = rec_size;
908
909                         *records = g_list_append( *records, temp_br );
910
911                         recs_returned++;
912                 }
913         }
914         fclose( in );
915         free_mem_rec_header( &mem_rh );
916
917         /* Read the PC3 file, if present */
918         pcFile = jpilot_get_pc3_file( pilotFile );
919         if( pcFile == NULL ) return MGU_SUCCESS;
920         pc_in = g_fopen( pcFile, "rb");
921         g_free( pcFile );
922
923         if( pc_in == NULL ) {
924                 return MGU_SUCCESS;
925         }
926
927         while( ! feof( pc_in ) ) {
928                 gboolean linked;
929
930                 temp_br = malloc( sizeof( buf_rec ) );
931                 if( ! temp_br ) {
932                         break;
933                 }
934                 r = jpilot_read_next_pc( pc_in, temp_br );
935                 if( r != MGU_SUCCESS ) {
936                         if( (r != MGU_EOF) && (r != MGU_ERROR_READ) ) {
937                                 free( temp_br->buf );
938                         }
939                         free( temp_br );
940                         break;
941                 }
942
943                 linked = FALSE;
944                 if( ( temp_br->rt != DELETED_PC_REC )
945                  && ( temp_br->rt != DELETED_PALM_REC )
946                  && ( temp_br->rt != MODIFIED_PALM_REC )
947                  && ( temp_br->rt != DELETED_DELETED_PALM_REC ) )
948                 {
949                         *records = g_list_append( *records, temp_br );
950                         recs_returned++;
951                         linked = TRUE;
952                 }
953
954                 if( ( temp_br->rt == DELETED_PALM_REC )
955                  || ( temp_br->rt == MODIFIED_PALM_REC ) )
956                 {
957                         temp_list = *records;
958                         if( *records ) {
959                                 while( temp_list->next ) {
960                                         temp_list=temp_list->next;
961                                 }
962                         }
963                         for( ; temp_list; temp_list=temp_list->prev ) {
964                                 if( ( ( buf_rec * )temp_list->data )->unique_id ==
965                                     temp_br->unique_id ) {
966                                         ( ( buf_rec * )temp_list->data )->rt =
967                                                 temp_br->rt;
968                                 }
969                         }
970                 }
971
972                 if( ! linked ) {
973                         free( temp_br->buf );
974                         free( temp_br );
975                 }
976         }
977         fclose( pc_in );
978
979         return MGU_SUCCESS;
980 }
981
982 /**
983  * Parse buffer containing multiple e-mail addresses into a linked list of
984  * addresses. Separator characters are " ,;|" and control characters. Address
985  * is only extracted if it contains an "at" (@) character.
986  * 
987  * \param buf Buffer to process.
988  * \return List of strings.
989  */
990 static GList *jpilot_parse_email( gchar *buf ) {
991         GList *list;
992         gchar *p, *st, *em;
993         gchar lch;
994         gint len;
995         gboolean valid, done;
996
997         valid = done = FALSE;
998         lch = ' ';
999         list = NULL;
1000         p = st = buf;
1001         while( ! done ) {
1002                 if( *p == ' ' || *p == ',' || *p == ';' || *p == '|' || *p < 32 ) {
1003                         if( *p == '\0' ) {
1004                                 done = TRUE;
1005                         }
1006                         else {
1007                                 *p = ' ';
1008                         }
1009
1010                         if( *p == lch ) {
1011                                 st++;
1012                         }
1013                         else {
1014                                 len = p - st;
1015                                 if( len > 0 ) {
1016                                         if( valid ) {
1017                                                 em = g_strndup( st, len );
1018                                                 list = g_list_append( list, em );
1019                                         }
1020                                         st = p;
1021                                         ++st;
1022                                         valid = FALSE;
1023                                 }
1024                         }
1025                 }
1026                 if( *p == '@' ) valid = TRUE;
1027                 lch = *p;
1028                 ++p;
1029         }
1030
1031         return list;    
1032 }
1033
1034 #define FULLNAME_BUFSIZE        256
1035 #define EMAIL_BUFSIZE           256
1036
1037 /**
1038  * Process a single label entry field, parsing multiple e-mail address entries.
1039  *
1040  * \param pilotFile  JPilot control data.
1041  * \param labelEntry Label entry data.
1042  * \param person     Person.
1043  */
1044 static void jpilot_parse_label( JPilotFile *pilotFile, gchar *labelEntry, ItemPerson *person ) {
1045         gchar buffer[ EMAIL_BUFSIZE ];
1046         ItemEMail *email;
1047         GList *list, *node;
1048
1049         if( labelEntry ) {
1050                 *buffer = '\0';
1051                 strcpy( buffer, labelEntry );
1052                 node = list = jpilot_parse_email( buffer );
1053                 while( node ) {
1054                         email = addritem_create_item_email();
1055                         addritem_email_set_address( email, node->data );
1056                         if (convert_charcode) {
1057                                 gchar *convertBuff = NULL;
1058                                 convertBuff = conv_codeset_strdup( labelEntry, 
1059                                                 jpilot_get_charset(), 
1060                                                 CS_INTERNAL );
1061                                 if (convertBuff)
1062                                         addritem_email_set_remarks( email, convertBuff );
1063                                 g_free( convertBuff );
1064                         }
1065                         else {
1066                                 addritem_email_set_remarks(email, buffer);
1067                         }
1068
1069                         addrcache_id_email( pilotFile->addressCache, email );
1070                         addrcache_person_add_email( pilotFile->addressCache, person, email );
1071                         node = g_list_next( node );
1072                 }
1073                 mgu_free_dlist( list );
1074                 list = NULL;
1075         }
1076 }
1077         
1078 /**
1079  * Unpack address, building new data inside cache.
1080  * \param pilotFile  JPilot control data.
1081  * \param buf        Record buffer.
1082  * \param folderInd  Array of (category) folders to load.
1083  */
1084 static void jpilot_load_address(
1085                 JPilotFile *pilotFile, buf_rec *buf, ItemFolder *folderInd[] )
1086 {
1087         struct Address addr;
1088         gchar **addrEnt;
1089         gint k;
1090         gint cat_id = 0;
1091         guint unique_id;
1092         guchar attrib;
1093         gchar fullName[ FULLNAME_BUFSIZE ];
1094         ItemPerson *person;
1095         gint *indPhoneLbl;
1096         gchar *labelEntry;
1097         GList *node;
1098         gchar* extID;
1099         gchar **firstName = NULL;
1100         gchar **lastName = NULL;
1101 #if (PILOT_LINK_MAJOR > 11)
1102         pi_buffer_t *RecordBuffer;
1103         RecordBuffer = pi_buffer_new(buf->size);
1104
1105         memcpy(RecordBuffer->data, buf->buf, buf->size);
1106         RecordBuffer->used = buf->size;
1107         if (unpack_Address(&addr, RecordBuffer, address_v1) == -1) {
1108                 pi_buffer_free(RecordBuffer);
1109                 return;
1110         }
1111         pi_buffer_free(RecordBuffer);
1112 #else
1113         gint num;
1114
1115         num = unpack_Address(&addr, buf->buf, buf->size);
1116         if (num <= 0) {
1117                 return;
1118         }
1119 #endif /* PILOT_LINK_0_12 */
1120
1121         addrEnt = addr.entry;
1122         attrib = buf->attrib;
1123         unique_id = buf->unique_id;
1124         cat_id = attrib & 0x0F;
1125
1126         *fullName = '\0';
1127         if( addrEnt[ IND_LABEL_FIRSTNAME ] ) {
1128                 firstName = g_strsplit( addrEnt[ IND_LABEL_FIRSTNAME ], "\01", 2 );
1129         }
1130
1131         if( addrEnt[ IND_LABEL_LASTNAME ] ) {
1132                 lastName = g_strsplit( addrEnt[ IND_LABEL_LASTNAME ], "\01", 2 );
1133         }
1134
1135         if( name_order == FAMILY_LAST ) {
1136                 g_snprintf( fullName, FULLNAME_BUFSIZE, "%s %s",
1137                             firstName ? firstName[0] : "",
1138                             lastName ? lastName[0] : "" );
1139         }
1140         else {
1141                 g_snprintf( fullName, FULLNAME_BUFSIZE, "%s %s",
1142                             lastName ? lastName[0] : "",
1143                             firstName ? firstName[0] : "" );
1144         }
1145
1146         if( firstName ) {
1147                 g_strfreev( firstName );
1148         }
1149         if( lastName ) {
1150                 g_strfreev( lastName );
1151         }
1152
1153         g_strstrip( fullName );
1154
1155         if( convert_charcode ) {
1156                 gchar *nameConv = NULL;
1157                 nameConv = conv_codeset_strdup( fullName, 
1158                                 jpilot_get_charset(), 
1159                                 CS_INTERNAL );
1160                 if (nameConv)
1161                         strncpy2( fullName, nameConv, FULLNAME_BUFSIZE );
1162                 g_free( nameConv );
1163         }
1164
1165         person = addritem_create_item_person();
1166         addritem_person_set_common_name( person, fullName );
1167         addritem_person_set_first_name( person, addrEnt[ IND_LABEL_FIRSTNAME ] );
1168         addritem_person_set_last_name( person, addrEnt[ IND_LABEL_LASTNAME ] );
1169         addrcache_id_person( pilotFile->addressCache, person );
1170
1171         extID = g_strdup_printf( "%d", unique_id );
1172         addritem_person_set_external_id( person, extID );
1173         g_free( extID );
1174         extID = NULL;
1175
1176         /* Add entry for each email address listed under phone labels. */
1177         indPhoneLbl = addr.phoneLabel;
1178         for( k = 0; k < JPILOT_NUM_ADDR_PHONE; k++ ) {
1179                 if( indPhoneLbl[k] == IND_PHONE_EMAIL ) {
1180                         labelEntry = addrEnt[ OFFSET_PHONE_LABEL + k ];
1181                         jpilot_parse_label( pilotFile, labelEntry, person );
1182                 }
1183         }
1184
1185         /* Add entry for each custom label */
1186         node = pilotFile->labelInd;
1187         while( node ) {
1188                 gint ind;
1189
1190                 ind = GPOINTER_TO_INT( node->data );
1191                 if( ind > -1 ) {
1192                         /*
1193                         * g_print( "%d : %20s : %s\n", ind, ai->labels[ind],
1194                         * addrEnt[ind] );
1195                         */
1196                         labelEntry = addrEnt[ind];
1197                         jpilot_parse_label( pilotFile, labelEntry, person );
1198                 }
1199
1200                 node = g_list_next( node );
1201         }
1202
1203         if( person->listEMail ) {
1204                 if( cat_id > -1 && cat_id < JPILOT_NUM_CATEG ) {
1205                         /* Add to specified category */
1206                         addrcache_folder_add_person(
1207                                 pilotFile->addressCache,
1208                                 folderInd[cat_id], person );
1209                 }
1210                 else {
1211                         /* Add to root folder */
1212                         addrcache_add_person(
1213                                 pilotFile->addressCache, person );
1214                 }
1215         }
1216         else {
1217                 addritem_free_item_person( person );
1218                 person = NULL;
1219         }
1220         /* Free up pointer allocated inside address */
1221         free_Address( & addr );
1222 }
1223
1224 /**
1225  * Free up address list.
1226  * \param records List of records to free.
1227  */
1228 static void jpilot_free_addrlist( GList *records ) {
1229         GList *node;
1230         buf_rec *br;
1231
1232         node = records;
1233         while( node ) {
1234                 br = node->data;
1235                 free( br->buf );
1236                 free( br );
1237                 node->data = NULL;
1238                 node = g_list_next( node );
1239         }
1240
1241         /* Free up list */
1242         g_list_free( records );
1243 }
1244
1245 /**
1246  * Read metadata from file.
1247  * \param pilotFile  JPilot control data.
1248  * \return Status/error code. <code>MGU_SUCCESS</code> if data read
1249  *         successfully.
1250  */
1251 static gint jpilot_read_metadata( JPilotFile *pilotFile ) {
1252         gint retVal;
1253         unsigned int rec_size;
1254         unsigned char *buf;
1255         int num;
1256
1257         cm_return_val_if_fail( pilotFile != NULL, -1 );
1258
1259         pilotFile->readMetadata = FALSE;
1260         addrcache_clear( pilotFile->addressCache );
1261
1262         /* Read file info */
1263         retVal = jpilot_get_file_info( pilotFile, &buf, &rec_size);
1264         if( retVal != MGU_SUCCESS ) {
1265                 pilotFile->retVal = retVal;
1266                 return pilotFile->retVal;
1267         }
1268
1269         num = unpack_AddressAppInfo( &pilotFile->addrInfo, buf, rec_size );
1270         if( buf ) {
1271                 free(buf);
1272         }
1273         if( num <= 0 ) {
1274                 pilotFile->retVal = MGU_ERROR_READ;
1275                 return pilotFile->retVal;
1276         }
1277
1278         pilotFile->readMetadata = TRUE;
1279         pilotFile->retVal = MGU_SUCCESS;
1280         return pilotFile->retVal;
1281 }
1282
1283 /**
1284  * Setup labels and indexes from metadata.
1285  * \param pilotFile  JPilot control data.
1286  * \return <i>TRUE</i> is setup successfully.
1287  */
1288 static gboolean jpilot_setup_labels( JPilotFile *pilotFile ) {
1289         gboolean retVal = FALSE;
1290         struct AddressAppInfo *ai;
1291         GList *node;
1292
1293         cm_return_val_if_fail( pilotFile != NULL, -1 );
1294
1295         /* Release indexes */
1296         node = pilotFile->labelInd;
1297         while( node ) {
1298                 node->data = NULL;
1299                 node = g_list_next( node );
1300         }
1301         pilotFile->labelInd = NULL;
1302
1303         if( pilotFile->readMetadata ) {
1304                 ai = & pilotFile->addrInfo;
1305                 node = pilotFile->customLabels;
1306                 while( node ) {
1307                         gchar *lbl = node->data;
1308                         gint ind = -1;
1309                         gint i;
1310                         for( i = 0; i < JPILOT_NUM_LABELS; i++ ) {
1311                                 gchar *labelName = ai->labels[i];
1312
1313                                 if( convert_charcode ) {
1314                                         gchar *convertBuff = NULL;
1315                                         convertBuff = conv_codeset_strdup( labelName, 
1316                                                         jpilot_get_charset(), 
1317                                                         CS_INTERNAL );
1318                                         if (convertBuff) {
1319                                                 labelName = convertBuff;
1320                                         }
1321                                 }
1322
1323                                 if( g_utf8_collate( labelName, lbl ) == 0 ) {
1324                                         ind = i;
1325                                         break;
1326                                 }
1327                         }
1328                         pilotFile->labelInd = g_list_append(
1329                                 pilotFile->labelInd, GINT_TO_POINTER(ind) );
1330                         node = g_list_next( node );
1331                 }
1332                 retVal = TRUE;
1333         }
1334         return retVal;
1335 }
1336
1337 /**
1338  * Load list with character strings of custom label names. Only none blank
1339  * names are loaded.
1340  * \param pilotFile  JPilot control data.
1341  * \param labelList List of label names to load.
1342  * \return List of label names loaded. Should be freed when done.
1343  */
1344 GList *jpilot_load_custom_label( JPilotFile *pilotFile, GList *labelList ) {
1345         gint i;
1346
1347         cm_return_val_if_fail( pilotFile != NULL, NULL );
1348
1349         if( pilotFile->readMetadata ) {
1350                 struct AddressAppInfo *ai = & pilotFile->addrInfo;
1351                 for( i = 0; i < NUM_CUSTOM_LABEL; i++ ) {
1352                         gchar *labelName = ai->labels[i+IND_CUSTOM_LABEL];
1353                         if( labelName ) {
1354                                 g_strchomp( labelName );
1355                                 g_strchug( labelName );
1356                                 if( *labelName != '\0' ) {
1357                                         if( convert_charcode ) {
1358                                                 gchar *convertBuff = NULL;
1359                                                 convertBuff = conv_codeset_strdup( labelName, 
1360                                                                 jpilot_get_charset(), 
1361                                                                 CS_INTERNAL );
1362                                                 if (convertBuff) {
1363                                                         labelName = convertBuff;
1364                                                 }
1365                                         }
1366                                         else {
1367                                                 labelName = g_strdup( labelName );
1368                                         }
1369                                         labelList = g_list_append( labelList, labelName );
1370                                 }
1371                         }
1372                 }
1373         }
1374         return labelList;
1375 }
1376
1377 /**
1378  * Build folder in address book for each category.
1379  * \param pilotFile  JPilot control data.
1380  */
1381 static void jpilot_build_category_list( JPilotFile *pilotFile ) {
1382         struct AddressAppInfo *ai = & pilotFile->addrInfo;
1383         struct CategoryAppInfo *cat = & ai->category;
1384         gint i;
1385
1386         for( i = 0; i < JPILOT_NUM_CATEG; i++ ) {
1387                 ItemFolder *folder = addritem_create_item_folder();
1388
1389                 if( convert_charcode ) {
1390                         gchar *convertBuff = NULL;
1391                         convertBuff = conv_codeset_strdup( cat->name[i], 
1392                                         jpilot_get_charset(), 
1393                                         CS_INTERNAL );
1394                         if (convertBuff) {
1395                                 addritem_folder_set_name( folder, convertBuff );
1396                                 g_free( convertBuff );
1397                         } else {
1398                                 addritem_folder_set_name( folder, cat->name[i] );
1399                         }
1400                 }
1401                 else {
1402                         addritem_folder_set_name( folder, cat->name[i] );
1403                 }
1404
1405                 addrcache_id_folder( pilotFile->addressCache, folder );
1406                 addrcache_add_folder( pilotFile->addressCache, folder );
1407         }
1408 }
1409
1410 /**
1411  * Remove empty (category) folders.
1412  * \param pilotFile  JPilot control data.
1413  */
1414 static void jpilot_remove_empty( JPilotFile *pilotFile ) {
1415         GList *listFolder;
1416         GList *remList;
1417         GList *node;
1418         gint i = 0;
1419
1420         listFolder = addrcache_get_list_folder( pilotFile->addressCache );
1421         node = listFolder;
1422         remList = NULL;
1423         while( node ) {
1424                 ItemFolder *folder = node->data;
1425                 if( ADDRITEM_NAME(folder) == NULL || *ADDRITEM_NAME(folder) == '\0' ) {
1426                         if( folder->listPerson ) {
1427                                 /* Give name to folder */
1428                                 gchar name[20];
1429                                 sprintf( name, "? %d", i );
1430                                 addritem_folder_set_name( folder, name );
1431                         }
1432                         else {
1433                                 /* Mark for removal */
1434                                 remList = g_list_append( remList, folder );
1435                         }
1436                 }
1437                 node = g_list_next( node );
1438                 i++;
1439         }
1440         node = remList;
1441         while( node ) {
1442                 ItemFolder *folder = node->data;
1443                 addrcache_remove_folder( pilotFile->addressCache, folder );
1444                 node = g_list_next( node );
1445         }
1446         g_list_free( remList );
1447 }
1448
1449 /**
1450  * Read address file into address cache.
1451  * \param pilotFile  JPilot control data.
1452  * \return Error/status code. <code>MGU_SUCCESS</code> if data read
1453  *         successfully.
1454  */
1455 static gint jpilot_read_file( JPilotFile *pilotFile ) {
1456         gint retVal, i;
1457         GList *records = NULL;
1458         GList *node;
1459         buf_rec *br;
1460         ItemFolder *folderInd[ JPILOT_NUM_CATEG ];
1461
1462         /* Read list of records from JPilot files */
1463         retVal = jpilot_read_db_files( pilotFile, &records );
1464         if( retVal != MGU_SUCCESS ) {
1465                 jpilot_free_addrlist( records );
1466                 return retVal;
1467         }
1468
1469         /* Setup labels and category folders */
1470         jpilot_setup_labels( pilotFile );
1471         jpilot_build_category_list( pilotFile );
1472
1473         /* Build array of pointers to categories */
1474         i = 0;
1475         node = addrcache_get_list_folder( pilotFile->addressCache );
1476         while( node ) {
1477                 if( i < JPILOT_NUM_CATEG ) {
1478                         folderInd[i] = node->data;
1479                 }
1480                 node = g_list_next( node );
1481                 i++;
1482         }
1483
1484         /* Load all addresses, free up old stuff as we go */
1485         node = records;
1486         while( node ) {
1487                 br = node->data;
1488                 if( ( br->rt != DELETED_PC_REC ) &&
1489                     ( br->rt != DELETED_PALM_REC ) &&
1490                     ( br->rt != MODIFIED_PALM_REC ) &&
1491                     ( br->rt != DELETED_DELETED_PALM_REC ) ) {
1492                         jpilot_load_address( pilotFile, br, folderInd );
1493                 }
1494                 free( br->buf );
1495                 free( br );
1496                 node->data = NULL;
1497                 node = g_list_next( node );
1498         }
1499
1500         /* Free up list */
1501         g_list_free( records );
1502
1503         /* Remove empty category folders */
1504         jpilot_remove_empty( pilotFile );
1505         jpilot_mark_files( pilotFile );
1506
1507         return retVal;
1508 }
1509
1510 /**
1511  * Read file into list. Main entry point
1512  * \param pilotFile  JPilot control data.
1513  * \return Error/status code. <code>MGU_SUCCESS</code> if data read
1514  *         successfully.
1515  */
1516 gint jpilot_read_data( JPilotFile *pilotFile ) {
1517         const gchar *cur_locale;
1518
1519         name_order = FAMILY_LAST;
1520
1521         cur_locale = conv_get_current_locale();
1522
1523         if( g_ascii_strncasecmp( cur_locale, "ja", 2 ) == 0 ) {
1524                 name_order = FAMILY_FIRST;
1525         }
1526
1527         cm_return_val_if_fail( pilotFile != NULL, -1 );
1528
1529         pilotFile->retVal = MGU_SUCCESS;
1530         pilotFile->addressCache->accessFlag = FALSE;
1531         if( jpilot_check_files( pilotFile ) ) {
1532                 addrcache_clear( pilotFile->addressCache );
1533                 jpilot_read_metadata( pilotFile );
1534                 if( pilotFile->retVal == MGU_SUCCESS ) {
1535                         pilotFile->retVal = jpilot_read_file( pilotFile );
1536                         if( pilotFile->retVal == MGU_SUCCESS ) {
1537                                 pilotFile->addressCache->modified = FALSE;
1538                                 pilotFile->addressCache->dataRead = TRUE;
1539                         }
1540                 }
1541         }
1542         return pilotFile->retVal;
1543 }
1544
1545 /**
1546  * Return linked list of persons. This is a list of references to ItemPerson
1547  * objects. Do <b>NOT</b> attempt to use the <code>addrbook_free_xxx()</code>
1548  * functions... this will destroy the addressbook data!
1549  *
1550  * \param  pilotFile  JPilot control data.
1551  * \return List of persons.
1552  */
1553 GList *jpilot_get_list_person( JPilotFile *pilotFile ) {
1554         cm_return_val_if_fail( pilotFile != NULL, NULL );
1555         return addrcache_get_list_person( pilotFile->addressCache );
1556 }
1557
1558 /**
1559  * Return linked list of folders. This is a list of references to non-empty
1560  * category folders. Do <b>NOT</b> attempt to use the
1561  * <code>addrbook_free_xxx()</code> functions... this will destroy the
1562  * addressbook data!
1563  *
1564  * \param  pilotFile  JPilot control data.
1565  * \return List of ItemFolder objects. This should not be freed.
1566  */
1567 GList *jpilot_get_list_folder( JPilotFile *pilotFile ) {
1568         cm_return_val_if_fail( pilotFile != NULL, NULL );
1569         return addrcache_get_list_folder( pilotFile->addressCache );
1570 }
1571
1572 /**
1573  * Return linked list of all persons. Note that the list contains references
1574  * to items. Do <b>NOT</b> attempt to use the <code>addrbook_free_xxx()</code>
1575  * functions... this will destroy the addressbook data!
1576  *
1577  * \param pilotFile  JPilot control data.
1578  * \return List of items, or NULL if none.
1579  */
1580 GList *jpilot_get_all_persons( JPilotFile *pilotFile ) {
1581         cm_return_val_if_fail( pilotFile != NULL, NULL );
1582         return addrcache_get_all_persons( pilotFile->addressCache );
1583 }
1584
1585 #define WORK_BUFLEN 1024
1586
1587 /**
1588  * Attempt to find a valid JPilot file.
1589  * \param pilotFile  JPilot control data.
1590  * \return Filename, or home directory if not found, or empty string if
1591  *         no home. Filename should be <code>g_free()</code> when done.
1592  */
1593 gchar *jpilot_find_pilotdb( void ) {
1594         const gchar *homedir;
1595         gchar str[ WORK_BUFLEN + 1 ];
1596         gint len;
1597         FILE *fp;
1598
1599         homedir = get_home_dir();
1600         if( ! homedir ) return g_strdup( "" );
1601
1602         strcpy( str, homedir );
1603         len = strlen( str );
1604         if( len > 0 ) {
1605                 if( str[ len-1 ] != G_DIR_SEPARATOR ) {
1606                         str[ len ] = G_DIR_SEPARATOR;
1607                         str[ ++len ] = '\0';
1608                 }
1609         }
1610         strncat( str, JPILOT_DBHOME_DIR, WORK_BUFLEN - strlen(str) );
1611         strncat( str, G_DIR_SEPARATOR_S, WORK_BUFLEN - strlen(str) );
1612         strncat( str, JPILOT_DBHOME_FILE, WORK_BUFLEN - strlen(str) );
1613
1614         /* Attempt to open */
1615         if( ( fp = g_fopen( str, "rb" ) ) != NULL ) {
1616                 fclose( fp );
1617         }
1618         else {
1619                 /* Truncate filename */
1620                 str[ len ] = '\0';
1621         }
1622         return g_strdup( str );
1623 }
1624
1625 /**
1626  * Check whether label is in list of custom labels.
1627  * \param pilotFile JPilot control data.
1628  * \param labelName to test.
1629  * \return <i>TRUE</i> if found.
1630  */
1631 gboolean jpilot_test_custom_label( JPilotFile *pilotFile, const gchar *labelName ) {
1632         gboolean retVal;
1633         GList *node;
1634
1635         cm_return_val_if_fail( pilotFile != NULL, FALSE );
1636
1637         retVal = FALSE;
1638         if( labelName ) {
1639                 node = pilotFile->customLabels;
1640                 while( node ) {
1641                         if( g_utf8_collate( labelName, ( gchar * ) node->data ) == 0 ) {
1642                                 retVal = TRUE;
1643                                 break;
1644                         }
1645                         node = g_list_next( node );
1646                 }
1647         }
1648         return retVal;
1649 }
1650
1651 /**
1652  * Test whether pilot link library installed.
1653  * \return <i>TRUE</i> if library available.
1654  */
1655 gboolean jpilot_test_pilot_lib( void ) {
1656         return TRUE;
1657 }
1658
1659 #endif  /* USE_JPILOT */
1660
1661 /*
1662 * End of Source.
1663 */