]>
git.ipfire.org Git - thirdparty/cups.git/blob - cgi-bin/var.c
2 * CGI form variable and array functions for CUPS.
4 * Copyright 2007-2015 by Apple Inc.
5 * Copyright 1997-2005 by Easy Software Products.
7 * Licensed under Apache License v2.0. See the file "LICENSE" for more information.
11 * Include necessary headers...
15 #include "cgi-private.h"
16 #include <cups/http.h>
23 #define CUPS_SID "org.cups.sid"
27 * Data structure to hold all the CGI form variables and arrays...
30 typedef struct /**** Form variable structure ****/
32 const char *name
; /* Name of variable */
33 int nvalues
, /* Number of values */
34 avalues
; /* Number of values allocated */
35 const char **values
; /* Value(s) of variable */
43 static int num_cookies
= 0;/* Number of cookies */
44 static cups_option_t
*cookies
= NULL
;/* Cookies */
45 static int form_count
= 0, /* Form variable count */
46 form_alloc
= 0; /* Number of variables allocated */
47 static _cgi_var_t
*form_vars
= NULL
;
49 static cgi_file_t
*form_file
= NULL
;
57 static void cgi_add_variable(const char *name
, int element
,
59 static int cgi_compare_variables(const _cgi_var_t
*v1
,
60 const _cgi_var_t
*v2
);
61 static _cgi_var_t
*cgi_find_variable(const char *name
);
62 static void cgi_initialize_cookies(void);
63 static int cgi_initialize_get(void);
64 static int cgi_initialize_multipart(const char *boundary
);
65 static int cgi_initialize_post(void);
66 static int cgi_initialize_string(const char *data
);
67 static const char *cgi_passwd(const char *prompt
);
68 static const char *cgi_set_sid(void);
69 static void cgi_sort_variables(void);
70 static void cgi_unlink_file(void);
74 * 'cgiCheckVariables()' - Check for the presence of "required" variables.
76 * Names may be separated by spaces and/or commas.
79 int /* O - 1 if all variables present, 0 otherwise */
80 cgiCheckVariables(const char *names
) /* I - Variables to look for */
82 char name
[255], /* Current variable name */
83 *s
; /* Pointer in string */
84 const char *val
; /* Value of variable */
85 int element
; /* Array element number */
91 while (*names
!= '\0')
93 while (*names
== ' ' || *names
== ',')
96 for (s
= name
; *names
!= '\0' && *names
!= ' ' && *names
!= ','; s
++, names
++)
103 if ((s
= strrchr(name
, '-')) != NULL
)
106 element
= atoi(s
+ 1) - 1;
107 val
= cgiGetArray(name
, element
);
110 val
= cgiGetVariable(name
);
116 return (0); /* Can't be blank, either! */
124 * 'cgiClearVariables()' - Clear all form variables.
128 cgiClearVariables(void)
130 int i
, j
; /* Looping vars */
131 _cgi_var_t
*v
; /* Current variable */
134 fputs("DEBUG: cgiClearVariables called.\n", stderr
);
136 for (v
= form_vars
, i
= form_count
; i
> 0; v
++, i
--)
138 _cupsStrFree(v
->name
);
139 for (j
= 0; j
< v
->nvalues
; j
++)
141 _cupsStrFree(v
->values
[j
]);
151 * 'cgiGetArray()' - Get an element from a form array.
154 const char * /* O - Element value or NULL */
155 cgiGetArray(const char *name
, /* I - Name of array variable */
156 int element
) /* I - Element number (0 to N) */
158 _cgi_var_t
*var
; /* Pointer to variable */
161 if ((var
= cgi_find_variable(name
)) == NULL
)
164 if (element
< 0 || element
>= var
->nvalues
)
167 return (_cupsStrRetain(var
->values
[element
]));
172 * 'cgiGetCookie()' - Get a cookie value.
175 const char * /* O - Value or NULL */
176 cgiGetCookie(const char *name
) /* I - Name of cookie */
178 return (cupsGetOption(name
, num_cookies
, cookies
));
183 * 'cgiGetFile()' - Get the file (if any) that was submitted in the form.
186 const cgi_file_t
* /* O - Attached file or NULL */
194 * 'cgiGetSize()' - Get the size of a form array value.
197 int /* O - Number of elements */
198 cgiGetSize(const char *name
) /* I - Name of variable */
200 _cgi_var_t
*var
; /* Pointer to variable */
203 if ((var
= cgi_find_variable(name
)) == NULL
)
206 return (var
->nvalues
);
211 * 'cgiGetVariable()' - Get a CGI variable from the database.
213 * Returns NULL if the variable doesn't exist. If the variable is an
214 * array of values, returns the last element.
217 const char * /* O - Value of variable */
218 cgiGetVariable(const char *name
) /* I - Name of variable */
220 const _cgi_var_t
*var
; /* Returned variable */
223 var
= cgi_find_variable(name
);
225 return ((var
== NULL
) ? NULL
: _cupsStrRetain(var
->values
[var
->nvalues
- 1]));
230 * 'cgiInitialize()' - Initialize the CGI variable "database".
233 int /* O - Non-zero if there was form data */
236 const char *method
, /* Form posting method */
237 *content_type
, /* Content-Type of post data */
238 *cups_sid_cookie
, /* SID cookie */
239 *cups_sid_form
; /* SID form variable */
243 * Setup a password callback for authentication...
246 cupsSetPasswordCB(cgi_passwd
);
249 * Set the locale so that times, etc. are formatted properly...
252 setlocale(LC_ALL
, "");
256 * Disable output buffering to find bugs...
259 setbuf(stdout
, NULL
);
266 cgi_initialize_cookies();
268 if ((cups_sid_cookie
= cgiGetCookie(CUPS_SID
)) == NULL
)
270 fputs("DEBUG: " CUPS_SID
" cookie not found, initializing!\n", stderr
);
271 cups_sid_cookie
= cgi_set_sid();
274 fprintf(stderr
, "DEBUG: " CUPS_SID
" cookie is \"%s\"\n", cups_sid_cookie
);
277 * Get the request method (GET or POST)...
280 method
= getenv("REQUEST_METHOD");
281 content_type
= getenv("CONTENT_TYPE");
286 * Grab form data from the corresponding location...
289 if (!_cups_strcasecmp(method
, "GET"))
290 return (cgi_initialize_get());
291 else if (!_cups_strcasecmp(method
, "POST") && content_type
)
293 const char *boundary
= strstr(content_type
, "boundary=");
298 if (content_type
&& !strncmp(content_type
, "multipart/form-data; ", 21))
300 if (!cgi_initialize_multipart(boundary
))
303 else if (!cgi_initialize_post())
306 if ((cups_sid_form
= cgiGetVariable(CUPS_SID
)) == NULL
||
307 strcmp(cups_sid_cookie
, cups_sid_form
))
310 fprintf(stderr
, "DEBUG: " CUPS_SID
" form variable is \"%s\"\n",
313 fputs("DEBUG: " CUPS_SID
" form variable is not present.\n", stderr
);
327 * 'cgiIsPOST()' - Determine whether this page was POSTed.
330 int /* O - 1 if POST, 0 if GET */
333 const char *method
; /* REQUEST_METHOD environment variable */
336 if ((method
= getenv("REQUEST_METHOD")) == NULL
)
339 return (!strcmp(method
, "POST"));
344 * 'cgiSetArray()' - Set array element N to the specified string.
346 * If the variable array is smaller than (element + 1), the intervening
347 * elements are set to NULL.
351 cgiSetArray(const char *name
, /* I - Name of variable */
352 int element
, /* I - Element number (0 to N) */
353 const char *value
) /* I - Value of variable */
355 int i
; /* Looping var */
356 _cgi_var_t
*var
; /* Returned variable */
359 if (name
== NULL
|| value
== NULL
|| element
< 0 || element
> 100000)
362 fprintf(stderr
, "DEBUG: cgiSetArray: %s[%d]=\"%s\"\n", name
, element
, value
);
364 if ((var
= cgi_find_variable(name
)) == NULL
)
366 cgi_add_variable(name
, element
, value
);
367 cgi_sort_variables();
371 if (element
>= var
->avalues
)
373 const char **temp
; /* Temporary pointer */
375 temp
= (const char **)realloc((void *)(var
->values
),
376 sizeof(char *) * (size_t)(element
+ 16));
380 var
->avalues
= element
+ 16;
384 if (element
>= var
->nvalues
)
386 for (i
= var
->nvalues
; i
< element
; i
++)
387 var
->values
[i
] = NULL
;
389 var
->nvalues
= element
+ 1;
391 else if (var
->values
[element
])
392 _cupsStrFree((char *)var
->values
[element
]);
394 var
->values
[element
] = _cupsStrAlloc(value
);
400 * 'cgiSetCookie()' - Set a cookie value.
404 cgiSetCookie(const char *name
, /* I - Name */
405 const char *value
, /* I - Value */
406 const char *path
, /* I - Path (typically "/") */
407 const char *domain
, /* I - Domain name */
408 time_t expires
, /* I - Expiration date (0 for session) */
409 int secure
) /* I - Require SSL */
411 num_cookies
= cupsAddOption(name
, value
, num_cookies
, &cookies
);
413 printf("Set-Cookie: %s=%s;", name
, value
);
415 printf(" path=%s;", path
);
417 printf(" domain=%s;", domain
);
420 char date
[256]; /* Date string */
422 printf(" expires=%s;", httpGetDateString2(expires
, date
, sizeof(date
)));
425 puts(" httponly; secure;");
432 * 'cgiSetSize()' - Set the array size.
436 cgiSetSize(const char *name
, /* I - Name of variable */
437 int size
) /* I - Number of elements (0 to N) */
439 int i
; /* Looping var */
440 _cgi_var_t
*var
; /* Returned variable */
443 if (name
== NULL
|| size
< 0 || size
> 100000)
446 if ((var
= cgi_find_variable(name
)) == NULL
)
449 if (size
>= var
->avalues
)
451 const char **temp
; /* Temporary pointer */
453 temp
= (const char **)realloc((void *)(var
->values
),
454 sizeof(char *) * (size_t)(size
+ 16));
458 var
->avalues
= size
+ 16;
462 if (size
> var
->nvalues
)
464 for (i
= var
->nvalues
; i
< size
; i
++)
465 var
->values
[i
] = NULL
;
467 else if (size
< var
->nvalues
)
469 for (i
= size
; i
< var
->nvalues
; i
++)
471 _cupsStrFree((void *)(var
->values
[i
]));
479 * 'cgiSetVariable()' - Set a CGI variable in the database.
481 * If the variable is an array, this truncates the array to a single element.
485 cgiSetVariable(const char *name
, /* I - Name of variable */
486 const char *value
) /* I - Value of variable */
488 int i
; /* Looping var */
489 _cgi_var_t
*var
; /* Returned variable */
492 if (name
== NULL
|| value
== NULL
)
495 fprintf(stderr
, "cgiSetVariable: %s=\"%s\"\n", name
, value
);
497 if ((var
= cgi_find_variable(name
)) == NULL
)
499 cgi_add_variable(name
, 0, value
);
500 cgi_sort_variables();
504 for (i
= 0; i
< var
->nvalues
; i
++)
506 _cupsStrFree((char *)var
->values
[i
]);
508 var
->values
[0] = _cupsStrAlloc(value
);
515 * 'cgi_add_variable()' - Add a form variable.
519 cgi_add_variable(const char *name
, /* I - Variable name */
520 int element
, /* I - Array element number */
521 const char *value
) /* I - Variable value */
523 _cgi_var_t
*var
; /* New variable */
526 if (name
== NULL
|| value
== NULL
|| element
< 0 || element
> 100000)
529 if (form_count
>= form_alloc
)
531 _cgi_var_t
*temp_vars
; /* Temporary form pointer */
535 temp_vars
= malloc(sizeof(_cgi_var_t
) * 16);
537 temp_vars
= realloc(form_vars
, (size_t)(form_alloc
+ 16) * sizeof(_cgi_var_t
));
542 form_vars
= temp_vars
;
546 var
= form_vars
+ form_count
;
548 if ((var
->values
= calloc((size_t)element
+ 1, sizeof(char *))) == NULL
)
551 var
->name
= _cupsStrAlloc(name
);
552 var
->nvalues
= element
+ 1;
553 var
->avalues
= element
+ 1;
554 var
->values
[element
] = _cupsStrAlloc(value
);
561 * 'cgi_compare_variables()' - Compare two variables.
564 static int /* O - Result of comparison */
565 cgi_compare_variables(
566 const _cgi_var_t
*v1
, /* I - First variable */
567 const _cgi_var_t
*v2
) /* I - Second variable */
569 return (_cups_strcasecmp(v1
->name
, v2
->name
));
574 * 'cgi_find_variable()' - Find a variable.
577 static _cgi_var_t
* /* O - Variable pointer or NULL */
578 cgi_find_variable(const char *name
) /* I - Name of variable */
580 _cgi_var_t key
; /* Search key */
583 if (form_count
< 1 || name
== NULL
)
588 return ((_cgi_var_t
*)bsearch(&key
, form_vars
, (size_t)form_count
, sizeof(_cgi_var_t
),
589 (int (*)(const void *, const void *))cgi_compare_variables
));
594 * 'cgi_initialize_cookies()' - Initialize cookies.
598 cgi_initialize_cookies(void)
600 const char *cookie
; /* HTTP_COOKIE environment variable */
601 char name
[128], /* Name string */
602 value
[512], /* Value string */
603 *ptr
; /* Pointer into name/value */
606 if ((cookie
= getenv("HTTP_COOKIE")) == NULL
)
611 int skip
= 0; /* Skip this cookie? */
614 * Skip leading whitespace...
617 while (isspace(*cookie
& 255))
626 for (ptr
= name
; *cookie
&& *cookie
!= '=';)
627 if (ptr
< (name
+ sizeof(name
) - 1))
649 for (cookie
++, ptr
= value
; *cookie
&& *cookie
!= '\"';)
650 if (ptr
< (value
+ sizeof(value
) - 1))
667 for (ptr
= value
; *cookie
&& *cookie
!= ';';)
668 if (ptr
< (value
+ sizeof(value
) - 1))
687 * Then add the cookie to an array as long as the name doesn't start with
691 if (name
[0] != '$' && !skip
)
692 num_cookies
= cupsAddOption(name
, value
, num_cookies
, &cookies
);
698 * 'cgi_initialize_get()' - Initialize form variables using the GET method.
701 static int /* O - 1 if form data read */
702 cgi_initialize_get(void)
704 char *data
; /* Pointer to form data string */
708 * Check to see if there is anything for us to read...
711 data
= getenv("QUERY_STRING");
712 if (data
== NULL
|| strlen(data
) == 0)
716 * Parse it out and return...
719 return (cgi_initialize_string(data
));
724 * 'cgi_initialize_multipart()' - Initialize variables and file using the POST
727 * TODO: Update to support files > 2GB.
730 static int /* O - 1 if form data was read */
731 cgi_initialize_multipart(
732 const char *boundary
) /* I - Boundary string */
734 char line
[10240], /* MIME header line */
735 name
[1024], /* Form variable name */
736 filename
[1024], /* Form filename */
737 mimetype
[1024], /* MIME media type */
738 bstring
[256], /* Boundary string to look for */
739 *ptr
, /* Pointer into name/filename */
740 *end
; /* End of buffer */
741 int ch
, /* Character from file */
742 fd
; /* Temporary file descriptor */
743 size_t blen
; /* Length of boundary string */
747 * Read multipart form data until we run out...
754 snprintf(bstring
, sizeof(bstring
), "\r\n--%s", boundary
);
755 blen
= strlen(bstring
);
757 while (fgets(line
, sizeof(line
), stdin
))
759 if (!strcmp(line
, "\r\n"))
762 * End of headers, grab value...
768 * Read an embedded file...
774 * Remove previous file...
781 * Allocate memory for the new file...
784 if ((form_file
= calloc(1, sizeof(cgi_file_t
))) == NULL
)
787 form_file
->name
= strdup(name
);
788 form_file
->filename
= strdup(filename
);
789 form_file
->mimetype
= strdup(mimetype
);
791 fd
= cupsTempFd(form_file
->tempfile
, sizeof(form_file
->tempfile
));
796 atexit(cgi_unlink_file
);
799 * Copy file data to the temp file...
804 while ((ch
= getchar()) != EOF
)
808 if ((size_t)(ptr
- line
) >= blen
&& !memcmp(ptr
- blen
, bstring
, blen
))
814 if ((ptr
- line
- (int)blen
) >= 8192)
817 * Write out the first 8k of the buffer...
820 write(fd
, line
, 8192);
821 memmove(line
, line
+ 8192, (size_t)(ptr
- line
- 8192));
827 * Write the rest of the data and close the temp file...
831 write(fd
, line
, (size_t)(ptr
- line
));
838 * Just get a form variable; the current code only handles
839 * form values up to 10k in size...
843 end
= line
+ sizeof(line
) - 1;
845 while ((ch
= getchar()) != EOF
)
850 if ((size_t)(ptr
- line
) >= blen
&& !memcmp(ptr
- blen
, bstring
, blen
))
860 * Set the form variable...
863 if ((ptr
= strrchr(name
, '-')) != NULL
&& isdigit(ptr
[1] & 255))
866 * Set a specific index in the array...
871 cgiSetArray(name
, atoi(ptr
) - 1, line
);
873 else if (cgiGetVariable(name
))
876 * Add another element in the array...
879 cgiSetArray(name
, cgiGetSize(name
), line
);
884 * Just set the line...
887 cgiSetVariable(name
, line
);
892 * Read the rest of the current line...
895 fgets(line
, sizeof(line
), stdin
);
898 * Clear the state vars...
905 else if (!_cups_strncasecmp(line
, "Content-Disposition:", 20))
907 if ((ptr
= strstr(line
+ 20, " name=\"")) != NULL
)
909 strlcpy(name
, ptr
+ 7, sizeof(name
));
911 if ((ptr
= strchr(name
, '\"')) != NULL
)
915 if ((ptr
= strstr(line
+ 20, " filename=\"")) != NULL
)
917 strlcpy(filename
, ptr
+ 11, sizeof(filename
));
919 if ((ptr
= strchr(filename
, '\"')) != NULL
)
923 else if (!_cups_strncasecmp(line
, "Content-Type:", 13))
925 for (ptr
= line
+ 13; isspace(*ptr
& 255); ptr
++);
927 strlcpy(mimetype
, ptr
, sizeof(mimetype
));
929 for (ptr
= mimetype
+ strlen(mimetype
) - 1;
930 ptr
> mimetype
&& isspace(*ptr
& 255);
936 * Return 1 for "form data found"...
944 * 'cgi_initialize_post()' - Initialize variables using the POST method.
947 static int /* O - 1 if form data was read */
948 cgi_initialize_post(void)
950 char *content_length
, /* Length of input data (string) */
951 *data
; /* Pointer to form data string */
952 size_t length
, /* Length of input data */
953 tbytes
; /* Total number of bytes read */
954 ssize_t nbytes
; /* Number of bytes read this read() */
955 int status
; /* Return status */
959 * Check to see if there is anything for us to read...
962 content_length
= getenv("CONTENT_LENGTH");
963 if (content_length
== NULL
|| atoi(content_length
) <= 0)
967 * Get the length of the input stream and allocate a buffer for it...
970 length
= (size_t)strtol(content_length
, NULL
, 10);
971 data
= malloc(length
+ 1);
977 * Read the data into the buffer...
980 for (tbytes
= 0; tbytes
< length
; tbytes
+= (size_t)nbytes
)
981 if ((nbytes
= read(0, data
+ tbytes
, (size_t)(length
- tbytes
))) < 0)
991 else if (nbytes
== 0)
994 * CUPS STR #3176: OpenBSD: Early end-of-file on POST data causes 100% CPU
996 * This should never happen, but does on OpenBSD. If we see early end-of-
997 * file, treat this as an error and process no data.
1004 data
[length
] = '\0';
1010 status
= cgi_initialize_string(data
);
1013 * Free the data and return...
1023 * 'cgi_initialize_string()' - Initialize form variables from a string.
1026 static int /* O - 1 if form data was processed */
1027 cgi_initialize_string(const char *data
) /* I - Form data string */
1029 int done
; /* True if we're done reading a form variable */
1030 char *s
, /* Pointer to current form string */
1031 ch
, /* Temporary character */
1032 name
[255], /* Name of form variable */
1033 value
[65536]; /* Variable value */
1044 * Loop until we've read all the form data...
1047 while (*data
!= '\0')
1050 * Get the variable name...
1053 for (s
= name
; *data
!= '\0'; data
++)
1056 else if (*data
>= ' ' && s
< (name
+ sizeof(name
) - 1))
1066 * Read the variable value...
1069 for (s
= value
, done
= 0; !done
&& *data
!= '\0'; data
++)
1072 case '&' : /* End of data... */
1076 case '+' : /* Escaped space character */
1077 if (s
< (value
+ sizeof(value
) - 1))
1081 case '%' : /* Escaped control character */
1083 * Read the hex code...
1086 if (!isxdigit(data
[1] & 255) || !isxdigit(data
[2] & 255))
1089 if (s
< (value
+ sizeof(value
) - 1))
1095 *s
= (char)(ch
<< 4);
1107 default : /* Other characters come straight through */
1108 if (*data
>= ' ' && s
< (value
+ sizeof(value
) - 1))
1113 *s
= '\0'; /* nul terminate the string */
1116 * Remove trailing whitespace...
1122 while (s
>= value
&& isspace(*s
& 255))
1126 * Add the string to the variable "database"...
1129 if ((s
= strrchr(name
, '-')) != NULL
&& isdigit(s
[1] & 255))
1133 cgiSetArray(name
, atoi(s
) - 1, value
);
1135 else if (cgiGetVariable(name
) != NULL
)
1136 cgiSetArray(name
, cgiGetSize(name
), value
);
1138 cgiSetVariable(name
, value
);
1146 * 'cgi_passwd()' - Catch authentication requests and notify the server.
1148 * This function sends a Status header and exits, forcing authentication
1152 static const char * /* O - NULL (no return) */
1153 cgi_passwd(const char *prompt
) /* I - Prompt (not used) */
1157 fprintf(stderr
, "DEBUG: cgi_passwd(prompt=\"%s\") called!\n",
1158 prompt
? prompt
: "(null)");
1161 * Send a 401 (unauthorized) status to the server, so it can notify
1162 * the client that authentication is required.
1165 puts("Status: 401\n");
1169 * This code is never executed, but is present to satisfy the compiler.
1177 * 'cgi_set_sid()' - Set the CUPS session ID.
1180 static const char * /* O - New session ID */
1183 char buffer
[512], /* SID data */
1184 sid
[33]; /* SID string */
1185 unsigned char sum
[16]; /* MD5 sum */
1186 const char *remote_addr
, /* REMOTE_ADDR */
1187 *server_name
, /* SERVER_NAME */
1188 *server_port
; /* SERVER_PORT */
1191 if ((remote_addr
= getenv("REMOTE_ADDR")) == NULL
)
1192 remote_addr
= "REMOTE_ADDR";
1193 if ((server_name
= getenv("SERVER_NAME")) == NULL
)
1194 server_name
= "SERVER_NAME";
1195 if ((server_port
= getenv("SERVER_PORT")) == NULL
)
1196 server_port
= "SERVER_PORT";
1198 CUPS_SRAND(time(NULL
));
1199 snprintf(buffer
, sizeof(buffer
), "%s:%s:%s:%02X%02X%02X%02X%02X%02X%02X%02X",
1200 remote_addr
, server_name
, server_port
,
1201 (unsigned)CUPS_RAND() & 255, (unsigned)CUPS_RAND() & 255,
1202 (unsigned)CUPS_RAND() & 255, (unsigned)CUPS_RAND() & 255,
1203 (unsigned)CUPS_RAND() & 255, (unsigned)CUPS_RAND() & 255,
1204 (unsigned)CUPS_RAND() & 255, (unsigned)CUPS_RAND() & 255);
1205 cupsHashData("md5", (unsigned char *)buffer
, strlen(buffer
), sum
, sizeof(sum
));
1207 cgiSetCookie(CUPS_SID
, cupsHashString(sum
, sizeof(sum
), sid
, sizeof(sid
)), "/", NULL
, 0, 0);
1209 return (cupsGetOption(CUPS_SID
, num_cookies
, cookies
));
1214 * 'cgi_sort_variables()' - Sort all form variables for faster lookup.
1218 cgi_sort_variables(void)
1223 qsort(form_vars
, (size_t)form_count
, sizeof(_cgi_var_t
),
1224 (int (*)(const void *, const void *))cgi_compare_variables
);
1229 * 'cgi_unlink_file()' - Remove the uploaded form.
1233 cgi_unlink_file(void)
1238 * Remove the temporary file...
1241 unlink(form_file
->tempfile
);
1244 * Free memory used...
1247 free(form_file
->name
);
1248 free(form_file
->filename
);
1249 free(form_file
->mimetype
);