File: data.c

package info (click to toggle)
dancer-services 1.8.0.6.3-4
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 2,600 kB
  • ctags: 1,623
  • sloc: ansic: 34,690; sh: 2,850; makefile: 269
file content (1295 lines) | stat: -rw-r--r-- 27,713 bytes parent folder | download | duplicates (4)
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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
/*
 * HybServ TS Services, Copyright (C) 1998-1999 Patrick Alken
 * This program comes with absolutely NO WARRANTY
 *
 * Should you choose to use and/or modify this source code, please
 * do so under the terms of the GNU General Public License under which
 * this program is distributed.
 *
 * $Id: data.c,v 1.3 2001/11/12 09:50:55 asuffield Exp $
 */

#include "defs.h"

#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#ifdef TIME_WITH_SYS_TIME
#include <sys/time.h>
#endif

#include "alloc.h"
#include "channel.h"
#include "chanserv.h"
#include "client.h"
#include "conf.h"
#include "config.h"
#include "data.h"
#include "hybdefs.h"
#include "log.h"
#include "match.h"
#include "memoserv.h"
#include "nickserv.h"
#include "settings.h"
#include "seenserv.h"
#include "misc.h"
#include "sprintf_irc.h"

static int CopyFile(char *oldfile, char *newfile);

/*
ReloadData()
  Reload nick/chan/memo/stat/oper databases
*/

int
ReloadData()

