summaryrefslogtreecommitdiff
path: root/cgi-bin/var.c
blob: 628ce8add577b80f624384b14ebfe4e74ad366df (plain)
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
/*
 * "$Id: var.c 7460 2008-04-16 02:19:54Z mike $"
 *
 *   CGI form variable and array functions.
 *
 *   Copyright 2007-2009 by Apple Inc.
 *   Copyright 1997-2005 by Easy Software Products.
 *
 *   These coded instructions, statements, and computer programs are the
 *   property of Apple Inc. and are protected by Federal copyright
 *   law.  Distribution and use rights are outlined in the file "LICENSE.txt"
 *   which should have been included with this file.  If this file is
 *   file is missing or damaged, see the license at "http://www.cups.org/".
 *
 * Contents:
 *
 *   cgiCheckVariables()        - Check for the presence of "required" variables.
 *   cgiGetArray()              - Get an element from a form array...
 *   cgiGetFile()               - Get the file (if any) that was submitted in the form.
 *   cgiGetSize()               - Get the size of a form array value.
 *   cgiGetVariable()           - Get a CGI variable from the database...
 *   cgiInitialize()            - Initialize the CGI variable "database"...
 *   cgiIsPOST()                - Determine whether this page was POSTed.
 *   cgiSetArray()              - Set array element N to the specified string.
 *   cgiSetSize()               - Set the array size.
 *   cgiSetVariable()           - Set a CGI variable in the database...
 *   cgi_add_variable()         - Add a form variable.
 *   cgi_compare_variables()    - Compare two variables.
 *   cgi_find_variable()        - Find a variable...
 *   cgi_initialize_get()       - Initialize form variables using the GET method.
 *   cgi_initialize_multipart() - Initialize variables and file using the POST method.
 *   cgi_initialize_post()      - Initialize variables using the POST method.
 *   cgi_initialize_string()    - Initialize form variables from a string.
 *   cgi_passwd()               - Catch authentication requests and notify the server.
 *   cgi_sort_variables()       - Sort all form variables for faster lookup.
 *   cgi_unlink_file()          - Remove the uploaded form.
 */

/*#define DEBUG*/
#include "cgi-private.h"
#include <errno.h>


/*
 * Data structure to hold all the CGI form variables and arrays...
 */

typedef struct				/**** Form variable structure ****/
{
  const char	*name;			/* Name of variable */
  int		nvalues,		/* Number of values */
		avalues;		/* Number of values allocated */
  const char	**values;		/* Value(s) of variable */
} _cgi_var_t;


/*
 * Local globals...
 */

static int		form_count = 0,	/* Form variable count */
			form_alloc = 0;	/* Number of variables allocated */
static _cgi_var_t	*form_vars = NULL;
					/* Form variables */
static cgi_file_t	*form_file = NULL;
					/* Uploaded file */


/*
 * Local functions...
 */

static void		cgi_add_variable(const char *name, int element,
			                 const char *value);
static int		cgi_compare_variables(const _cgi_var_t *v1,
			                      const _cgi_var_t *v2);
static _cgi_var_t	*cgi_find_variable(const char *name);
static int		cgi_initialize_get(void);
static int		cgi_initialize_multipart(const char *boundary);
static int		cgi_initialize_post(void);
static int		cgi_initialize_string(const char *data);
static const char	*cgi_passwd(const char *prompt);
static void		cgi_sort_variables(void);
static void		cgi_unlink_file(void);


/*
 * 'cgiCheckVariables()' - Check for the presence of "required" variables.
 *
 * Names may be separated by spaces and/or commas.
 */

int					/* O - 1 if all variables present, 0 otherwise */
cgiCheckVariables(const char *names)	/* I - Variables to look for */
{
  char		name[255],		/* Current variable name */
		*s;			/* Pointer in string */
  const char	*val;			/* Value of variable */
  int		element;		/* Array element number */


  if (names == NULL)
    return (1);

  while (*names != '\0')
  {
    while (*names == ' ' || *names == ',')
      names ++;

    for (s = name; *names != '\0' && *names != ' ' && *names != ','; s ++, names ++)
      *s = *names;

    *s = 0;
    if (name[0] == '\0')
      break;

    if ((s = strrchr(name, '-')) != NULL)
    {
      *s      = '\0';
      element = atoi(s + 1) - 1;
      val     = cgiGetArray(name, element);
    }
    else
      val = cgiGetVariable(name);

    if (val == NULL)
      return (0);

    if (*val == '\0')
      return (0);	/* Can't be blank, either! */
  }

  return (1);
}


