aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/lib/libtinyrad/lstrings.c
blob: e2b6bdf499db48317677efa01d244348f7d09e76 (plain) (blame)
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
/*
 *  Tiny RADIUS Client Library
 *  Copyright (C) 2021 David M. Syzdek <david@syzdek.net>.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are
 *  met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * 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.
 *     * Neither the name of David M. Syzdek 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 COPYRIGHT HOLDERS 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 DAVID M. SYZDEK 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.
 */
#define _LIB_LIBTINYRAD_LSTRINGS_C 1
#include "lstrings.h"


///////////////
//           //
//  Headers  //
//           //
///////////////
#pragma mark - Headers

#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <time.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <ctype.h>
#include <pwd.h>
#include <grp.h>
#include <sys/utsname.h>
#include <assert.h>

#include "ldict.h"


///////////////////
//               //
//  Definitions  //
//               //
///////////////////
#pragma mark - Definitions


//////////////////
//              //
//  Prototypes  //
//              //
//////////////////
#pragma mark - Prototypes


/////////////////
//             //
//  Functions  //
//             //
/////////////////
#pragma mark - Functions

//------------------//
// string functions //
//------------------//
#pragma mark string functions

char *
tinyrad_strdup(
         const char *                  s1 )
{
   char *      ptr;
   size_t      len;
   TinyRadDebugTrace();
   if (!(s1))
      return(NULL);
   len = strlen(s1);
   if ((ptr = malloc(len+2)) == NULL)
      return(NULL);
   memcpy(ptr, s1, len);
   ptr[len+0] = '\0';
   ptr[len+1] = '\0';
   return(ptr);
}