{
#ifdef NICKSERVICES
  struct NickInfo *temp, *newnick, *nnext;
  int ii;

#ifdef CHANNELSERVICES
  struct ChanInfo *ctemp, *cnext;
#endif

#ifdef MEMOSERVICES
  struct MemoInfo *mtemp, *mnext;
#endif

#endif /* NICKSERVICES */

#ifdef NICKSERVICES

  for (ii = 0; ii < NICKLIST_MAX; ++ii)
    for (temp = nicklist[ii]; temp; temp = temp->next)
      temp->flags |= NS_DELETE;

  if (ns_loaddata() == (-2))
  {
    /*
     * Reload had fatal errors, so use the old database -
     * go through and KEEP all structures marked for deletion
     * and DELETE structures not marked, because they are the
     * ones that were just added in the failed reload
     */

    for (ii = 0; ii < NICKLIST_MAX; ++ii)
    {
      for (temp = nicklist[ii]; temp; temp = nnext)
      {
        nnext = temp->next;

        if (!(temp->flags & NS_DELETE))
          DeleteNick(temp);
        else
        {
          /* remove the deletion flag */
          temp->flags &= ~NS_DELETE;
        }
      }
    }

    return 0;
  }
  else
  {
    /*
     * Reload was ok - now go through and remove the old nick
     * structures marked for deletion
     */

    for (ii = 0; ii < NICKLIST_MAX; ++ii)
    {
      for (temp = nicklist[ii]; temp; temp = nnext)
      {
        nnext = temp->next;

        if (temp->flags & NS_DELETE)
        {
          /*
           * We should try to preserve the old identification
           * data. Before deleting this nickname, attempt
           * to find the corresponding one that was just
           * read from the configuration file, and set it's
           * ident/collide/split_ts variables correctly.
           * It is safe to use FindNick() because it will
           * return the most current entry. If the entry
           * was deleted, FindNick() will return 'temp'
           * so we're still not losing anything.
           */
          if ((newnick = FindNick(temp->nick)))
          {
            newnick->flags |= (temp->flags & NS_IDENTIFIED);
            newnick->collide_ts = temp->collide_ts;

          #ifdef RECORD_SPLIT_TS
            newnick->split_ts = temp->split_ts;
            newnick->whensplit = temp->whensplit;
          #endif /* RECORD_SPLIT_TS */
          }

          DeleteNick(temp);

        } /* if (temp->flags & NS_DELETE) */
      } /* for (temp = nicklist[ii]; temp; temp = nnext) */
    } /* for (ii = 0; ii < NICKLIST_MAX; ++ii) */
  }

#ifdef CHANNELSERVICES

  for (ii = 0; ii < CHANLIST_MAX; ++ii)
    for (ctemp = chanlist[ii]; ctemp; ctemp = ctemp->next)
      ctemp->flags |= CS_DELETE;

  if (cs_loaddata() == (-2))
  {
    /*
     * Reload had fatal errors, so use the old database -
     * go through and KEEP all structures marked for deletion
     * and DELETE structures not marked, because they are the
     * ones that were just added in the failed reload
     */

    for (ii = 0; ii < CHANLIST_MAX; ++ii)
    {
      for (ctemp = chanlist[ii]; ctemp; ctemp = cnext)
      {
        cnext = ctemp->next;

        if (!(ctemp->flags & CS_DELETE))
          DeleteChan(ctemp);
        else
        {
          /* remove the deletion flag */
          ctemp->flags &= ~CS_DELETE;
        }
      }
    }

    return 0;
  }
  else
  {
    struct Channel *cptr;

    /*
     * Reload was ok - now go through and remove the old chan
     * structures marked for deletion
     */

    for (ii = 0; ii < CHANLIST_MAX; ++ii)
    {
      for (ctemp = chanlist[ii]; ctemp; ctemp = cnext)
      {
        cnext = ctemp->next;

        if (ctemp->flags & CS_DELETE)
          DeleteChan(ctemp);
        else
        {
          /*
           * It must be a new channel entry, have ChanServ
           * join the channel
           */
          if (!(ctemp->flags & CS_FORGET))
          {
            cptr = FindChannel(ctemp->name);
            if (cptr && !IsChannelMember(cptr, Me.csptr))
              cs_join(ctemp);
          }
        }
      }
    }
    
    /*
     * Now go through the list and have ChanServ part any old chans
     */
    if (Me.csptr)
    {
      struct UserChannel *uc, *ucprev;

      ucprev = NULL;
      for (uc = Me.csptr->firstchan; uc; )
      {
        if (!FindChan(uc->chptr->name))
        {
          if (ucprev)
          {
            ucprev->next = uc->next;
            cs_part(uc->chptr);
            uc = ucprev;
          }
          else
          {
            Me.csptr->firstchan = uc->next;
            cs_part(uc->chptr);
            uc = NULL;
          }
        }

        ucprev = uc;

        if (uc)
          uc = uc->next;
        else
          uc = Me.csptr->firstchan;
      }
    }
  } /* if (Me.csptr) */

#endif /* CHANNELSERVICES */

#ifdef MEMOSERVICES

  for (ii = 0; ii < MEMOLIST_MAX; ++ii)
    for (mtemp = memolist[ii]; mtemp; mtemp = mtemp->next)
      mtemp->flags |= MS_RDELETE;

  if (ms_loaddata() == (-2))
  {
    /*
     * Reload had fatal errors, so use the old database -
     * go through and KEEP all structures marked for deletion
     * and DELETE structures not marked, because they are the
     * ones that were just added in the failed reload
     */

    for (ii = 0; ii < MEMOLIST_MAX; ++ii)
    {
      for (mtemp = memolist[ii]; mtemp; mtemp = mnext)
      {
        mnext = mtemp->next;

        if (!(mtemp->flags & MS_RDELETE))
          DeleteMemoList(mtemp);
        else
        {
          /* remove the deletion flag */
          mtemp->flags &= ~MS_RDELETE;
        }
      }
    }

    return 0;
  }
  else
  {
    /*
     * Reload was ok - now go through and remove the old memo
     * structures marked for deletion
     */

    for (ii = 0; ii < MEMOLIST_MAX; ++ii)
    {
      for (mtemp = memolist[ii]; mtemp; mtemp = mnext)
      {
        mnext = mtemp->next;

        if (mtemp->flags & MS_RDELETE)
          DeleteMemoList(mtemp);
      }
    }
  }

#endif /* MEMOSERVICES */

#endif /* NICKSERVICES */

#ifdef STATSERVICES

  if (ss_loaddata() == (-2))
    return 0;

#endif /* STATSERVICES */

#ifdef SEENSERVICES

  if (es_loaddata() == (-2))
    return 0;

#endif /* SEENSERVICES */

  if (os_loaddata() == (-2))
    return 0;

  return 1;
} /* ReloadData() */