/*
 * 'cgiGetArray()' - Get an element from a form array...
 */

const char *				/* O - Element value or NULL */
cgiGetArray(const char *name,		/* I - Name of array variable */
            int        element)		/* I - Element number (0 to N) */
{
  _cgi_var_t	*var;			/* Pointer to variable */


  if ((var = cgi_find_variable(name)) == NULL)
    return (NULL);

  if (element < 0 || element >= var->nvalues)
    return (NULL);

  return (var->values[element]);
}


/*
 * 'cgiGetFile()' - Get the file (if any) that was submitted in the form.
 */

const cgi_file_t *			/* O - Attached file or NULL */
cgiGetFile(void)
{
  return (form_file);
}


/*
 * 'cgiGetSize()' - Get the size of a form array value.
 */

int					/* O - Number of elements */
cgiGetSize(const char *name)		/* I - Name of variable */
{
  _cgi_var_t	*var;			/* Pointer to variable */


  if ((var = cgi_find_variable(name)) == NULL)
    return (0);

  return (var->nvalues);
}


/*
 * 'cgiGetVariable()' - Get a CGI variable from the database...
 *
 * Returns NULL if the variable doesn't exist.  If the variable is an
 * array of values, returns the last element...
 */

const char *				/* O - Value of variable */
cgiGetVariable(const char *name)	/* I - Name of variable */
{
  const _cgi_var_t	*var;		/* Returned variable */


  var = cgi_find_variable(name);

#ifdef DEBUG
  if (var == NULL)
    DEBUG_printf(("cgiGetVariable(\"%s\") is returning NULL...\n", name));
  else
    DEBUG_printf(("cgiGetVariable(\"%s\") is returning \"%s\"...\n", name,
		  var->values[var->nvalues - 1]));
#endif /* DEBUG */

  return ((var == NULL) ? NULL : var->values[var->nvalues - 1]);
}


/*
 * 'cgiInitialize()' - Initialize the CGI variable "database"...
 */

int					/* O - Non-zero if there was form data */
cgiInitialize(void)
{
  const char	*method;		/* Form posting method */
  const char	*content_type;		/* Content-Type of post data */


 /*
  * Setup a password callback for authentication...
  */

  cupsSetPasswordCB(cgi_passwd);

 /*
  * Set the locale so that times, etc. are formatted properly...
  */

  setlocale(LC_ALL, "");

#ifdef DEBUG
 /*
  * Disable output buffering to find bugs...
  */

  setbuf(stdout, NULL);
#endif /* DEBUG */

 /*
  * Get the request method (GET or POST)...
  */

  method       = getenv("REQUEST_METHOD");
  content_type = getenv("CONTENT_TYPE");
  if (!method)
    return (0);

 /*
  * Grab form data from the corresponding location...
  */

  if (!strcasecmp(method, "GET"))
    return (cgi_initialize_get());
  else if (!strcasecmp(method, "POST") && content_type)
  {
    const char *boundary = strstr(content_type, "boundary=");

    if (boundary)
      boundary += 9;

    if (content_type && !strncmp(content_type, "multipart/form-data; ", 21))
      return (cgi_initialize_multipart(boundary));
    else
      return (cgi_initialize_post());
  }
  else
    return (0);
}


/*
 * 'cgiIsPOST()' - Determine whether this page was POSTed.
 */

int					/* O - 1 if POST, 0 if GET */
cgiIsPOST(void)
{
  const char	*method;		/* REQUEST_METHOD environment variable */


  if ((method = getenv("REQUEST_METHOD")) == NULL)
    return (0);
  else
    return (!strcmp(method, "POST"));
}


/*
 * 'cgiSetArray()' - Set array element N to the specified string.
 *
 * If the variable array is smaller than (element + 1), the intervening
 * elements are set to NULL.
 */

