Source

dlini / dlini_internal.c

  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
/*
 Daybo Logic INI Support Library for non-Windows systems
 Copyright (C) 2001-2005 Daybo Logic.
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
 3. Neither the name of the project nor the names of its contributors
    may be used to endorse or promote products derived from this software
    without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 SUCH DAMAGE.

  Daybo Logic,
  Flat 2 Barker Court,
  Victoria Avenue,
  Redfield,
  Bristol
  England.
  UK
  BS5 9NW

  +44 117 954 2306
  David Duncan Ross Palmer <http://www.daybologic.co.uk/mailddrp/>
  http://www.daybologic.co.uk/dev/dlini
*/

/*
   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
   % This module provides support to other INI functions only. %
   % The functions in here should not be used by users.        %
   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*/

#define DLINI_SOURCE

#ifdef __UNIX__
# include <sys/file.h>
# include <unistd.h>
#else /* Win32 or DOS */
# if ( defined(__BORLANDC__) || defined(__WATCOMC__) )
#   include <io.h>
#   include <fcntl.h>
#   include <share.h>
#   include <sys/stat.h>
#    include <sys\types.h>
# else
#   error
# endif
#endif /*__UNIX__*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stddef.h>
#include <limits.h>
#ifdef HDRSTOP
# pragma hdrstop
#endif /*HDRSTOP*/

#include "dlstdinc.h"
#include "dlini.h"
/*-------------------------------------------------------------------------*/
static enum dlini_bool_t SeekToKeysValue(
  FILE *FHandle
);