/*
CreateDatabase()
  Open file 'name' and return a pointer to it
*/

FILE *
CreateDatabase(char *name, char *info)

{
  FILE *fptr;
  time_t currtime;

  if ((fptr = fopen(name, "w")) == NULL)
    return (NULL);

  /* change the mode to -rw------- */
  chmod(name, 0600);

  currtime = current_ts;
  fprintf(fptr, "; dancer-services %s - %s - created %s",
    hVersion,
    info,
    ctime(&currtime));

  return (fptr);
} /* CreateDatabase() */

/*
BackupDatabases()
 Called from DoTimer() to backup the previous days'
database files. Use a directory structure like:
   backup/YYYYMMDD/database
so we can tell exactly what day the files were backed up.
*/

void
BackupDatabases(time_t unixtime)

{
  struct tm *backup_tm;
  char bpath[MAXLINE],
       temp[MAXLINE];

  /*
   * First make sure HPath/backup/ exists
   * Notice that %s/backup/something has to be under 512 characters. -kre
   */
  ircsprintf(bpath, "%s/backup", HPath);
  /* Function mkdir() returns -1 on failure -kre */
  if (mkdir(bpath, 0700)==-1)
  {
    /* Proceed if errno is set. This usually should not be necessary, but
     * this code should help me find why Solaris complains -kre */
    if (errno && errno!=EEXIST)
    {
      putlog(LOG1,
        "Error creating backup directory [%s]: %s",
        bpath,
        strerror(errno));
      return;
    }
  }

  backup_tm = localtime(&unixtime);

  ircsprintf(bpath, "%s/backup/%d%02d%02d", HPath, 1900 +
      backup_tm->tm_year, backup_tm->tm_mon + 1, backup_tm->tm_mday);

  /*
   * Make the directory permissions: drwx------
   * Function mkdir() returns -1 on failure -kre
   */
  if (mkdir(bpath, 0700)==-1)
  {
    /* Proceed if errno is set. This usually should not be necessary, but
     * this code should help me find why Solaris complains -kre */
    if (errno && errno!=EEXIST)
    {
      putlog(LOG1,
        "Error creating backup directory [%s]: %s",
        bpath,
        strerror(errno));
      return;
    }
  }

  ircsprintf(temp, "%s/%s", bpath, OperServDB);

  CopyFile(OperServDB, temp);

#ifdef STATSERVICES

  ircsprintf(temp, "%s/%s", bpath, StatServDB);

  CopyFile(StatServDB, temp);

#endif /* STATSERVICES */

#ifdef NICKSERVICES

  ircsprintf(temp, "%s/%s", bpath, NickServDB);

  CopyFile(NickServDB, temp);

#ifdef CHANNELSERVICES
  ircsprintf(temp, "%s/%s", bpath, ChanServDB);

  CopyFile(ChanServDB, temp);
#endif /* CHANNELSERVICES */

#ifdef MEMOSERVICES
  ircsprintf(temp, "%s/%s", bpath, MemoServDB);

  CopyFile(MemoServDB, temp);
#endif /* MEMOSERVICES */

/* SeenServDB should be backed up too. -kre */
#ifdef SEENSERVICES
  ircsprintf(temp, "%s/%s", bpath, SeenServDB);

  CopyFile(SeenServDB, temp);
#endif

#endif /* NICKSERVICES */
} /* BackupDatabases() */

/*
WriteDatabases()
 Rewrite all databases

Return: 1 if successful
        0 if not
*/

int
WriteDatabases()

{

  if (!WriteOpers())
    return (0);

#ifdef STATSERVICES

  if (!WriteStats())
    return (0);

#endif /* STATSERVICES */

#ifdef SEENSERVICES

  if (!WriteSeen())
    return (0);

#endif /* SEENSERVICES */

#ifdef NICKSERVICES

  if (!WriteNicks())
    return (0);

#ifdef CHANNELSERVICES

  if (!WriteChans())
    return (0);

#endif /* CHANNELSERVICES */

#ifdef MEMOSERVICES

  if (!WriteMemos())
    return (0);

#endif /* MEMOSERVICES */

#endif /* NICKSERVICES */

  return (1);
} /* WriteDatabases() */