char *
tinyrad_strexpand(
         char *                        dst,
         const char * restrict         src,
         size_t                        len,
         int                           force_expansion )
{
   size_t            pos;
   size_t            offset;
   char              buff[4096];
   char *            ptr;
   char              quote;
   struct utsname    unam;
   struct passwd     pwd;
   struct passwd *   pwres;
   struct group      grp;
   struct group *    grres;

   TinyRadDebugTrace();

   assert(dst != NULL);
   assert(len  > 0);

   if (!(src))
      return(NULL);

   // expand escapes in buffer
   offset = 0;
   quote  = ((src[0] == '\'')||(src[0] == '"')) ? src[0] : 0;
   for(pos = (((quote)) ? 1 : 0); ( ((src[pos])) && (offset < (len-1)) ); pos++)
   {
      if ( (quote != '"') && (force_expansion != TRAD_YES) )
      {
         dst[offset++] = src[pos];
         continue;
      };
      switch(src[pos])
      {
         // tokens
         case '%':
         // %% - a literal percent
         // %D - domain name
         // %d - home directory
         // %G - group ID
         // %g - group name
         // %H - hostname with domain name
         // %h - hostname without domain name
         // %P - process ID
         // %p - process name
         // %U - user ID
         // %u - username
         pos++;
         switch(src[pos])
         {
            case 'D': // domain name
            if (uname(&unam) == -1)
               return(NULL);
            strncpy(buff, unam.nodename, sizeof(buff));
            if ((ptr = strchr(buff, '.')) == NULL)
               buff[0] = '\0';
            ptr = ((ptr)) ? &ptr[1] : buff;
            dst[offset] = '\0';
            tinyrad_strlcat(dst, ptr, len);
            offset += strlen(ptr);
            break;

            case 'd': // home directory
            getpwuid_r(getuid(), &pwd, buff, sizeof(buff), &pwres);
            if (!(pwres))
               break;
            dst[offset] = '\0';
            tinyrad_strlcat(dst, pwres->pw_dir, len);
            offset += strlen(pwres->pw_dir);
            break;

            case 'G': // gid
            snprintf(buff, sizeof(buff), "%u", getgid());
            dst[offset] = '\0';
            tinyrad_strlcat(dst, buff, len);
            offset += strlen(buff);
            break;

            case 'g': // group name
            getgrgid_r(getgid(), &grp, buff, sizeof(buff), &grres);
            if (!(grres))
               break;
            dst[offset] = '\0';
            tinyrad_strlcat(dst, grres->gr_name, len);
            offset += strlen(grres->gr_name);
            break;

            case 'H': // fully qualified hostname
            if (uname(&unam) == -1)
               break;
            dst[offset] = '\0';
            tinyrad_strlcat(dst, unam.nodename, len);
            offset += strlen(unam.nodename);
            break;

            case 'h': // short hostname
            if (uname(&unam) == -1)
               break;
            strncpy(buff, unam.nodename, sizeof(buff));
            if ((ptr = strchr(buff, '.')) != NULL)
               ptr[0] = '\0';
            dst[offset] = '\0';
            tinyrad_strlcat(dst, buff, len);
            offset += strlen(buff);
            break;

            case 'P': // process ID
            snprintf(buff, sizeof(buff), "%u", getppid());
            dst[offset] = '\0';
            tinyrad_strlcat(dst, buff, len);
            offset += strlen(buff);
            break;

            case 'p': // process name/ident
            dst[offset] = '\0';
            tinyrad_strlcat(dst, tinyrad_debug_ident, len);
            offset += strlen(tinyrad_debug_ident);
            break;

            case 'U': // uid
            snprintf(buff, sizeof(buff), "%u", getgid());
            dst[offset] = '\0';
            tinyrad_strlcat(dst, buff, len);
            offset += strlen(buff);
            break;

            case 'u': // username
            getpwuid_r(getuid(), &pwd, buff, sizeof(buff), &pwres);
            if (!(pwres))
               break;
            dst[offset] = '\0';
            tinyrad_strlcat(dst, pwres->pw_name, len);
            offset += strlen(pwres->pw_name);
            break;

            case '%': // '%' character
            dst[offset++] = src[pos];
            break;

            default:
            dst[offset++] = src[pos];
         };
         break;

         // character escape sequences
         case '\\':
         pos++;
         switch(src[pos])
         {
            case '"':
            case '\'':
            case '\\':
            case '\?':
            dst[offset++] = src[pos];
            break;

            case 'n': dst[offset++] = '\n'; break;
            case 'r': dst[offset++] = '\r'; break;
            case 't': dst[offset++] = '\t'; break;
            case 'v': dst[offset++] = '\v'; break;

            // \xnn - treat nn as hex value
            case 'x':
            buff[0] = src[++pos];
            buff[1] = src[++pos];
            buff[2] = '\0';
            dst[offset++] = (char)strtoul(buff, &ptr, 16);
            if (ptr != &buff[2])
               return(TRAD_SUCCESS);
            break;

            // \nnn - treat nnn as octal value
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            buff[0] = src[pos++];
            buff[1] = src[pos++];
            buff[2] = src[pos];
            buff[3] = '\0';
            dst[offset++] = (char)strtoul(buff, &ptr, 8);
            if (ptr != &buff[3])
               return(TRAD_SUCCESS);
            break;

            default:
            dst[offset++] = src[pos];
         };
         break;

         default:
         dst[offset++] = src[pos];
         break;
      };
   };
   if ((quote))
      offset--;
   if (offset >= len)
   {
      dst[len-1] = '\0';
      return(NULL);
   };
   dst[offset] = '\0';

   return(dst);
}


size_t
tinyrad_strlcpy(
         char * restrict               dst,
         const char * restrict         src,
         size_t                        dstsize )
{
   size_t len;
   TinyRadDebugTrace();
   assert(dst     != NULL);
   assert(src     != NULL);
   assert(dstsize  > 0);
   for(len = 0; ((src[len])); len++)
      if (len < dstsize)
         dst[len] = src[len];
   dst[((len < dstsize) ? len : (dstsize-1))] = '\0';
   return(len);
}


size_t
tinyrad_strlcat(
         char * restrict               dst,
         const char * restrict         src,
         size_t                        dstsize )
{
   size_t      pos;
   size_t      offset;
   size_t      len;
   TinyRadDebugTrace();
   assert(dst     != NULL);
   assert(src     != NULL);
   assert(dstsize  > 0);
   for(pos = 0; ((dst[pos])); pos++);
   for(offset = 0; ((src[offset])); offset++)
      if ((pos + offset) < dstsize)
         dst[pos+offset] = src[offset];
   len = offset + pos;
   dst[((len < dstsize) ? len : (dstsize-1))] = '\0';
   return(len);
}


