File: gmds.m

package info (click to toggle)
gworkspace 0.9.4-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 20,832 kB
  • sloc: objc: 69,382; sh: 488; makefile: 39
file content (763 lines) | stat: -rw-r--r-- 20,091 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
/* gmsd.m
 *  
 * Copyright (C) 2006-2013 Free Software Foundation, Inc.
 *
 * Author: Enrico Sersale <enrico@dtedu.net>
 * Date: February 2006
 *
 * This file is part of the GNUstep GWorkspace application
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111 USA.
 */

#include <sys/types.h>
#include <sys/stat.h>
#include "gmds.h"
#include "dbschema.h"
#include "config.h"

#define GWDebugLog(format, args...) \
  do { \
    if (GW_DEBUG_LOG) { \
      NSLog(format , ## args); \
    } \
  } while (0)

#define GWPrintfDebugLog(format, args...) \
  do { \
    if (GW_DEBUG_LOG) { \
      fprintf(stderr, format , ## args); \
      fflush(stderr); \
    } \
  } while (0)

#define MAX_RETRY 1000
#define MAX_RES 100
#define TOUCH_INTERVAL (60.0)

enum {
  STRING,
  ARRAY,
  NUMBER,
  DATE_TYPE,
  DATA
};

enum {
  NUM_INT,
  NUM_FLOAT,
  NUM_BOOL
};

typedef enum _MDKOperatorType
{
  MDKLessThanOperatorType,
  MDKLessThanOrEqualToOperatorType,
  MDKGreaterThanOperatorType,
  MDKGreaterThanOrEqualToOperatorType,
  MDKEqualToOperatorType,
  MDKNotEqualToOperatorType,
  MDKInRangeOperatorType
} MDKOperatorType;


static void path_exists(sqlite3_context *context, int argc, sqlite3_value **argv)
{
  const unsigned char *path = sqlite3_value_text(argv[0]);
  int exists = 0;
  
  if (path) {
    struct stat statbuf;  
    exists = (stat((const char *)path, &statbuf) == 0);
  }
     
  sqlite3_result_int(context, exists);
}

static void path_moved(sqlite3_context *context, int argc, sqlite3_value **argv)
{
  const unsigned char *oldbase = sqlite3_value_text(argv[0]);
  int oldblen = strlen((const char *)oldbase);
  const unsigned char *newbase = sqlite3_value_text(argv[1]);
  int newblen = strlen((const char *)newbase);
  const unsigned char *oldpath = sqlite3_value_text(argv[2]);
  int oldplen = strlen((const char *)oldpath);
  char *newpath;
  int i = newblen;
  int j;
  
  newpath = malloc(newblen + oldplen - oldblen + 1);
  strncpy(newpath, (const char *)newbase, newblen + oldplen - oldblen + 1);

  for (j = oldblen; j < oldplen; j++) {
    newpath[i] = oldpath[j];
    i++;
  }
  
  newpath[i] = '\0';
  
  sqlite3_result_text(context, newpath, strlen(newpath), SQLITE_TRANSIENT);

  free(newpath);
}

static void time_stamp(sqlite3_context *context, int argc, sqlite3_value **argv)
{
  NSTimeInterval interval = [[NSDate date] timeIntervalSinceReferenceDate];

  sqlite3_result_double(context, interval);
}

static void contains_substr(sqlite3_context *context, int argc, sqlite3_value **argv)
{
  const char *buff = (const char *)sqlite3_value_text(argv[0]);
  const char *substr = (const char *)sqlite3_value_text(argv[1]);
  int contains = (strstr(buff, substr) != NULL);
  
  sqlite3_result_int(context, contains);
}

static void append_string(sqlite3_context *context, int argc, sqlite3_value **argv)
{
  const char *buff = (const char *)sqlite3_value_text(argv[0]);
  const char *str = (const char *)sqlite3_value_text(argv[1]);

  if (strstr(buff, str) == NULL) {
    char newbuff[2048] = "";
  
    sprintf(newbuff, "%s %s", buff, str);
    newbuff[strlen(newbuff)] = '\0';
    sqlite3_result_text(context, newbuff, strlen(newbuff), SQLITE_TRANSIENT);
    
    return;
  } 
  
  sqlite3_result_text(context, buff, strlen(buff), SQLITE_TRANSIENT);  
}

static void word_score(sqlite3_context *context, int argc, sqlite3_value **argv)
{
  int searchlen = strlen((const char *)sqlite3_value_text(argv[0]));
  int foundlen = strlen((const char *)sqlite3_value_text(argv[1]));
  int posting_wcount = sqlite3_value_int(argv[2]);
  int path_wcount = sqlite3_value_int(argv[3]);
  float score = (1.0 * posting_wcount / path_wcount);

  if (searchlen != foundlen) {
    score *= (1.0 * searchlen / foundlen);    
  } 

  sqlite3_result_double(context, score);
}

static void attribute_score(sqlite3_context *context, int argc, sqlite3_value **argv)
{
  sqlite3_result_double(context, 0.0);
}


@implementation	GMDS

- (void)dealloc
{
  NSConnection *connection = [clientInfo objectForKey: @"connection"];
  
  if (connection) {
    [nc removeObserver: self
		              name: NSConnectionDidDieNotification
		            object: connection];
  }

  RELEASE (clientInfo);
  
  [nc removeObserver: self
		            name: NSConnectionDidDieNotification
		          object: conn];
  DESTROY (conn);
  RELEASE (connectionName);
  
  if (db != NULL) {
    sqlite3_close(db);
  }
  
  RELEASE (dbpath);
  RELEASE (dbdir);
  RELEASE (touchQueries);
  
  [super dealloc];
}

- (id)init
{
  self = [super init];
  
  if (self) {    
    BOOL isdir;

    fm = [NSFileManager defaultManager];
  
    dbdir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    dbdir = [dbdir stringByAppendingPathComponent: @"gmds"];

    if (([fm fileExistsAtPath: dbdir isDirectory: &isdir] &isdir) == NO) {
      if ([fm createDirectoryAtPath: dbdir attributes: nil] == NO) { 
        NSLog(@"unable to create: %@", dbdir);
        DESTROY (self);
        return self;
      }
    }

    dbdir = [dbdir stringByAppendingPathComponent: @".db"];

    if (([fm fileExistsAtPath: dbdir isDirectory: &isdir] &isdir) == NO) {
      if ([fm createDirectoryAtPath: dbdir attributes: nil] == NO) { 
        NSLog(@"unable to create: %@", dbdir);
        DESTROY (self);
        return self;
      }
    }

    dbdir = [dbdir stringByAppendingPathComponent: db_version];

    if (([fm fileExistsAtPath: dbdir isDirectory: &isdir] &isdir) == NO) {
      if ([fm createDirectoryAtPath: dbdir attributes: nil] == NO) { 
        NSLog(@"unable to create: %@", dbdir);
        DESTROY (self);
        return self;
      }
    }
    
    RETAIN (dbdir);
    ASSIGN (dbpath, [dbdir stringByAppendingPathComponent: @"contents.db"]);    
    db = NULL;

    if ([self opendb] == NO) {
      DESTROY (self);
      return self;    
    }
    
    conn = [NSConnection defaultConnection];
    [conn setRootObject: self];
    [conn setDelegate: self];
    
    if ([conn registerName: @"gmds"] == NO) {
	    NSLog(@"unable to register with name server - quitting.");
	    DESTROY (self);
	    return self;
	  }
    
    nc = [NSNotificationCenter defaultCenter];
      
    [nc addObserver: self
           selector: @selector(connectionDidDie:)
	             name: NSConnectionDidDieNotification
	           object: conn];
             
    clientInfo = [NSMutableDictionary new];
    
    touchQueries = [NSMutableArray new];
    touchind = 0;
    [touchQueries addObject: @"select count(is_directory) from paths;"];
    [touchQueries addObject: @"select count(word) from words;"];
    [touchQueries addObject: @"select count(word_count) from postings;"];
    [touchQueries addObject: @"select count(attribute) from attributes;"];
    
    [NSTimer scheduledTimerWithTimeInterval: TOUCH_INTERVAL 
                                     target: self 
                                   selector: @selector(touchTables:) 
                                   userInfo: nil 
                                    repeats: YES];
  }
  
  return self;    
}

- (BOOL)connection:(NSConnection *)parentConnection
            shouldMakeNewConnection:(NSConnection *)newConnnection
{
  if ([clientInfo objectForKey: @"connection"] == nil) {
    CREATE_AUTORELEASE_POOL(pool); 
    NSProcessInfo *info = [NSProcessInfo processInfo];
    NSMutableArray *args = [[info arguments] mutableCopy];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    id connum = [defaults objectForKey: @"gmds_connection_number"]; 
    unsigned long ln;
    NSTask *task; 

    if (connum == nil) {
      connum = [NSNumber numberWithUnsignedLong: 0L];
    }

    ln = [connum unsignedLongValue];
    ASSIGN (connectionName, ([NSString stringWithFormat: @"gmds_%lu", ln]));

    if ([conn registerName: connectionName] == NO) {
      NSLog(@"unable to register with name server - quitting.");
      exit(EXIT_FAILURE);
    }

    GWDebugLog(@"connection name changed to %@", connectionName);

    ln++;
    connum = [NSNumber numberWithUnsignedLong: ln];
    [defaults setObject: connum forKey: @"gmds_connection_number"];
    [defaults synchronize];

    task = [NSTask new];
    [task setLaunchPath: [[NSBundle mainBundle] executablePath]];
    [args removeObjectAtIndex: 0];
    if (![args containsObject: @"--daemon"])
      {
        [args addObject: @"--daemon"];
      }
    [task setArguments: args];
    RELEASE (args);
    [task setEnvironment: [info environment]];
    [task launch];
    RELEASE (task);

    RELEASE (pool);
    
    [clientInfo setObject: newConnnection forKey: @"connection"];
    
    [newConnnection setDelegate: self];
    
    [nc addObserver: self
           selector: @selector(connectionDidDie:)
	             name: NSConnectionDidDieNotification
	           object: newConnnection];

    GWDebugLog(@"new client connection");

    return YES;
  } 
  
  NSLog(@"client connection already exists!");
  
  return NO;
}

- (void)connectionDidDie:(NSNotification *)notification
{
  id connection = [notification object];

  [nc removeObserver: self
	              name: NSConnectionDidDieNotification
	            object: connection];
  
  if (connection == conn) {
    NSLog(@"[gmds connectionDidDie]: Error: gmds server root connection has been destroyed.");
    exit(EXIT_FAILURE);
  }
  
  [self terminate]; 
}

- (oneway void)registerClient:(id)remote
{  
  if ([clientInfo objectForKey: @"client"] == nil) { 
    [(id)remote setProtocolForProxy: @protocol(GMDSClientProtocol)];    
    [clientInfo setObject: remote forKey: @"client"];
    GWDebugLog(@"new client registered");
  }
}

- (oneway void)unregisterClient:(id)remote
{
  id client = [clientInfo objectForKey: @"client"];  

  if (client && (client == remote)) {
    [clientInfo removeObjectForKey: @"client"]; 
    GWDebugLog(@"client unregistered");
    [self terminate]; 
  }
}

- (BOOL)performSubquery:(NSString *)query
{
  CREATE_AUTORELEASE_POOL(pool); 
  const char *qbuff = [query UTF8String];
  struct sqlite3_stmt *stmt;
  int err;

  if ((err = sqlite3_prepare(db, qbuff, strlen(qbuff), &stmt, NULL)) == SQLITE_OK) {  
    int retry = 0;
    
    while (1) {
      err = sqlite3_step(stmt);

      if (err == SQLITE_DONE) {
        break;

      } else if (err == SQLITE_BUSY) {
        CREATE_AUTORELEASE_POOL(arp); 
        NSDate *when = [NSDate dateWithTimeIntervalSinceNow: 0.1];

        [NSThread sleepUntilDate: when];
        GWDebugLog(@"retry %i", retry);
        RELEASE (arp);

        if (retry++ > MAX_RETRY) {
          NSLog(@"%s", sqlite3_errmsg(db));
		      break;
        }

      } else {
        NSLog(@"%s", sqlite3_errmsg(db));
        break;
      }
    }
    
    sqlite3_finalize(stmt);
  }
  
  RELEASE (pool);
    
  return (err == SQLITE_DONE);
}

- (BOOL)performPreQueries:(NSArray *)queries
{
  int i;
  
  if ([self performSubquery: @"BEGIN"] == NO) {
    return NO;
  }
  
  for (i = 0; i < [queries count]; i++) {
    if ([self performSubquery: [queries objectAtIndex: i]] == NO) {
      [self performSubquery: @"COMMIT"];
      return NO;
    }
  }
  
  [self performSubquery: @"COMMIT"];
   
  return YES;
}

- (void)performPostQueries:(NSArray *)queries
{
  int i;

  if ([self performSubquery: @"BEGIN"] == NO) {
    return;
  }

  for (i = 0; i < [queries count]; i++) {
    [self performSubquery: [queries objectAtIndex: i]];
  }

  [self performSubquery: @"COMMIT"];
}

- (oneway void)performQuery:(NSDictionary *)queryInfo
{
  CREATE_AUTORELEASE_POOL(pool); 
  NSArray *prequeries = [queryInfo objectForKey: @"pre"];
  BOOL prepared = YES;
  NSString *query = [queryInfo objectForKey: @"join"];
  NSArray *postqueries = [queryInfo objectForKey: @"post"];  
  NSNumber *queryNumber = [queryInfo objectForKey: @"qnumber"];  
  const char *qbuff = [query UTF8String];
  NSMutableArray *reslines = [NSMutableArray array];
  struct sqlite3_stmt *stmt;
  int retry = 0;
  int err;
  int i;
  
  if (prequeries) {
    prepared = [self performPreQueries: prequeries];
  }
  
  if (prepared && (sqlite3_prepare(db, qbuff, strlen(qbuff), &stmt, NULL) == SQLITE_OK)) {
    while (1) {
      err = sqlite3_step(stmt);

      if (err == SQLITE_ROW) {
        NSMutableArray *line = [NSMutableArray array];
        int count = sqlite3_data_count(stmt);

        // we use "<= count" because sqlite sends also 
        // the id of the entry with type = 0 
        for (i = 0; i <= count; i++) { 
          int type = sqlite3_column_type(stmt, i);
                    
          if (type == SQLITE_INTEGER) {
            [line addObject: [NSNumber numberWithInt: sqlite3_column_int(stmt, i)]];
          
          } else if (type == SQLITE_FLOAT) {
            [line addObject: [NSNumber numberWithDouble: sqlite3_column_double(stmt, i)]];
          
          } else if (type == SQLITE_TEXT) {
            [line addObject: [NSString stringWithUTF8String: (const char *)sqlite3_column_text(stmt, i)]];
          
          } else if (type == SQLITE_BLOB) {
            const char *bytes = sqlite3_column_blob(stmt, i);
            int length = sqlite3_column_bytes(stmt, i); 

            [line addObject: [NSData dataWithBytes: bytes length: length]];
          }
        }

        [reslines addObject: line];

        if ([reslines count] == MAX_RES) {
          GWDebugLog(@"SENDING");

          if ([self sendResults: reslines forQueryWithNumber: queryNumber]) {
            GWDebugLog(@"SENT");
            [reslines removeAllObjects];
          } else {
            GWDebugLog(@"INVALID!");
            break;
          }
        }

      } else {
        if (err == SQLITE_DONE) {
          GWDebugLog(@"SENDING (last)");

          if ([self sendResults: reslines forQueryWithNumber: queryNumber]) {
            GWDebugLog(@"SENT");
          } else {
            GWDebugLog(@"INVALID!");
          }

          break;

        } else if (err == SQLITE_BUSY) {
          CREATE_AUTORELEASE_POOL(arp); 
          NSDate *when = [NSDate dateWithTimeIntervalSinceNow: 0.1];

          [NSThread sleepUntilDate: when];
          GWDebugLog(@"retry %i", retry);
          RELEASE (arp);

          if (retry++ > MAX_RETRY) {
            NSLog(@"%s", sqlite3_errmsg(db));
		        break;
          }

        } else {
          NSLog(@"%i %s", err, sqlite3_errmsg(db));
          break;
        }
      }
    }
  
    sqlite3_finalize(stmt);
    
  } else {
    NSLog(@"%s", sqlite3_errmsg(db));
  }
  
  if (postqueries) {
    [self performPostQueries: postqueries];
  }
  
  [self endOfQueryWithNumber: queryNumber];
  
  RELEASE (pool);
}

- (BOOL)sendResults:(NSArray *)lines
           forQueryWithNumber:(NSNumber *)qnum
{
  CREATE_AUTORELEASE_POOL(arp); 
  id client = [clientInfo objectForKey: @"client"];
  NSDictionary *results;
  BOOL accepted;
  
  results = [NSDictionary dictionaryWithObjectsAndKeys: qnum, @"qnumber",
                                                        lines, @"lines", nil];  
  accepted = [client queryResults: [NSArchiver archivedDataWithRootObject: results]];    
  RELEASE (arp);
  
  return accepted;
}

- (void)endOfQueryWithNumber:(NSNumber *)qnum
{
  [[clientInfo objectForKey: @"client"] endOfQueryWithNumber: qnum];
}

- (BOOL)opendb
{
  if (db == NULL) {
    BOOL newdb = ([fm fileExistsAtPath: dbpath] == NO);
    char *err;
        
    db = opendbAtPath(dbpath);
        
    if (db != NULL) {
      if (newdb) {
        if (sqlite3_exec(db, [db_schema UTF8String], NULL, 0, &err) != SQLITE_OK) {
          NSLog(@"unable to create the database at %@", dbpath);
          sqlite3_free(err); 
          return NO;    
        } else {
          GWDebugLog(@"contents database created");
        }
      }
    } else {
      NSLog(@"unable to open the database at %@", dbpath);
      return NO;
    }    
    
    sqlite3_create_function(db, "pathExists", 1, 
                                SQLITE_UTF8, 0, path_exists, 0, 0);                                
    sqlite3_create_function(db, "pathMoved", 3, 
                                SQLITE_UTF8, 0, path_moved, 0, 0);
    sqlite3_create_function(db, "timeStamp", 0, 
                                SQLITE_UTF8, 0, time_stamp, 0, 0);
    sqlite3_create_function(db, "containsSubstr", 2, 
                                SQLITE_UTF8, 0, contains_substr, 0, 0);                                
    sqlite3_create_function(db, "appendString", 2, 
                                SQLITE_UTF8, 0, append_string, 0, 0);
    sqlite3_create_function(db, "wordScore", 4, 
                                SQLITE_UTF8, 0, word_score, 0, 0);
    sqlite3_create_function(db, "attributeScore", 5, 
                                SQLITE_UTF8, 0, attribute_score, 0, 0);

    performWriteQuery(db, @"PRAGMA cache_size = 20000");
    performWriteQuery(db, @"PRAGMA count_changes = 0");
    performWriteQuery(db, @"PRAGMA synchronous = OFF");
    performWriteQuery(db, @"PRAGMA temp_store = MEMORY");
  }

  /* only to avoid a compiler warning */
  if (0) {
    NSLog(@"%@", db_schema_tmp);
    NSLog(@"%@", user_db_schema);
    NSLog(@"%@", user_db_schema_tmp);
  }

  return YES;
}

- (void)touchTables:(id)sender
{
  if ([self isBaseServer]) {
    CREATE_AUTORELEASE_POOL(pool);   
    const char *query = [[touchQueries objectAtIndex: touchind] UTF8String];
    NSDate *date = [NSDate date];
    char *err;

    GWPrintfDebugLog("executing: \"%s\" ... ", query);

    if (sqlite3_exec(db, query, NULL, 0, &err) != SQLITE_OK) {
      NSLog(@"error at %s", query);

      if (err != NULL) {
        NSLog(@"%s", err);
        sqlite3_free(err); 
      }
    } else {
      GWPrintfDebugLog("done. (%.2f sec.)\n", [[NSDate date] timeIntervalSinceDate: date]);
    }

    touchind++;

    if (touchind == [touchQueries count]) {
      touchind = 0;
    }

    RELEASE (pool);
  }
}

- (BOOL)isBaseServer
{
  return ([clientInfo objectForKey: @"client"] == nil);
}

- (void)terminate
{
  NSConnection *connection = [clientInfo objectForKey: @"connection"];
  
  if (connection) {
    [nc removeObserver: self
		              name: NSConnectionDidDieNotification
		            object: connection];
  }

  RELEASE (clientInfo);
  
  if (db != NULL) {
    sqlite3_close(db);
  }
  
  NSLog(@"exiting");
  
  exit(EXIT_SUCCESS);
}

@end


int main(int argc, char** argv)
{
  CREATE_AUTORELEASE_POOL(pool);
  NSProcessInfo *info = [NSProcessInfo processInfo];
  NSMutableArray *args = AUTORELEASE ([[info arguments] mutableCopy]);

  BOOL subtask = YES;

  if ([args containsObject: @"--daemon"])
    subtask = NO;

  if (subtask)
    {
      NSTask *task = [NSTask new];
    
      NS_DURING
        {
	  [args removeObjectAtIndex: 0];
          [args addObject: @"--daemon"];
          [task setLaunchPath: [[NSBundle mainBundle] executablePath]];
          [task setArguments: args];
          [task setEnvironment: [info environment]];
          [task launch];
          DESTROY (task);
        }
      NS_HANDLER
        {
          fprintf (stderr, "unable to launch the gmds task. exiting.\n");
          DESTROY (task);
        }
      NS_ENDHANDLER

        exit(EXIT_FAILURE);
    }
    
  RELEASE(pool);

  {
    CREATE_AUTORELEASE_POOL (pool);
    GMDS *gmds = [[GMDS alloc] init];
    RELEASE (pool);
  
    if (gmds != nil)
      {
        CREATE_AUTORELEASE_POOL (pool);
        [[NSRunLoop currentRunLoop] run];
        RELEASE (pool);
      }
  }
    
  exit(EXIT_SUCCESS);
}