/*
WriteOpers()
  Write OperServDB to disk - just record opers' nicknames and
what umodes they have

Format:   Nickname <umodes>

 Return 1 if successful, 0 if not
*/

int
WriteOpers()

{
  FILE *fp;
  char tempname[MAXLINE];
  struct Userlist *tempuser;
  char *donestr; /* list of nicks we wrote */
  char temp[MAXLINE];

  ircsprintf(tempname, "%s.tmp", OperServDB);
  fp = CreateDatabase(tempname, "OperServ Database");
  if (!fp)
  {
    putlog(LOG1, "Error writing OperServ Database (%s): %s",
      OperServDB,
      strerror(errno));
    return 0;
  }

  /*
   * The problem here is some O: lines may be for the same
   * nickname, so we need to keep track to make sure we don't
   * write the same nickname twice.  It doesn't matter which
   * Userlist structure we write for each nickname, because
   * all structures for the same nickname will have the
   * exact same value for "umodes", which os_loaddata()
   * or o_umode() did already.
   * Check to make sure the nick we're about to write
   * is not already in 'donestr' - if not, write it
   * and cat it to donestr.
   */
  donestr = (char *) MyMalloc(sizeof(char));
  *donestr = '\0';
  for (tempuser = UserList; tempuser; tempuser = tempuser->next)
  {
    ircsprintf(temp, "*%s*", tempuser->nick);
    if (match(temp, donestr) == 0)
    {
      fprintf(fp, "%s %ld\n", tempuser->nick, tempuser->umodes);
      ircsprintf(temp, "%s ", tempuser->nick);
      donestr = (char *) MyRealloc(donestr, strlen(donestr) + strlen(temp)
          + 1);
      strcat(donestr, temp);
    }
  }

  MyFree(donestr);

  fclose(fp);

  rename(tempname, OperServDB);

  putlog(LOG3, "Wrote %s",
    OperServDB);

  return 1;
} /* WriteOpers() */

#ifdef STATSERVICES

/*
WriteStats()
  Write out StatServ statistics for max users/chans etc to
StatServDB
*/

int
WriteStats()

{
  FILE *fp;
  char tempname[MAXLINE];

  ircsprintf(tempname, "%s.tmp", StatServDB);
  fp = CreateDatabase(tempname, "StatServ Database");
  if (!fp)
  {
    putlog(LOG1, "Error writing StatServ Database (%s): %s",
      StatServDB,
      strerror(errno));
    return 0;
  }

  fprintf(fp, "->USERS %ld %ld\n",
    Network->MaxUsers,
    (long) Network->MaxUsers_ts);

  fprintf(fp, "->OPERS %ld %ld\n",
    Network->MaxOperators,
    (long) Network->MaxOperators_ts);

  fprintf(fp, "->CHANS %ld %ld\n",
    Network->MaxChannels,
    (long) Network->MaxChannels_ts);

  fprintf(fp, "->SERVS %ld %ld\n",
    Network->MaxServers,
    (long) Network->MaxServers_ts);

  fclose(fp);

  rename(tempname, StatServDB);

  putlog(LOG3, "Wrote %s",
    StatServDB);

  return 1;
} /* WriteStats() */

#endif /* STATSERVICES */

#ifdef NICKSERVICES

/*
WriteNicks()
 Write all nickname entries to NickServDB
*/

int
WriteNicks()