enum dlini_bool_t dlini_int_debugFlag = dliniFalse;
/*-------------------------------------------------------------------------*/
enum dlini_bool_t dlini_int_FindSection(
  const char *const FunctionName,
  FILE *FHandle,
  const char *SectionString
)
{
  char lineBuff[DLINI_LINEBUFFER];
  char* s;
  
  rewind(FHandle);
  do {
    s = fgets(lineBuff, sizeof(lineBuff)/sizeof(lineBuff[0]), FHandle);
    if ( s ) {
      dlini_int_ChopComment(s);
      dlini_int_ChopCrap(s);
      if ( dlini_int_stricmp(FunctionName, s, SectionString) == 0 )
        return dliniTrue;
    }
  } while ( s );
  rewind(FHandle);
  return dliniFalse;
}
/*-------------------------------------------------------------------------*/
enum dlini_bool_t dlini_int_FindFirstSection(
  FILE *FHandle
)
{
  if ( FHandle ) rewind(FHandle);
  return dlini_int_FindNextSection(FHandle);
}
/*-------------------------------------------------------------------------*/
enum dlini_bool_t dlini_int_FindNextSection(
  FILE *FHandle
)
{
  enum dlini_bool_t lastCharEOL = dliniFalse;
  int currentChar;

  if ( !FHandle ) return dliniFalse;

  do {
    currentChar = fgetc(FHandle);
    if ( lastCharEOL && currentChar == '[' )
      return dliniTrue;

    if ( currentChar == '\n' )
      lastCharEOL = dliniTrue;
  } while ( currentChar != EOF );
  return dliniFalse;
}
/*-------------------------------------------------------------------------*/
void dlini_int_GoToLine(
  FILE *FHandle,
  unsigned int LineNumber
)
{
  rewind(FHandle);
  while ( LineNumber ) {
    int byte = fgetc(FHandle);
    if ( byte == EOF ) break;
    if ( byte == '\n' ) LineNumber--;
  }
}
/*-------------------------------------------------------------------------*/
unsigned int dlini_int_GetKeyNames(
  FILE *FHandle,
  const char *SectionName,
  char *OutputBuffer,
  unsigned int BuffMaxChars
)
{
}
/*-------------------------------------------------------------------------*/
char *dlini_int_CreateResolvedSectionName(
  const char *SectionName
)
{
  char *ptr;
  size_t sz;

  sz = ( strlen(SectionName)+3 ) * sizeof(SectionName[0]);
  ptr = (char*)malloc( sz );
  if ( ptr ) {
    ptr[0] = '[';
    strcpy(ptr+1, SectionName);
    strcat(ptr, "]");
  }

  return ptr;
}
/*-------------------------------------------------------------------------*/
void dlini_int_DestroyResolvedSectionName(
  char *ResolvedSectionName
)
{
  if ( ResolvedSectionName )
    free(ResolvedSectionName);
}
/*-------------------------------------------------------------------------*/
FILE *dlini_int_Open(
  const char *Filename,
  enum dlini_bool_t Write
)
{
  /* This function is where I have to deal with locks.
  This makes this code pretty much a hack and not portable.
  I shall add new code for different ways of doing things as things
  break. */

  int fd;
  FILE *fsp = NULL;

# ifdef __UNIX__
    struct flock fl;

    fl.l_type = ( (Write==dliniTrue) ? (F_WRLCK) : (F_RDLCK) );
    fl.l_whence = SEEK_SET; /* Values below absolute */
    fl.l_start = 0; /* Lock section starts at top */
    fl.l_len = 0; /* Indicates entire file */
    fl.l_pid = getpid(); /* Identify process which owns the lock (us) */

    fd = open(Filename, ( (Write==dliniTrue) ? (O_RDWR) : (O_RDONLY) ));
    if ( fd != -1 ) { /* If no error */
      if ( fcntl(fd, F_SETLKW, &fl) == -1 ) {
        close(fd);
        fd = -1;
      }
    }
    else { /* -1 error on open */
      perror("INI open failed:");
      return NULL;
    }
# else /*__WIN32__*/
#   if ( defined(__BORLANDC__) || defined(__WATCOMC__) )
      fd = sopen(Filename, O_RDONLY, SH_DENYRW, S_IREAD); /* Fix this */
      if ( fd != -1 ) {
        if ( lock(fd, 0L, filelength(fd)) ) {
          /* Locking the file has failed */
          close(fd);
          fd = -1;
        }
      }
#   else
#     error ("No code for this compiler")
#   endif /*__BORLANDC__*/
# endif /*__UNIX__*/

  if ( fd != -1 ) { /* If no error */
    fsp = fdopen(fd, ( (Write==dliniTrue) ? ("r+t") : ("rt") ));
    if ( !fsp )
      close(fd);
  }

  return fsp;
}
/*-------------------------------------------------------------------------*/
void dlini_int_Close(
  FILE *FHandle
)
{
  if ( FHandle ) {
    /* I don't think I have to unlock the file in UNIX, just close the handle
    and I should be finished with it. */
#ifndef __UNIX__ /* Not UNIX */
# if ( defined(__BORLANDC__) || defined(__WATCOMC__) )
    int fd = fileno(FHandle);
    unlock(fd, 0L, filelength(fd));
# else
#   error "Can't handle compiler"
# endif
#endif
    fclose(FHandle);
  }
}
/*-------------------------------------------------------------------------*/
const char *dlini_int_ResolveFileName(
  const char *FileName
)
{
  /* This is what Windows calls the default INI file anyroad */
  static const char defFileName[] = "win.ini";

  if ( FileName ) return FileName;
  return defFileName;
}
/*-------------------------------------------------------------------------*/
unsigned int dlini_int_ChopComment(
  char *LineString
)
{
  unsigned int oldLen;
  char *comment;

  oldLen = strlen(LineString);
  comment = strchr(LineString, ';');
  if ( comment )
    comment[0] = '\0'; /* Terminate at beginning of comment */
    
  return oldLen - strlen(LineString);
}
/*-------------------------------------------------------------------------*/
unsigned int dlini_int_ChopCrap(
  char *LineString
)
{
  size_t pos;
  unsigned int oldLen;

  pos = strlen(LineString);
  oldLen = pos;
  if ( pos-- ) {
    do {
      if (
        LineString[pos] == '\n' ||
        LineString[pos] == ' ' ||
        LineString[pos] == '\r'
      ) {
        LineString[pos] = '\0';
        break;
      }
    } while ( pos-- );
  }
  return oldLen - strlen(LineString);
}
/*-------------------------------------------------------------------------*/
enum dlini_bool_t dlini_int_FindKey(
  const char *const FunctionName,
  FILE *FHandle,
  const char *KeyName
)
{
  char lineBuff[DLINI_LINEBUFFER];
  char* s;
  
  do {
    const char *keyoff; /* Offset of key into string (must be zero) */
    s = fgets(lineBuff, sizeof(lineBuff)/sizeof(lineBuff[0]), FHandle);
    if ( !s ) break; /* EOF */

    if ( lineBuff[0] == '[' ) /* Started new section */
      return dliniFalse; /* Do not look in the next section */
      
    keyoff = dlini_int_stristr(FunctionName, s, KeyName);
    if ( keyoff ) {
      if ( keyoff == lineBuff ) /* Key at beginning of line; perfect */
        return SeekToKeysValue(FHandle);
    }
  } while ( s );
  
  return dliniFalse;
}
/*-------------------------------------------------------------------------*/
enum dlini_bool_t dlini_int_FindNextKey(
  FILE *FHandle
)
{
  if ( FHandle ) {
    enum dlini_bool_t loop = dliniTrue;
    char lastChar = '\n';
    int currentChar;

    do {
      currentChar = fgetc(FHandle);
      if ( currentChar == EOF )
        return dliniFalse;
        
      if ( (char)lastChar == '\n' ) {
        if (
          currentChar != ' ' &&
          currentChar != '\n' &&
          currentChar != '['
        ) {
          fseek(FHandle, -1, SEEK_CUR); /* Back one char */
          break;
        }
      }

      lastChar = (char)currentChar;
    } while ( loop );
  }
  else
    return dliniFalse; /* File handle not supplied */

  return dliniTrue;
}
/*-------------------------------------------------------------------------*/
unsigned int dlini_int_ReadKey(
  FILE *FHandle,
  char *lpReturnedString,
  unsigned int nSize,
  enum dlini_bool_t AttachEquals
)
{
  int currentChar;
  char buff[DLINI_LINEBUFFER];
  unsigned int readChars = 0U;

  memset(lpReturnedString, 0, nSize);
  do {
    currentChar = fgetc(FHandle);
    if ( (char)currentChar == ';' ) { /* Start of comment? */
      fgets(buff, sizeof(buff), FHandle); /* Read (discard) rest of line */
      continue; /* Start over, junking comment */
    }
    else if ( (char)currentChar == '=' ) { /* separator encountered */
      fseek(FHandle, -1, SEEK_CUR); /* Rewind one character */
      break;
    }
    else {
      buff[readChars] = (char)currentChar;
      readChars++;
    }
  } while ( !feof(FHandle) );

  buff[readChars] = '\0';
  readChars -= dlini_int_ChopCrap(buff);
  if ( AttachEquals ) {
    if ( readChars < (sizeof(buff)/sizeof(buff[0])-1) ) {
      buff[readChars] = '=';
      buff[readChars+1] = '\0';
    }
  }
  strncat(lpReturnedString, buff, nSize);
  return readChars;
}
/*-------------------------------------------------------------------------*/
enum dlini_bool_t dlini_int_FindNextValue(
  FILE *FHandle
)
{
  if ( FHandle ) {
    char currentChar;
    enum dlini_bool_t loop = dliniTrue;
    enum dlini_bool_t equalsFound = dliniFalse;

    do {
      currentChar = fgetc(FHandle);
      if ( currentChar == '=' )
        equalsFound = dliniTrue;
      else if ( currentChar != ' ' ) {
        loop = false;
        fseek(FHandle, -1, SEEK_CUR);
      }

    } while ( loop );

    if ( equalsFound ) return dliniTrue;
  }
  
  return dliniFalse;
}
/*-------------------------------------------------------------------------*/
unsigned int dlini_int_ReadValue(
  FILE *FHandle,
  char *lpReturnedString,
  unsigned int nSize
)
{
  memset(lpReturnedString, 0, nSize);
  fgets(lpReturnedString, nSize, FHandle);
  dlini_int_ChopComment(lpReturnedString);
  dlini_int_ChopCrap(lpReturnedString);
  return strlen(lpReturnedString);
}
/*-------------------------------------------------------------------------*/
int dlini_int_stricmp(
  const char *const FunctionName,
  const char *s1,
  const char *s2
)
{
  char *copyS1;
  char *copyS2; /* Copies of both */
  int ret; /* Return value */
  
  copyS1 = dlini_int_strdup(FunctionName, s1);
  copyS2 = dlini_int_strdup(FunctionName, s2);
  if ( !copyS1 || !copyS2 ) {
    if ( dlini_int_debugFlag ) {
      fprintf(
        stderr,
        "%s(): Not enough memory to make a comparison in "
        "dlini_int_stricmp().  Comparison will be negative\n",
        FunctionName
      );
    }
    return -1;
  }

  /* Convert both to uppercase which provides a way to ignore the case */  
  dlini_int_strupr(copyS1);
  dlini_int_strupr(copyS2);
  
  ret = strcmp(copyS1, copyS2); /* Do comparison and save result */
  
  /* Cleanup and return */
  free(copyS1); free(copyS2);
  return ret;
}
/*-------------------------------------------------------------------------*/
char *dlini_int_strlwr(
  char *s
)
{
  unsigned int index = 0U;
  
  if ( !s ) return s; /* Get out before damage is done */
  while ( s[index] != '\0' ) {
    s[index] = (char)tolower( (int)(s[index]) );
    index++;
  };
  return s;
}
/*-------------------------------------------------------------------------*/
char *dlini_int_strupr(
  char *s
)
{
  unsigned int index = 0U;
  
  if ( !s ) return s; /* Get out before damage is done */
  while ( s[index] != '\0' ) {
    s[index] = (char)toupper( (int)(s[index]) );
    index++;
  };
  return s;
}
/*-------------------------------------------------------------------------*/
const char *dlini_int_stristr(
  const char *const FunctionName,
  const char *Str,
  const char *SubStr
)
{
  char *strCopy;
  char *subStrCopy;
  const char *ret = NULL;

  strCopy = dlini_int_strdup(FunctionName, Str);
  subStrCopy = dlini_int_strdup(FunctionName, SubStr);
  if ( strCopy && subStrCopy ) {
    char *offset;
    dlini_int_strlwr(strCopy);
    dlini_int_strlwr(subStrCopy);

    offset = strstr(strCopy, subStrCopy);
    if ( offset ) {
      unsigned int diff = offset - strCopy;
      ret = Str + diff;
    }
    
    free(strCopy);
    free(subStrCopy);
  }

  return ret;
}
/*-------------------------------------------------------------------------*/
char *dlini_int_strdup(
  const char *const FunctionName,
  const char *Str
)
{
  char *strCpy = NULL;
  const char *const thisFunctionName = "dlini_int_strdup";

  if ( Str ) {
    unsigned int bytes = strlen(Str)+1;
    strCpy = malloc(bytes);
    if ( strCpy ) {
      strcpy(strCpy, Str);
    }
    else {
      fprintf(
        stderr,
        "%s(): Failed to allocate %u bytes with %s()\n\n",
        (FunctionName) ? (FunctionName) : ("unknown"),
        bytes,
        thisFunctionName
      );
    }
  }
  else {
    fprintf(
      stderr,
      "%s(): Sent a NULL string to %s()\n",
      (FunctionName) ? (FunctionName) : ("unknown"),
      thisFunctionName
    );
  }

  return strCpy;
}
/*-------------------------------------------------------------------------*/
static enum dlini_bool_t SeekToKeysValue(
  FILE *FHandle
)
{
  unsigned int i = 2;
  int c;
  
  while ( i ) {
    long int oldPos = ftell(FHandle);
    
    fseek(FHandle, -1, SEEK_CUR); /* Go back one byte */
    
    if ( ftell(FHandle) != (oldPos - 1) )
      return dliniFalse;
      
    c = getc(FHandle);
    if ( c == '\n' )
      i--;
      
    ungetc(c, FHandle);
  }
  /*
    We are now at the start of the line we want.  Seek forward until we
    discover the '=', when we do, we're in front of it ready for whoever
    wants to read or write the value
  */
  
  do {
    c = fgetc(FHandle);
    if ( c == '=' ) break;
    if ( c == EOF ) return dliniFalse;
  } while ( c != EOF ); /* Condiction is of no consequence */
  
  return dliniTrue;
}
/*-------------------------------------------------------------------------*/
unsigned int dlini_int_StringToPositiveInteger(
  const char *StringAsNumber
)
{
  int number = atoi(StringAsNumber);
  if ( number < 0 ) number = 0; /* Microsoft rules, negatives are illegal */
  return number;
}
/*-------------------------------------------------------------------------*/
unsigned char dlini_int_ByteChecksum(
  const void *Buffer,
  const unsigned int BufferSize
)
{
  unsigned char sum = '\0';
  unsigned int i;
  unsigned char *CharBuffer = (unsigned char *)Buffer;

  for ( i = 0U; i < BufferSize; i++ )
    sum += CharBuffer[i];

  return sum;
}
/*-------------------------------------------------------------------------*/