void
cgiSetArray(const char *name,		/* I - Name of variable */
            int        element,		/* I - Element number (0 to N) */
            const char *value)		/* I - Value of variable */
{
  int		i;			/* Looping var */
  _cgi_var_t	*var;			/* Returned variable */


  if (name == NULL || value == NULL || element < 0 || element > 100000)
    return;

  if ((var = cgi_find_variable(name)) == NULL)
  {
    cgi_add_variable(name, element, value);
    cgi_sort_variables();
  }
  else
  {
    if (element >= var->avalues)
    {
      const char **temp;		/* Temporary pointer */

      temp = (const char **)realloc((void *)(var->values),
                                    sizeof(char *) * (element + 16));
      if (!temp)
        return;

      var->avalues = element + 16;
      var->values  = temp;
    }

    if (element >= var->nvalues)
    {
      for (i = var->nvalues; i < element; i ++)
	var->values[i] = NULL;

      var->nvalues = element + 1;
    }
    else if (var->values[element])
      free((char *)var->values[element]);

    var->values[element] = strdup(value);
  }
}


/*
 * 'cgiSetSize()' - Set the array size.
 */

void
cgiSetSize(const char *name,		/* I - Name of variable */
           int        size)		/* I - Number of elements (0 to N) */
{
  int		i;			/* Looping var */
  _cgi_var_t	*var;			/* Returned variable */


  if (name == NULL || size < 0 || size > 100000)
    return;

  if ((var = cgi_find_variable(name)) == NULL)
    return;

  if (size >= var->avalues)
  {
    const char **temp;			/* Temporary pointer */

    temp = (const char **)realloc((void *)(var->values),
				  sizeof(char *) * (size + 16));
    if (!temp)
      return;

    var->avalues = size + 16;
    var->values  = temp;
  }

  if (size > var->nvalues)
  {
    for (i = var->nvalues; i < size; i ++)
      var->values[i] = NULL;
  }
  else if (size < var->nvalues)
  {
    for (i = size; i < var->nvalues; i ++)
      if (var->values[i])
        free((void *)(var->values[i]));
  }

  var->nvalues = size;
}


/*
 * 'cgiSetVariable()' - Set a CGI variable in the database...
 *
 * If the variable is an array, this truncates the array to a single element.
 */

void
cgiSetVariable(const char *name,	/* I - Name of variable */
               const char *value)	/* I - Value of variable */
{
  int		i;			/* Looping var */
  _cgi_var_t	*var;			/* Returned variable */


  if (name == NULL || value == NULL)
    return;

  if ((var = cgi_find_variable(name)) == NULL)
  {
    cgi_add_variable(name, 0, value);
    cgi_sort_variables();
  }
  else
  {
    for (i = 0; i < var->nvalues; i ++)
      if (var->values[i])
        free((char *)var->values[i]);

    var->values[0] = strdup(value);
    var->nvalues   = 1;
  }
}


/*
 * 'cgi_add_variable()' - Add a form variable.
 */

static void
cgi_add_variable(const char *name,	/* I - Variable name */
		 int        element,	/* I - Array element number */
                 const char *value)	/* I - Variable value */
{
  _cgi_var_t	*var;			/* New variable */


  if (name == NULL || value == NULL || element < 0 || element > 100000)
    return;

  DEBUG_printf(("cgi_add_variable: Adding variable \'%s\' with value "
                "\'%s\'...\n", name, value));

  if (form_count >= form_alloc)
  {
    _cgi_var_t	*temp_vars;		/* Temporary form pointer */


    if (form_alloc == 0)
      temp_vars = malloc(sizeof(_cgi_var_t) * 16);
    else
      temp_vars = realloc(form_vars, (form_alloc + 16) * sizeof(_cgi_var_t));

    if (!temp_vars)
      return;

    form_vars  = temp_vars;
    form_alloc += 16;
  }

  var = form_vars + form_count;

  if ((var->values = calloc(element + 1, sizeof(char *))) == NULL)
    return;

  var->name            = strdup(name);
  var->nvalues         = element + 1;
  var->avalues         = element + 1;
  var->values[element] = strdup(value);

  form_count ++;
}


/*
 * 'cgi_compare_variables()' - Compare two variables.
 */