{
  FILE *fp;
  char tempname[MAXLINE];
  int ii, ncnt;
  struct NickInfo *nptr;
  struct NickHost *hptr;
  int islinked;

  ircsprintf(tempname, "%s.tmp", NickServDB);
  fp = CreateDatabase(tempname, "NickServ Database");
  if (!fp)
  {
    putlog(LOG1, "Error writing NickServ Database (%s): %s",
      NickServDB,
      strerror(errno));
    return 0;
  }

  ncnt = 0;

#ifdef LINKED_NICKNAMES

  /*
   * We have to go through the nicklist to write out all master entries
   * first, because the leaf entries will have a ->LINK <master nick>, so
   * the next time the database is read, we have to make sure we can find
   * the master nickname entry or we've got problems :-). Basically, make
   * sure the leaf entries don't get written out before master entries.
   * Unfortunately, we have to repeat some code here.
   */

  for (ii = 0; ii < NICKLIST_MAX; ++ii)
  {
    for (nptr = nicklist[ii]; nptr; nptr = nptr->next)
    {
      if (nptr->master || !nptr->nextlink)
      {
        /* This is not a master nickname */
        continue;
      }

      ++ncnt;

      /* write out "nickname flags created last-seen" to file */
      fprintf(fp, "%s %ld %ld %ld\n",
        nptr->nick,
        nptr->flags,
        (long) nptr->created,
        (long) nptr->lastseen);

      /* write out password only if not forbidden! -kre */
      if (nptr->password)
        fprintf(fp, "->PASS %s\n", nptr->password);

      if (nptr->email)
        fprintf(fp, "->EMAIL %s\n", nptr->email);

      if (nptr->url)
        fprintf(fp, "->URL %s\n", nptr->url);

      if (nptr->gsm)
        fprintf(fp, "->GSM %s\n", nptr->gsm);

      if (nptr->phone)
        fprintf(fp, "->PHONE %s\n", nptr->phone);

      if (nptr->UIN)
        fprintf(fp, "->UIN %s\n", nptr->UIN);

      if (LastSeenInfo)
      {
        if (nptr->lastu && nptr->lasth)
          fprintf(fp, "->LASTUH %s %s\n", nptr->lastu,
            nptr->lasth);

        if (nptr->lastqmsg)
          fprintf(fp, "->LASTQMSG :%s\n", nptr->lastqmsg);
      }

      for (hptr = nptr->hosts; hptr; hptr = hptr->next)
        fprintf(fp, "->HOST %s\n", hptr->hostmask);

    } /* for (nptr = nicklist[ii]; nptr; nptr = nptr->next) */
  } /* for (ii = 0; ii < NICKLIST_MAX; ++ii) */

#endif /* LINKED_NICKNAMES */

  /*
   * Now go through and write out all non-master nickname
   * entries
   */

  for (ii = 0; ii < NICKLIST_MAX; ++ii)
  {
    for (nptr = nicklist[ii]; nptr; nptr = nptr->next)
    {
      islinked = 0;

    #ifdef LINKED_NICKNAMES
      if (nptr->master)
        islinked = 1;
      else
      {
        /*
         * If nptr->master is NULL, but nptr->nextlink is not,
         * this is a master nickname, which was already written,
         * continue the loop
         */
        if (nptr->nextlink)
          continue;
      }
    #endif /* LINKED_NICKNAMES */

      ++ncnt;

      /* write out "nickname flags created last-seen" to file */
      fprintf(fp, "%s %ld %ld %ld\n",
        nptr->nick, nptr->flags, (long) nptr->created, (long)
        nptr->lastseen);

      if (nptr->password)
        fprintf(fp, "->PASS %s\n", nptr->password);

      if (nptr->email)
        fprintf(fp, "->EMAIL %s\n", nptr->email);

      if (nptr->url)
        fprintf(fp, "->URL %s\n", nptr->url);

      if (nptr->gsm)
        fprintf(fp, "->GSM %s\n", nptr->gsm);

      if (nptr->phone)
        fprintf(fp, "->PHONE %s\n", nptr->phone);

      if (nptr->UIN)
        fprintf(fp, "->UIN %s\n", nptr->UIN);

      if (LastSeenInfo)
      {
        if (nptr->lastu && nptr->lasth)
          fprintf(fp, "->LASTUH %s %s\n",
            nptr->lastu,
            nptr->lasth);

        if (nptr->lastqmsg)
          fprintf(fp, "->LASTQMSG :%s\n",
            nptr->lastqmsg);
      }

      if (!islinked)
      {
        /*
         * write out hostmasks only if this nickname is
         * not linked - if it is, the master nickname
         * (previously written) has the access list
         */

        for (hptr = nptr->hosts; hptr; hptr = hptr->next)
          fprintf(fp, "->HOST %s\n",
            hptr->hostmask);
      }

    #ifdef LINKED_NICKNAMES

#if 0
      assert(nptr != nptr->master);
#endif
      /* Quickfix. Seems unlink is broken atm. But, there is no need to
       * die here since master was not written because of
       * nptr->nextlink. Huh. Should fix link copying routines -kre */
      if ((nptr != nptr->master) && nptr->master)
        fprintf(fp, "->LINK %s\n",
          nptr->master->nick);

    #endif /* LINKED_NICKNAMES */
    } /* for (nptr = nicklist[ii]; nptr; nptr = nptr->next) */
  } /* for (ii = 0; ii < NICKLIST_MAX; ++ii) */

  fclose(fp);

  rename(tempname, NickServDB);

  putlog(LOG3, "Wrote %s (%d registered nicknames)",
    NickServDB, ncnt);

  return (1);
} /* WriteNicks() */