char *
tinyrad_strndup(
         const char *                  s1,
         size_t                        n )
{
   char *      ptr;
   size_t      len;
   TinyRadDebugTrace();
   if (!(s1))
      return(NULL);
   len = strlen(s1);
   len = (len < n) ? len : n;
   if ((ptr = malloc(len+2)) == NULL)
      return(NULL);
   memcpy(ptr, s1, len);
   ptr[len+0] = '\0';
   ptr[len+1] = '\0';
   return(ptr);
}


/// Appends string to NULL terminated array of strings
///
/// @param[out] strsp         pointer to string array
/// @param[in]  str           string to append to array
/// @return returns error code
int
tinyrad_strsadd(
         char ***                      strsp,
         const char *                  str )
{
   size_t     count;
   char **    strs;

   TinyRadDebugTrace();

   assert(strsp != NULL);
   assert(str   != NULL);

   count = tinyrad_strscount(*strsp);

   // increase size of array
   if ((strs = realloc(*strsp, (sizeof(char *)*(count+2)))) == NULL)
      return(TRAD_ENOMEM);
   *strsp        = strs;

   // copy string
   if ((strs[count] = tinyrad_strdup(str)) == NULL)
      return(TRAD_ENOMEM);

   // terminate array
   count++;
   strs[count] = NULL;

   return(TRAD_SUCCESS);
}


/// counts number of strings in NULL terminated array of strings
///
/// @param[in]  strs          pointer to string array
/// @return number of strings in array
size_t
tinyrad_strscount(
         char * const *                strs )
{
   size_t count;
   TinyRadDebugTrace();
   if (!(strs))
      return(0);
   for(count = 0; ((strs != NULL)&&(strs[count] != NULL)); count++);
   return(count);
}


int
tinyrad_strsdup(
         char ***                      dstp,
         char * const *                src )
{
   size_t      len;
   size_t      size;
   size_t      pos;
   char **     dst;

   TinyRadDebugTrace();

   assert(dstp != NULL);
   assert(src   != NULL);

   len  = tinyrad_strscount(src);
   size = sizeof(char *) * (len+1);

   if ((dst = malloc(size)) == NULL)
      return(TRAD_ENOMEM);

   for(pos = 0; (pos < len); pos++)
   {
      if ((dst[pos] = tinyrad_strdup(src[pos])) == NULL)
      {
         tinyrad_strsfree(dst);
         return(TRAD_ENOMEM);
      };
   };
   dst[pos] = NULL;

   *dstp = dst;

   return(TRAD_SUCCESS);
}


/// frees NULL terminated array of strings
///
/// @param[in]  strs          pointer to string array
void
tinyrad_strsfree(
         char **                       strs )
{
   int i;
   TinyRadDebugTrace();
   if (!(strs))
      return;
   for(i = 0; ((strs[i])); i++)
   {
      free(strs[i]);
      strs[i] = NULL;
   };
   free(strs);
   return;
}


int
tinyrad_strsplit(
         const char *                  str,
         int                           delim,
         char ***                      argvp,
         int *                         argcp )
{
   int            rc;
   int            argc;
   size_t         pos;
   char **        argv;
   char *         line;
   char *         bol;

   TinyRadDebugTrace();

   assert(str   != NULL);
   assert(delim != 0);
   assert(argvp != NULL);

   argv = NULL;
   argc = 0;
   if ((argvp))
      *argvp   = NULL;
   if ((argcp))
      *argcp = 0;

   if (!(str))
      return(TRAD_SUCCESS);

   if ((line = tinyrad_strdup(str)) == NULL)
      return(TRAD_ENOMEM);
   bol = line;

   for(pos = 0; ((line[pos])); pos++)
   {
      if (line[pos] == delim)
      {
         argc++;
         line[pos] = '\0';
         if ((rc = tinyrad_strsadd(&argv, bol)) != TRAD_SUCCESS)
         {
            free(line);
            tinyrad_strsfree(argv);
            return(rc);
         };
         bol = &line[pos+1];
      };
   };

//   if ( (bol == line) && (!(bol[0])) )
//      return(TRAD_SUCCESS);

   if ((rc = tinyrad_strsadd(&argv, bol)) != TRAD_SUCCESS)
   {
      free(line);
      tinyrad_strsfree(argv);
      return(rc);
   };
   argc++;

   if ((argvp))
      *argvp = argv;
   if ((argcp))
      *argcp = argc;

   return(TRAD_SUCCESS);
}