static int				/* O - Result of comparison */
cgi_compare_variables(
    const _cgi_var_t *v1,		/* I - First variable */
    const _cgi_var_t *v2)		/* I - Second variable */
{
  return (strcasecmp(v1->name, v2->name));
}


/*
 * 'cgi_find_variable()' - Find a variable...
 */

static _cgi_var_t *			/* O - Variable pointer or NULL */
cgi_find_variable(const char *name)	/* I - Name of variable */
{
  _cgi_var_t	key;			/* Search key */


  if (form_count < 1 || name == NULL)
    return (NULL);

  key.name = name;

  return ((_cgi_var_t *)bsearch(&key, form_vars, form_count, sizeof(_cgi_var_t),
                           (int (*)(const void *, const void *))cgi_compare_variables));
}


/*
 * 'cgi_initialize_get()' - Initialize form variables using the GET method.
 */

static int				/* O - 1 if form data read */
cgi_initialize_get(void)
{
  char	*data;				/* Pointer to form data string */


  DEBUG_puts("cgi_initialize_get: Initializing variables using GET method...");

 /*
  * Check to see if there is anything for us to read...
  */

  data = getenv("QUERY_STRING");
  if (data == NULL || strlen(data) == 0)
    return (0);

 /*
  * Parse it out and return...
  */

  return (cgi_initialize_string(data));
}


/*
 * 'cgi_initialize_multipart()' - Initialize variables and file using the POST method.
 *
 * TODO: Update to support files > 2GB.
 */

static int				/* O - 1 if form data was read */
cgi_initialize_multipart(
    const char *boundary)		/* I - Boundary string */
{
  char		line[10240],		/* MIME header line */
		name[1024],		/* Form variable name */
		filename[1024],		/* Form filename */
		mimetype[1024],		/* MIME media type */
		bstring[256],		/* Boundary string to look for */
		*ptr,			/* Pointer into name/filename */
		*end;			/* End of buffer */
  int		ch,			/* Character from file */
		fd,			/* Temporary file descriptor */
		blen;			/* Length of boundary string */


  DEBUG_printf(("cgi_initialize_multipart(boundary=\"%s\")\n", boundary));

 /*
  * Read multipart form data until we run out...
  */

  name[0]     = '\0';
  filename[0] = '\0';
  mimetype[0] = '\0';

  snprintf(bstring, sizeof(bstring), "\r\n--%s", boundary);
  blen = strlen(bstring);

  while (fgets(line, sizeof(line), stdin))
  {
    if (!strcmp(line, "\r\n"))
    {
     /*
      * End of headers, grab value...
      */

      if (filename[0])
      {
       /*
        * Read an embedded file...
	*/

        if (form_file)
	{
	 /*
	  * Remove previous file...
	  */

	  cgi_unlink_file();
	}

       /*
        * Allocate memory for the new file...
	*/

	if ((form_file = calloc(1, sizeof(cgi_file_t))) == NULL)
	  return (0);

        form_file->name     = strdup(name);
	form_file->filename = strdup(filename);
	form_file->mimetype = strdup(mimetype);

        fd = cupsTempFd(form_file->tempfile, sizeof(form_file->tempfile));

        if (fd < 0)
	  return (0);

        atexit(cgi_unlink_file);

       /*
        * Copy file data to the temp file...
	*/
	
        ptr = line;

	while ((ch = getchar()) != EOF)
	{
	  *ptr++ = ch;

          if ((ptr - line) >= blen && !memcmp(ptr - blen, bstring, blen))
	  {
	    ptr -= blen;
	    break;
	  }

          if ((ptr - line - blen) >= 8192)
	  {
	   /*
	    * Write out the first 8k of the buffer...
	    */

	    write(fd, line, 8192);
	    memmove(line, line + 8192, ptr - line - 8192);
	    ptr -= 8192;
	  }
	}

       /*
        * Write the rest of the data and close the temp file...
	*/

	if (ptr > line)
          write(fd, line, ptr - line);

	close(fd);
      }
      else
      {
       /*
        * Just get a form variable; the current code only handles
	* form values up to 10k in size...
	*/

        ptr = line;
	end = line + sizeof(line) - 1;

	while ((ch = getchar()) != EOF)
	{
	  if (ptr < end)
	    *ptr++ = ch;

          if ((ptr - line) >= blen && !memcmp(ptr - blen, bstring, blen))
	  {
	    ptr -= blen;
	    break;
	  }
	}

	*ptr = '\0';

       /*
        * Set the form variable...
	*/

	if ((ptr = strrchr(name, '-')) != NULL && isdigit(ptr[1] & 255))
	{
	 /*
	  * Set a specific index in the array...
	  */

	  *ptr++ = '\0';
	  if (line[0])
            cgiSetArray(name, atoi(ptr) - 1, line);
	}
	else if (cgiGetVariable(name))
	{
	 /*
	  * Add another element in the array...
	  */

	  cgiSetArray(name, cgiGetSize(name), line);
	}
	else
	{
	 /*
	  * Just set the line...
	  */

	  cgiSetVariable(name, line);
	}
      }

     /*
      * Read the rest of the current line...
      */

      fgets(line, sizeof(line), stdin);

     /*
      * Clear the state vars...
      */

      name[0]     = '\0';
      filename[0] = '\0';
      mimetype[0] = '\0';
    }
    else if (!strncasecmp(line, "Content-Disposition:", 20))
    {
      if ((ptr = strstr(line + 20, " name=\"")) != NULL)
      {
        strlcpy(name, ptr + 7, sizeof(name));

	if ((ptr = strchr(name, '\"')) != NULL)
	  *ptr = '\0';
      }

      if ((ptr = strstr(line + 20, " filename=\"")) != NULL)
      {
        strlcpy(filename, ptr + 11, sizeof(filename));

	if ((ptr = strchr(filename, '\"')) != NULL)
	  *ptr = '\0';
      }
    }
    else if (!strncasecmp(line, "Content-Type:", 13))
    {
      for (ptr = line + 13; isspace(*ptr & 255); ptr ++);

      strlcpy(mimetype, ptr, sizeof(mimetype));

      for (ptr = mimetype + strlen(mimetype) - 1;
           ptr > mimetype && isspace(*ptr & 255);
	   *ptr-- = '\0');
    }
  }

 /*
  * Return 1 for "form data found"...
  */

  return (1);
}