#ifdef CHANNELSERVICES

/*
WriteChans()
 Write out all channel entries to ChanServDB
*/

int
WriteChans()

{
  FILE *fp;
  char tempname[MAXLINE];
  struct ChanInfo *cptr, *cnext;
  int ii,
      ccnt;

  ircsprintf(tempname, "%s.tmp", ChanServDB);
  fp = CreateDatabase(tempname, "ChanServ Database");
  if (!fp)
  {
    putlog(LOG1, "Error writing ChanServ Database (%s): %s",
      ChanServDB,
      strerror(errno));
    return 0;
  }

  ccnt = 0;

  for (ii = 0; ii < CHANLIST_MAX; ++ii)
  {
    for (cptr = chanlist[ii]; cptr; cptr = cnext)
    {
      cnext = cptr->next;

      if (!GetLink(cptr->founder) &&
          !(cptr->flags & CS_FORGET))
      {
        /*
         * There is no founder - check if there is a successor.
         * If so, promote them to founder, otherwise delete the
         * channel.
         */
        if (cptr->successor && GetLink(cptr->successor))
        {
          /*
           * There is a valid successor - promote them to founder
           */
          PromoteSuccessor(cptr);
        }
        else
        {
          putlog(LOG2,
            "%s: dropping channel [%s] (no founder)",
            n_ChanServ,
            cptr->name);

          DeleteChan(cptr);

          continue;
        }
      }

      if (cptr->successor)
      {
        if (!GetLink(cptr->successor))
        {
          /* successor's nickname has expired - erase it */
          putlog(LOG2,
            "%s: Successor [%s] for channel [%s] expired, removing",
            n_ChanServ,
            cptr->successor,
            cptr->name);

          MyFree(cptr->successor);
          cptr->successor = NULL;
        }
      }

      ++ccnt;

      /*
       * format: channel-name flags ts_created ts_lastused
       */
      fprintf(fp, "%s %ld %ld %ld\n",
	      cptr->name,
	      cptr->flags,
	      (long) cptr->created,
	      (long) cptr->lastused);

      if (!(cptr->flags & CS_FORGET))
      {
        struct ChanAccess *ca;
        struct AutoKick *ak;
        int jj;

        /* write founder */
        fprintf(fp, "->FNDR %s %ld\n",
		cptr->founder,
		(long) cptr->last_founder_active);

        /* write password */
        fprintf(fp, "->PASS %s\n",
          cptr->password);

        if (cptr->successor)
          fprintf(fp, "->SUCCESSOR %s %ld\n",
		  cptr->successor,
		  (long) cptr->last_successor_active);

        if (cptr->topic)
          fprintf(fp, "->TOPIC :%s\n",
            cptr->topic);

        if (cptr->limit)
          fprintf(fp, "->LIMIT %ld\n",
            cptr->limit);

        if (cptr->key)
          fprintf(fp, "->KEY %s\n",
            cptr->key);

        if (cptr->forward)
          fprintf(fp, "->FORWARD %s\n",
            cptr->forward);

        if (cptr->modes_on)
          fprintf(fp, "->MON %d\n",
            cptr->modes_on);

        if (cptr->modes_off)
          fprintf(fp, "->MOFF %d\n",
            cptr->modes_off);

        if (cptr->entrymsg)
          fprintf(fp, "->ENTRYMSG :%s\n",
            cptr->entrymsg);

        if (cptr->email)
          fprintf(fp, "->EMAIL %s\n",
            cptr->email);

        if (cptr->url)
          fprintf(fp, "->URL %s\n",
            cptr->url);

        fprintf(fp, "->ALVL");
        for (jj = 0; jj <= CA_FOUNDER; ++jj)
          fprintf(fp, " %d",
            cptr->access_lvl[jj]);
        fprintf(fp, "\n");

        for (ca = cptr->access; ca; ca = ca->next)
          fprintf(fp, "->ACCESS %s %d %ld %ld\n",
		  ca->nptr ? ca->nptr->nick : stripctrlsymbols(ca->hostmask),
		  ca->level,
		  (long) ca->created, (long) ca->last_used);

        for (ak = cptr->akick; ak; ak = ak->next)
          fprintf(fp, "->AKICK %s :%s\n",
            stripctrlsymbols(ak->hostmask),
            ak->reason ? stripctrlsymbols(ak->reason) : "");
      } /* if (!(cptr->flags & CS_FORGET)) */
    } /* for (cptr = chanlist[ii]; cptr; cptr = cnext) */
  } /* for (ii = 0; ii < CHANLIST_MAX; ++ii) */

  fclose(fp);

  rename(tempname, ChanServDB);

  putlog(LOG3, "Wrote %s (%d registered channels)",
    ChanServDB,
    ccnt);

  return (1);
} /* WriteChans() */