int
tinyrad_strtoargs(
         char *                        str,
         char ***                      argvp,
         int *                         argcp )
{
   char           quote;
   char *         bol;
   char **        argv;
   size_t         pos;
   int            rc;
   int            eol;

   TinyRadDebugTrace();

   assert(str != NULL);

   argv = NULL;
   eol  = 0;

   for(pos = 0; ( ((str[pos])) && (!(eol)) ); pos++)
   {
      switch(str[pos])
      {
         // skip white space
         case ' ':
         case '\t':
         break;

         // parse quoted argument
         case '"':
         case '\'':
         quote = str[pos];
         bol   = &str[pos];
         for(pos += 1; ((str[pos] != '\0') && (str[pos] != quote)); pos++)
            if ( (quote == '"') && (str[pos] == '\\') && (str[pos+1] == '"') )
               pos++;
         if (str[pos] != quote)
         {
            tinyrad_strsfree(argv);
            return(TRAD_ESYNTAX);
         };
         pos++;
         switch(str[pos])
         {
            case '\0':
            case '#':
            eol = 1;
            str[pos] = '\0';
            break;

            case ' ':
            case '\t':
            str[pos] = '\0';
            break;

            default:
            tinyrad_strsfree(argv);
            return(TRAD_ESYNTAX);
         };
         if ((rc = tinyrad_strsadd(&argv, bol)) != TRAD_SUCCESS)
         {
            tinyrad_strsfree(argv);
            return(rc);
         };
         break;

         // parse unquoted argument
         default:
         bol = &str[pos];
         while( (str[pos] != ' ') && (str[pos] != '\t') && (str[pos] != '\0') && (str[pos] != '#') )
         {
            if ( (str[pos] < '!') || (str[pos] > '~') || (str[pos] == '"') || (str[pos] == '\'') )
            {
               tinyrad_strsfree(argv);
               return(TRAD_ESYNTAX);
            };
            pos++;
         };
         if ((str[pos] == '#') || (str[pos] == '\0'))
            eol = 1;
         str[pos] = '\0';
         if ((bol[0]))
         {
            if ((rc = tinyrad_strsadd(&argv, bol)) != TRAD_SUCCESS)
            {
               tinyrad_strsfree(argv);
               return(rc);
            };
         };
         break;
      };
   };

   if ((argcp))
      *argcp = (int)tinyrad_strscount(argv);
   if ((argvp))
      *argvp = argv;
   if (!(argvp))
      tinyrad_strsfree(argv);

   return(TRAD_SUCCESS);
}


int
tinyrad_strtobool(
         const char *                  str )
{
   if      (!(str))                       return(-1);
   else if (!(strcasecmp(str, "1")))      return(TRAD_YES);
   else if (!(strcasecmp(str, "true")))   return(TRAD_YES);
   else if (!(strcasecmp(str, "yes")))    return(TRAD_YES);
   else if (!(strcasecmp(str, "0")))      return(TRAD_NO);
   else if (!(strcasecmp(str, "false")))  return(TRAD_NO);
   else if (!(strcasecmp(str, "no")))     return(TRAD_NO);
   return(-1);
}


char *
tinyrad_strtrim(
         char *                        str )
{
   ssize_t offset;
   ssize_t pos;

   TinyRadDebugTrace();

   if (!(str))
      return(str);

   // find end of whitespace
   for(offset = 0; ( ((str[offset])) && ((isspace(str[offset]))) ); offset++);

   // shift string by offset
   for(pos = offset; ((str[pos])); pos++)
      str[pos-offset] = str[pos];
   if (!(pos))
      return(str);

   // trim end of line
   for(pos = pos - 1 - offset; ( ((isspace(str[pos]))) && (pos > 0) ); pos--);
   str[pos+1] = '\0';

   return(str);
}



/* end of source */