/*
 * 'cgi_initialize_post()' - Initialize variables using the POST method.
 */

static int				/* O - 1 if form data was read */
cgi_initialize_post(void)
{
  char	*content_length,		/* Length of input data (string) */
	*data;				/* Pointer to form data string */
  int	length,				/* Length of input data */
	nbytes,				/* Number of bytes read this read() */
	tbytes,				/* Total number of bytes read */
	status;				/* Return status */


  DEBUG_puts("cgi_initialize_post: Initializing variables using POST method...");

 /*
  * Check to see if there is anything for us to read...
  */

  content_length = getenv("CONTENT_LENGTH");
  if (content_length == NULL || atoi(content_length) <= 0)
    return (0);

 /*
  * Get the length of the input stream and allocate a buffer for it...
  */

  length = atoi(content_length);
  data   = malloc(length + 1);

  if (data == NULL)
    return (0);

 /*
  * Read the data into the buffer...
  */

  for (tbytes = 0; tbytes < length; tbytes += nbytes)
    if ((nbytes = read(0, data + tbytes, length - tbytes)) < 0)
    {
      if (errno != EAGAIN)
      {
        free(data);
        return (0);
      }
      else
        nbytes = 0;
    }
    else if (nbytes == 0)
    {
     /*
      * CUPS STR #3176: OpenBSD: Early end-of-file on POST data causes 100% CPU
      *
      * This should never happen, but does on OpenBSD.  If we see early end-of-
      * file, treat this as an error and process no data.
      */

      free(data);
      return (0);
    }

  data[length] = '\0';

 /*
  * Parse it out...
  */

  status = cgi_initialize_string(data);

 /*
  * Free the data and return...
  */

  free(data);

  return (status);
}


/*
 * 'cgi_initialize_string()' - Initialize form variables from a string.
 */