#endif /* CHANNELSERVICES */

#ifdef MEMOSERVICES

/*
WriteMemos()
 Write memo entries to MemoServDB
*/

int
WriteMemos()

{
  FILE *fp;
  char tempname[MAXLINE];
  int ii,
      mcnt;
  struct MemoInfo *mi;
  struct Memo *memoptr;

  ircsprintf(tempname, "%s.tmp", MemoServDB);
  fp = CreateDatabase(tempname, "MemoServ Database");
  if (!fp)
  {
    putlog(LOG1, "Error writing MemoServ Database (%s): %s",
      MemoServDB,
      strerror(errno));
    return 0;
  }

  mcnt = 0;

  for (ii = 0; ii < MEMOLIST_MAX; ++ii)
  {
    for (mi = memolist[ii]; mi; mi = mi->next)
    {
      ++mcnt;

      /* write out "target" to file */
      fprintf(fp, "%s\n",
        mi->name);

      for (memoptr = mi->memos; memoptr; memoptr = memoptr->next)
      {
        /* write out "sender ts-sent flags :text" to file */
        if (!(memoptr->flags & MS_DELETE))
          fprintf(fp, "->TEXT %s %ld %ld :%s\n",
            memoptr->sender,
            (long) memoptr->sent,
            memoptr->flags,
            memoptr->text);
      }
    } /* for (mi = memolist[ii]; mi; mi = mi->next) */
  } /* for (ii = 0; ii < MEMOLIST_MAX; ++ii) */

  fclose(fp);

  rename(tempname, MemoServDB);

  putlog(LOG3, "Wrote %s (%d memo entries)",
    MemoServDB,
    mcnt);

  return (1);
} /* WriteMemos() */

#endif /* MEMOSERVICES */

#endif /* NICKSERVICES */

/*
LoadData()
  Load databases
*/

void
LoadData()

