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