static int				/* O - 1 if form data was processed */
cgi_initialize_string(const char *data)	/* I - Form data string */
{
  int	done;				/* True if we're done reading a form variable */
  char	*s,				/* Pointer to current form string */
	ch,				/* Temporary character */
	name[255],			/* Name of form variable */
	value[65536];			/* Variable value... */


 /*
  * Check input...
  */

  if (data == NULL)
    return (0);

 /*
  * Loop until we've read all the form data...
  */

  while (*data != '\0')
  {
   /*
    * Get the variable name...
    */

    for (s = name; *data != '\0'; data ++)
      if (*data == '=')
        break;
      else if (*data >= ' ' && s < (name + sizeof(name) - 1))
        *s++ = *data;

    *s = '\0';
    if (*data == '=')
      data ++;
    else
      return (0);

   /*
    * Read the variable value...
    */

    for (s = value, done = 0; !done && *data != '\0'; data ++)
      switch (*data)
      {
	case '&' :	/* End of data... */
            done = 1;
            break;

	case '+' :	/* Escaped space character */
            if (s < (value + sizeof(value) - 1))
              *s++ = ' ';
            break;

	case '%' :	/* Escaped control character */
	   /*
	    * Read the hex code...
	    */

            if (s < (value + sizeof(value) - 1))
	    {
              data ++;
              ch = *data - '0';
              if (ch > 9)
        	ch -= 7;
              *s = ch << 4;

              data ++;
              ch = *data - '0';
              if (ch > 9)
        	ch -= 7;
              *s++ |= ch;
            }
	    else
	      data += 2;
            break;

	default :	/* Other characters come straight through */
	    if (*data >= ' ' && s < (value + sizeof(value) - 1))
              *s++ = *data;
            break;
      }

    *s = '\0';		/* nul terminate the string */

   /*
    * Remove trailing whitespace...
    */

    if (s > value)
      s --;

    while (s >= value && isspace(*s & 255))
      *s-- = '\0';

   /*
    * Add the string to the variable "database"...
    */

    if ((s = strrchr(name, '-')) != NULL && isdigit(s[1] & 255))
    {
      *s++ = '\0';
      if (value[0])
        cgiSetArray(name, atoi(s) - 1, value);
    }
    else if (cgiGetVariable(name) != NULL)
      cgiSetArray(name, cgiGetSize(name), value);
    else
      cgiSetVariable(name, value);
  }

  return (1);
}


/*
 * 'cgi_passwd()' - Catch authentication requests and notify the server.
 *
 * This function sends a Status header and exits, forcing authentication
 * for this request.
 */

static const char *			/* O - NULL (no return) */
cgi_passwd(const char *prompt)		/* I - Prompt (not used) */
{
  (void)prompt;

  fprintf(stderr, "DEBUG: cgi_passwd(prompt=\"%s\") called!\n",
          prompt ? prompt : "(null)");

 /*
  * Send a 401 (unauthorized) status to the server, so it can notify
  * the client that authentication is required.
  */

  puts("Status: 401\n");
  exit(0);

 /*
  * This code is never executed, but is present to satisfy the compiler.
  */

  return (NULL);
}


/*
 * 'cgi_sort_variables()' - Sort all form variables for faster lookup.
 */

static void
cgi_sort_variables(void)
{
#ifdef DEBUG
  int	i;


  DEBUG_puts("cgi_sort_variables: Sorting variables...");
#endif /* DEBUG */

  if (form_count < 2)
    return;

  qsort(form_vars, form_count, sizeof(_cgi_var_t),
        (int (*)(const void *, const void *))cgi_compare_variables);

#ifdef DEBUG
  DEBUG_puts("cgi_sort_variables: Sorted variable list is:");
  for (i = 0; i < form_count; i ++)
    DEBUG_printf(("cgi_sort_variables: %d: %s (%d) = \"%s\" ...\n", i,
                  form_vars[i].name, form_vars[i].nvalues,
		  form_vars[i].values[0]));
#endif /* DEBUG */
}


/*
 * 'cgi_unlink_file()' - Remove the uploaded form.
 */

static void
cgi_unlink_file(void)
{
  if (form_file)
  {
   /*
    * Remove the temporary file...
    */

    unlink(form_file->tempfile);

   /*
    * Free memory used...
    */

    free(form_file->name);
    free(form_file->filename);
    free(form_file->mimetype);
    free(form_file);

    form_file = NULL;
  }
}


/*
 * End of "$Id: var.c 7460 2008-04-16 02:19:54Z mike $".
 */