{
  /* load OperServ database */
  if (os_loaddata() == (-2))
  {
    fprintf(stderr, "Fatal errors parsing database (%s)\n",
      OperServDB);
    putlog(LOG1, "Fatal errors parsing database (%s)",
      OperServDB);
    exit(1);
  }

#ifdef SEENSERVICES
  /* load SeenServ database */
  if (es_loaddata() == (-2))
  {
    fprintf(stderr, "Fatal errors parsing database (%s)\n",
      SeenServDB);
    putlog(LOG1, "Fatal errors parsing database (%s)",
      SeenServDB);
    exit(1);
  }
#endif /* SEENSERVICES */

#ifdef NICKSERVICES
  /* load NickServ database */
  if (ns_loaddata() == (-2))
  {
    fprintf(stderr, "Fatal errors parsing database (%s)\n",
      NickServDB);
    putlog(LOG1, "Fatal errors parsing database (%s)",
      NickServDB);
    exit(1);
  }

  #ifdef CHANNELSERVICES
    /* load ChanServ database */
    if (cs_loaddata() == (-2))
    {
      fprintf(stderr, "Fatal errors parsing database (%s)\n",
        ChanServDB);
      putlog(LOG1, "Fatal errors parsing database (%s)",
        ChanServDB);
      exit(1);
    }
  #endif

  #ifdef MEMOSERVICES
    /* load MemoServ database */
    if (ms_loaddata() == (-2))
    {
      fprintf(stderr, "Fatal errors parsing database (%s)\n",
        MemoServDB);
      putlog(LOG1, "Fatal errors parsing database (%s)",
        MemoServDB);
      exit(1);
    }
  #endif

#endif /* NICKSERVICES */

#ifdef STATSERVICES
  /* load StatServ database */
  if (ss_loaddata() == (-2))
  {
    fprintf(stderr, "Fatal errors parsing database (%s)\n",
      StatServDB);
    putlog(LOG1, "Fatal errors parsing database (%s)",
      StatServDB);
    exit(1);
  }
#endif /* STATSERVICES */

#ifdef NICKSERVICES

  putlog(LOG1, 
  "Databases loaded (%d registered nicknames, %d registered channels, %d memo entries)",
    Network->TotalNicks,

  #ifdef CHANNELSERVICES

    Network->TotalChans,

  #else

    0,

  #endif

  #ifdef MEMOSERVICES

    Network->TotalMemos);

  #else

    0);

  #endif

#endif /* NICKSERVICES */
} /* LoadData() */

/*
CopyFile()
 Copy 'oldfile' to 'newfile'
Return:
  0  - successful copy
  -1 - cannot open old file
  -2 - cannot open new file
  -3 - old file isn't normal
  -4 - ran out of disk space
*/

static int
CopyFile(char *oldfile, char *newfile)

{
  int oldfd,
      newfd;
  struct stat fst;
  char buffer[MAXLINE];
  int bytes;

  if ((oldfd = open(oldfile, O_RDONLY, 0)) < 0)
    return (-1);

  fstat(oldfd, &fst);
  if (!(fst.st_mode & S_IFREG))
    return (-3);

  if ((newfd = creat(newfile, (int) (fst.st_mode & 0700))) < 0)
  {
    close(oldfd);
    return (-2);
  }

  /*
   * Now start copying
   */
  for (bytes = 1; bytes > 0; )
  {
    bytes = read(oldfd, buffer, sizeof(buffer));
    if (bytes > 0)
    {
      if (write(newfd, buffer, bytes) < bytes)
      {
        /* disk space is full */
        close(oldfd);
        close(newfd);
        unlink(newfile); /* delete the file we created */
        return (-4);
      }
    }
    /*
     * When bytes == 0 (EOF), we will drop out of the loop
     */
  }

  /* successful copy */
  close(oldfd);
  close(newfd);
  return (0);
} /* CopyFile() */

#ifdef SEENSERVICES

/*
WriteSeen()
  Write out SeenServ statistics for users quits/changing nicks to
SeenServDB
*/

int
WriteSeen()

{
  FILE *fp;
  char tempname[MAXLINE];
  aSeen *seen;

  ircsprintf(tempname, "%s.tmp", SeenServDB);
  fp = CreateDatabase(tempname, "SeenServ Database");
  if (!fp)
  {
    putlog(LOG1, "Error writing SeenServ Database (%s): %s",
      SeenServDB,
      strerror(errno));
    return 0;
  }

  for (seen = seenb; seen; seen = seen->next) {
    if (seen) 
    switch(seen->type) {
      case 1:
         fprintf(fp, "->QUIT %s %s %ld :%s\n", seen->nick, seen->userhost, (long) seen->time, seen->msg);
         break;
      case 2:
         fprintf(fp, "->NICK %s %s %ld\n", seen->nick, seen->userhost, (long) seen->time);
         break;
      default:
         break;
    }
  }

  fclose(fp);

  rename(tempname, SeenServDB);

  putlog(LOG3, "Wrote %s",
    SeenServDB);

  return 1;

} /* WriteSeen() */

#endif /* SEENSERVICES */