Fossil SCM

fossil-scm / src / cgi.c
Source Blame History 3105 lines
dbda8d6… drh 1 /*
c19f34c… drh 2 ** Copyright (c) 2006 D. Richard Hipp
dbda8d6… drh 3 **
dbda8d6… drh 4 ** This program is free software; you can redistribute it and/or
c06edd2… drh 5 ** modify it under the terms of the Simplified BSD License (also
c06edd2… drh 6 ** known as the "2-Clause License" or "FreeBSD License".)
d8ec765… drh 7 **
dbda8d6… drh 8 ** This program is distributed in the hope that it will be useful,
c06edd2… drh 9 ** but without any warranty; without even the implied warranty of
c06edd2… drh 10 ** merchantability or fitness for a particular purpose.
dbda8d6… drh 11 **
dbda8d6… drh 12 ** Author contact information:
dbda8d6… drh 13 ** [email protected]
dbda8d6… drh 14 ** http://www.hwaci.com/drh/
dbda8d6… drh 15 **
dbda8d6… drh 16 *******************************************************************************
dbda8d6… drh 17 **
33d3bf3… km 18 ** This file began as a set of C functions and procedures used to interpret
37ccaaf… drh 19 ** CGI environment variables for Fossil web pages that were invoked by
37ccaaf… drh 20 ** CGI. That's where the file name comes from. But over the years it
37ccaaf… drh 21 ** has grown to incorporate lots of related functionality, including:
37ccaaf… drh 22 **
37ccaaf… drh 23 ** * Interpreting CGI environment variables when Fossil is run as
37ccaaf… drh 24 ** CGI (the original purpose).
37ccaaf… drh 25 **
37ccaaf… drh 26 ** * Interpreting HTTP requests received directly or via an SSH tunnel.
37ccaaf… drh 27 **
37ccaaf… drh 28 ** * Interpreting SCGI requests
37ccaaf… drh 29 **
37ccaaf… drh 30 ** * Generating appropriate replies to CGI, SCGI, and HTTP requests.
37ccaaf… drh 31 **
37ccaaf… drh 32 ** * Listening for incoming HTTP requests and dispatching them.
37ccaaf… drh 33 ** (Used by "fossil ui" and "fossil server", for example).
37ccaaf… drh 34 **
37ccaaf… drh 35 ** So, even though the name of this file implies that it only deals with
37ccaaf… drh 36 ** CGI, in fact, the code in this file is used to interpret webpage requests
37ccaaf… drh 37 ** received by a variety of means, and to generate well-formatted replies
37ccaaf… drh 38 ** to those requests.
37ccaaf… drh 39 **
37ccaaf… drh 40 ** The code in this file abstracts the web-request so that downstream
37ccaaf… drh 41 ** modules that generate the body of the reply (based on the requested page)
275da70… danield 42 ** do not need to know if the request is coming from CGI, direct HTTP,
37ccaaf… drh 43 ** SCGI, or some other means.
37ccaaf… drh 44 **
37ccaaf… drh 45 ** This module gathers information about web page request into a key/value
37ccaaf… drh 46 ** store. Keys and values come from:
37ccaaf… drh 47 **
37ccaaf… drh 48 ** * Query parameters
37ccaaf… drh 49 ** * POST parameter
37ccaaf… drh 50 ** * Cookies
37ccaaf… drh 51 ** * Environment variables
37ccaaf… drh 52 **
37ccaaf… drh 53 ** The parameters are accessed using cgi_parameter() and similar functions
37ccaaf… drh 54 ** or their convenience macros P() and similar.
37ccaaf… drh 55 **
37ccaaf… drh 56 ** Environment variable parameters are set as if the request were coming
37ccaaf… drh 57 ** in over CGI even if the request arrived via SCGI or direct HTTP. Thus
37ccaaf… drh 58 ** the downstream modules that are trying to interpret the request do not
37ccaaf… drh 59 ** need to know the request protocol - they can just request the values
37ccaaf… drh 60 ** of environment variables and everything will always work.
ec56c69… drh 61 **
ec56c69… drh 62 ** This file contains routines used by Fossil when it is acting as a
ec56c69… drh 63 ** CGI client. For the code used by Fossil when it is acting as a
ec56c69… drh 64 ** CGI server (for the /ext webpage) see the "extcgi.c" source file.
dbda8d6… drh 65 */
dbda8d6… drh 66 #include "config.h"
3564af0… drh 67 #ifdef _WIN32
26a88f1… mistachkin 68 # if !defined(_WIN32_WINNT)
26a88f1… mistachkin 69 # define _WIN32_WINNT 0x0501
26a88f1… mistachkin 70 # endif
0658068… jan.nijtmans 71 # include <winsock2.h>
bb85c12… mistachkin 72 # include <ws2tcpip.h>
d0305b3… aku 73 #else
ab0a0d7… drh 74 # include <sys/socket.h>
7fc2902… drh 75 # include <sys/un.h>
ab0a0d7… drh 76 # include <netinet/in.h>
7ce8400… drh 77 # include <netdb.h>
ab0a0d7… drh 78 # include <arpa/inet.h>
ab0a0d7… drh 79 # include <sys/times.h>
ab0a0d7… drh 80 # include <sys/time.h>
ab0a0d7… drh 81 # include <sys/wait.h>
ab0a0d7… drh 82 # include <sys/select.h>
7fc2902… drh 83 # include <errno.h>
df97fae… drh 84 #endif
df97fae… drh 85 #ifdef __EMX__
ab0a0d7… drh 86 typedef int socklen_t;
d0305b3… aku 87 #endif
dbda8d6… drh 88 #include <time.h>
dbda8d6… drh 89 #include <stdio.h>
dbda8d6… drh 90 #include <stdlib.h>
dbda8d6… drh 91 #include <unistd.h>
f6263bb… drh 92 #include <assert.h>
dbda8d6… drh 93 #include "cgi.h"
816e893… mistachkin 94 #include "cygsup.h"
dbda8d6… drh 95
dbda8d6… drh 96 #if INTERFACE
dbda8d6… drh 97 /*
dbda8d6… drh 98 ** Shortcuts for cgi_parameter. P("x") returns the value of query parameter
dbda8d6… drh 99 ** or cookie "x", or NULL if there is no such parameter or cookie. PD("x","y")
dbda8d6… drh 100 ** does the same except "y" is returned in place of NULL if there is not match.
dbda8d6… drh 101 */
534c10f… stephan 102 #define P(x) cgi_parameter((x),0)
534c10f… stephan 103 #define PD(x,y) cgi_parameter((x),(y))
534c10f… stephan 104 #define PT(x) cgi_parameter_trimmed((x),0)
534c10f… stephan 105 #define PDT(x,y) cgi_parameter_trimmed((x),(y))
534c10f… stephan 106 #define PB(x) cgi_parameter_boolean(x)
534c10f… stephan 107 #define PCK(x) cgi_parameter_checked(x,1)
534c10f… stephan 108 #define PIF(x,y) cgi_parameter_checked(x,y)
8612122… drh 109 #define P_NoBot(x) cgi_parameter_no_attack((x),0)
8612122… drh 110 #define PD_NoBot(x,y) cgi_parameter_no_attack((x),(y))
1243bf3… stephan 111
1243bf3… stephan 112 /*
1243bf3… stephan 113 ** Shortcut for the cgi_printf() routine. Instead of using the
1243bf3… stephan 114 **
1243bf3… stephan 115 ** @ ...
1243bf3… stephan 116 **
1243bf3… stephan 117 ** notation provided by the translate.c utility, you can also
1243bf3… stephan 118 ** optionally use:
1243bf3… stephan 119 **
1243bf3… stephan 120 ** CX(...)
1243bf3… stephan 121 */
1243bf3… stephan 122 #define CX cgi_printf
b312f5f… drh 123
b312f5f… drh 124 /*
b312f5f… drh 125 ** Destinations for output text.
b312f5f… drh 126 */
b312f5f… drh 127 #define CGI_HEADER 0
b312f5f… drh 128 #define CGI_BODY 1
b312f5f… drh 129
dbb5e2d… drh 130 /*
dbb5e2d… drh 131 ** Flags for SSH HTTP clients
dbb5e2d… drh 132 */
dbb5e2d… drh 133 #define CGI_SSH_CLIENT 0x0001 /* Client is SSH */
dbb5e2d… drh 134 #define CGI_SSH_COMPAT 0x0002 /* Compat for old SSH transport */
dbb5e2d… drh 135 #define CGI_SSH_FOSSIL 0x0004 /* Use new Fossil SSH transport */
dbb5e2d… drh 136
dbda8d6… drh 137 #endif /* INTERFACE */
dbda8d6… drh 138
dbda8d6… drh 139 /*
37ccaaf… drh 140 ** The reply content is generated in two pieces: the header and the body.
c048aac… andybradford 141 ** These pieces are generated separately because they are not necessarily
b312f5f… drh 142 ** produced in order. Parts of the header might be built after all or
b312f5f… drh 143 ** part of the body. The header and body are accumulated in separate
b312f5f… drh 144 ** Blob structures then output sequentially once everything has been
b312f5f… drh 145 ** built.
37ccaaf… drh 146 **
37ccaaf… drh 147 ** Do not confuse the content header with the HTTP header. The content header
37ccaaf… drh 148 ** is generated by downstream code. The HTTP header is generated by the
37ccaaf… drh 149 ** cgi_reply() routine below.
37ccaaf… drh 150 **
e2bdc10… danield 151 ** The content header and content body are *approximately* the <head>
37ccaaf… drh 152 ** element and the <body> elements for HTML replies. However this is only
37ccaaf… drh 153 ** approximate. The content header also includes parts of <body> that
37ccaaf… drh 154 ** show the banner and menu bar at the top of each page. Also note that
37ccaaf… drh 155 ** not all replies are HTML, but there can still be separate header and
37ccaaf… drh 156 ** body sections of the content.
c048aac… andybradford 157 **
c048aac… andybradford 158 ** The cgi_destination() interface switches between the buffers.
dbda8d6… drh 159 */
b312f5f… drh 160 static Blob cgiContent[2] = { BLOB_INITIALIZER, BLOB_INITIALIZER };
0a14f18… drh 161 static Blob *pContent = &cgiContent[0];
dbda8d6… drh 162
dbda8d6… drh 163 /*
b312f5f… drh 164 ** Set the destination buffer into which to accumulate CGI content.
dbda8d6… drh 165 */
b312f5f… drh 166 void cgi_destination(int dest){
b312f5f… drh 167 switch( dest ){
b312f5f… drh 168 case CGI_HEADER: {
b312f5f… drh 169 pContent = &cgiContent[0];
b312f5f… drh 170 break;
b312f5f… drh 171 }
b312f5f… drh 172 case CGI_BODY: {
b312f5f… drh 173 pContent = &cgiContent[1];
b312f5f… drh 174 break;
b312f5f… drh 175 }
b312f5f… drh 176 default: {
b312f5f… drh 177 cgi_panic("bad destination");
b312f5f… drh 178 }
b312f5f… drh 179 }
b312f5f… drh 180 }
dbda8d6… drh 181
dbda8d6… drh 182 /*
37ccaaf… drh 183 ** Check to see if the content header or body contains the zNeedle string.
37ccaaf… drh 184 ** Return true if it does and false if it does not.
65870e8… drh 185 */
65870e8… drh 186 int cgi_header_contains(const char *zNeedle){
65870e8… drh 187 return strstr(blob_str(&cgiContent[0]), zNeedle)!=0;
65870e8… drh 188 }
ff78d6d… drh 189 int cgi_body_contains(const char *zNeedle){
ff78d6d… drh 190 return strstr(blob_str(&cgiContent[1]), zNeedle)!=0;
ff78d6d… drh 191 }
65870e8… drh 192
65870e8… drh 193 /*
37ccaaf… drh 194 ** Append new reply content to what already exists.
dbda8d6… drh 195 */
dbda8d6… drh 196 void cgi_append_content(const char *zData, int nAmt){
b312f5f… drh 197 blob_append(pContent, zData, nAmt);
dbda8d6… drh 198 }
dbda8d6… drh 199
dbda8d6… drh 200 /*
37ccaaf… drh 201 ** Reset both reply content buffers to be empty.
dbda8d6… drh 202 */
dbda8d6… drh 203 void cgi_reset_content(void){
b312f5f… drh 204 blob_reset(&cgiContent[0]);
b312f5f… drh 205 blob_reset(&cgiContent[1]);
dbda8d6… drh 206 }
dbda8d6… drh 207
dbda8d6… drh 208 /*
37ccaaf… drh 209 ** Return a pointer to Blob that is currently accumulating reply content.
dbda8d6… drh 210 */
f5e8b1d… drh 211 Blob *cgi_output_blob(void){
b312f5f… drh 212 return pContent;
f5e8b1d… drh 213 }
f5e8b1d… drh 214
f5e8b1d… drh 215 /*
37ccaaf… drh 216 ** Return the content header as a text string
9cf90a4… drh 217 */
9cf90a4… drh 218 const char *cgi_header(void){
9cf90a4… drh 219 return blob_str(&cgiContent[0]);
9cf90a4… drh 220 }
9cf90a4… drh 221
9cf90a4… drh 222 /*
37ccaaf… drh 223 ** Combine the header and body content all into the header buffer.
37ccaaf… drh 224 ** In other words, append the body content to the end of the header
37ccaaf… drh 225 ** content.
b312f5f… drh 226 */
b312f5f… drh 227 static void cgi_combine_header_and_body(void){
b312f5f… drh 228 int size = blob_size(&cgiContent[1]);
b312f5f… drh 229 if( size>0 ){
b312f5f… drh 230 blob_append(&cgiContent[0], blob_buffer(&cgiContent[1]), size);
b312f5f… drh 231 blob_reset(&cgiContent[1]);
b312f5f… drh 232 }
b312f5f… drh 233 }
b312f5f… drh 234
b312f5f… drh 235 /*
37ccaaf… drh 236 ** Return a pointer to the combined header+body content.
b312f5f… drh 237 */
d8bbe4a… drh 238 char *cgi_extract_content(void){
b312f5f… drh 239 cgi_combine_header_and_body();
b312f5f… drh 240 return blob_buffer(&cgiContent[0]);
dbda8d6… drh 241 }
dbda8d6… drh 242
dbda8d6… drh 243 /*
dbda8d6… drh 244 ** Additional information used to form the HTTP reply
dbda8d6… drh 245 */
ae8fc0e… drh 246 static const char *zReplyMimeType = "text/html"; /* Content type of the reply */
a6003f1… drh 247 static const char *zReplyStatus = "OK"; /* Reply status description */
dbda8d6… drh 248 static int iReplyStatus = 200; /* Reply status code */
dbda8d6… drh 249 static Blob extraHeader = BLOB_INITIALIZER; /* Extra header text */
b6892cc… drh 250 static int rangeStart = 0; /* Start of Range: */
b6892cc… drh 251 static int rangeEnd = 0; /* End of Range: plus 1 */
dbda8d6… drh 252
dbda8d6… drh 253 /*
37ccaaf… drh 254 ** Set the reply content type.
37ccaaf… drh 255 **
37ccaaf… drh 256 ** The reply content type defaults to "text/html". It only needs to be
37ccaaf… drh 257 ** changed (by calling this routine) in the exceptional case where some
37ccaaf… drh 258 ** other content type is being returned.
dbda8d6… drh 259 */
dbda8d6… drh 260 void cgi_set_content_type(const char *zType){
ae8fc0e… drh 261 int i;
9d7c15d… drh 262 for(i=0; zType[i]>='+' && zType[i]<='z'; i++){}
ae8fc0e… drh 263 zReplyMimeType = fossil_strndup(zType, i);
6dab614… drh 264 }
6dab614… drh 265
6dab614… drh 266 /*
37ccaaf… drh 267 ** Erase any existing reply content. Replace is with a pNewContent.
37ccaaf… drh 268 **
37ccaaf… drh 269 ** This routine erases pNewContent. In other words, it move pNewContent
37ccaaf… drh 270 ** into the content buffer.
6dab614… drh 271 */
6dab614… drh 272 void cgi_set_content(Blob *pNewContent){
b312f5f… drh 273 cgi_reset_content();
b312f5f… drh 274 cgi_destination(CGI_HEADER);
b312f5f… drh 275 cgiContent[0] = *pNewContent;
6dab614… drh 276 blob_zero(pNewContent);
dbda8d6… drh 277 }
dbda8d6… drh 278
dbda8d6… drh 279 /*
dbda8d6… drh 280 ** Set the reply status code
dbda8d6… drh 281 */
dbda8d6… drh 282 void cgi_set_status(int iStat, const char *zStat){
140cb31… drh 283 zReplyStatus = fossil_strdup(zStat);
dbda8d6… drh 284 iReplyStatus = iStat;
dbda8d6… drh 285 }
dbda8d6… drh 286
dbda8d6… drh 287 /*
37ccaaf… drh 288 ** Append text to the content header buffer.
dbda8d6… drh 289 */
dbda8d6… drh 290 void cgi_append_header(const char *zLine){
dbda8d6… drh 291 blob_append(&extraHeader, zLine, -1);
14c81d9… drh 292 }
14c81d9… drh 293 void cgi_printf_header(const char *zLine, ...){
14c81d9… drh 294 va_list ap;
14c81d9… drh 295 va_start(ap, zLine);
14c81d9… drh 296 blob_vappendf(&extraHeader, zLine, ap);
14c81d9… drh 297 va_end(ap);
f488a5a… stephan 298 }
dbda8d6… drh 299
dbda8d6… drh 300 /*
f488a5a… stephan 301 ** Set a cookie by queuing up the appropriate HTTP header output. If
f488a5a… stephan 302 ** !g.isHTTP, this is a no-op.
dbda8d6… drh 303 **
6b7b323… drh 304 ** Zero lifetime implies a session cookie. A negative one expires
6b7b323… drh 305 ** the cookie immediately.
dbda8d6… drh 306 */
dbda8d6… drh 307 void cgi_set_cookie(
dbda8d6… drh 308 const char *zName, /* Name of the cookie */
dbda8d6… drh 309 const char *zValue, /* Value of the cookie. Automatically escaped */
dbda8d6… drh 310 const char *zPath, /* Path cookie applies to. NULL means "/" */
dbda8d6… drh 311 int lifetime /* Expiration of the cookie in seconds from now */
dbda8d6… drh 312 ){
f488a5a… stephan 313 char const *zSecure = "";
f488a5a… stephan 314 if(!g.isHTTP) return /* e.g. JSON CLI mode, where g.zTop is not set */;
f488a5a… stephan 315 else if( zPath==0 ){
0a1f4ed… drh 316 zPath = g.zTop;
0a1f4ed… drh 317 if( zPath[0]==0 ) zPath = "/";
0a1f4ed… drh 318 }
7fcb462… stephan 319 if( g.zBaseURL!=0 && fossil_strncmp(g.zBaseURL, "https:", 6)==0 ){
474850c… drh 320 zSecure = " secure;";
474850c… drh 321 }
6b7b323… drh 322 if( lifetime!=0 ){
dbda8d6… drh 323 blob_appendf(&extraHeader,
920ace1… drh 324 "Set-Cookie: %s=%t; Path=%s; max-age=%d; HttpOnly; %s\r\n",
6b7b323… drh 325 zName, lifetime>0 ? zValue : "null", zPath, lifetime, zSecure);
dbda8d6… drh 326 }else{
dbda8d6… drh 327 blob_appendf(&extraHeader,
920ace1… drh 328 "Set-Cookie: %s=%t; Path=%s; HttpOnly; %s\r\n",
474850c… drh 329 zName, zValue, zPath, zSecure);
474850c… drh 330 }
474850c… drh 331 }
474850c… drh 332
3f4b5d3… joel 333
3f4b5d3… joel 334 /*
3f4b5d3… joel 335 ** Return true if the response should be sent with Content-Encoding: gzip.
3f4b5d3… joel 336 */
3f4b5d3… joel 337 static int is_gzippable(void){
cfc7aca… drh 338 if( g.fNoHttpCompress ) return 0;
3f4b5d3… joel 339 if( strstr(PD("HTTP_ACCEPT_ENCODING", ""), "gzip")==0 ) return 0;
7fcb462… stephan 340 /* Maintenance note: this oddball structure is intended to make
7fcb462… stephan 341 ** adding new mimetypes to this list less of a performance hit than
7fcb462… stephan 342 ** doing a strcmp/glob over a growing set of compressible types. */
ae8fc0e… drh 343 switch(zReplyMimeType ? *zReplyMimeType : 0){
7fcb462… stephan 344 case (int)'a':
ae8fc0e… drh 345 if(0==fossil_strncmp("application/",zReplyMimeType,12)){
ae8fc0e… drh 346 const char * z = &zReplyMimeType[12];
7fcb462… stephan 347 switch(*z){
7fcb462… stephan 348 case (int)'j':
7fcb462… stephan 349 return fossil_strcmp("javascript", z)==0
7fcb462… stephan 350 || fossil_strcmp("json", z)==0;
7fcb462… stephan 351 case (int)'w': return fossil_strcmp("wasm", z)==0;
7fcb462… stephan 352 case (int)'x':
7fcb462… stephan 353 return fossil_strcmp("x-tcl", z)==0
7fcb462… stephan 354 || fossil_strcmp("x-tar", z)==0;
7fcb462… stephan 355 default:
7fcb462… stephan 356 return sqlite3_strglob("*xml", z)==0;
7fcb462… stephan 357 }
7fcb462… stephan 358 }
7fcb462… stephan 359 break;
7fcb462… stephan 360 case (int)'i':
ae8fc0e… drh 361 return fossil_strcmp(zReplyMimeType, "image/svg+xml")==0
ae8fc0e… drh 362 || fossil_strcmp(zReplyMimeType, "image/vnd.microsoft.icon")==0;
7fcb462… stephan 363 case (int)'t':
ae8fc0e… drh 364 return fossil_strncmp(zReplyMimeType, "text/", 5)==0;
7fcb462… stephan 365 }
7fcb462… stephan 366 return 0;
f6263bb… drh 367 }
f6263bb… drh 368
f6263bb… drh 369
f6263bb… drh 370 /*
f6263bb… drh 371 ** The following routines read or write content from/to the wire for
f6263bb… drh 372 ** an HTTP request. Depending on settings the content might be coming
f6263bb… drh 373 ** from or going to a socket, or a file, or it might come from or go
f6263bb… drh 374 ** to an SSL decoder/encoder.
f6263bb… drh 375 */
f6263bb… drh 376 /*
f6263bb… drh 377 ** Works like fgets():
f6263bb… drh 378 **
f6263bb… drh 379 ** Read a single line of input into s[]. Ensure that s[] is zero-terminated.
f6263bb… drh 380 ** The s[] buffer is size bytes and so at most size-1 bytes will be read.
f6263bb… drh 381 **
f6263bb… drh 382 ** Return a pointer to s[] on success, or NULL at end-of-input.
f6263bb… drh 383 */
f6263bb… drh 384 static char *cgi_fgets(char *s, int size){
f6263bb… drh 385 if( !g.httpUseSSL ){
f6263bb… drh 386 return fgets(s, size, g.httpIn);
f6263bb… drh 387 }
f6263bb… drh 388 #ifdef FOSSIL_ENABLE_SSL
f6263bb… drh 389 return ssl_gets(g.httpSSLConn, s, size);
f6263bb… drh 390 #else
f6263bb… drh 391 fossil_fatal("SSL not available");
f6263bb… drh 392 #endif
f6263bb… drh 393 }
f6263bb… drh 394
f6263bb… drh 395 /* Works like fread():
f6263bb… drh 396 **
f6263bb… drh 397 ** Read as many as bytes of content as we can, up to a maximum of nmemb
b0834be… stephan 398 ** bytes. Return the number of bytes read. Return 0 if there is no
f6263bb… drh 399 ** further input or if an I/O error occurs.
f6263bb… drh 400 */
f6263bb… drh 401 size_t cgi_fread(void *ptr, size_t nmemb){
f6263bb… drh 402 if( !g.httpUseSSL ){
f6263bb… drh 403 return fread(ptr, 1, nmemb, g.httpIn);
f6263bb… drh 404 }
f6263bb… drh 405 #ifdef FOSSIL_ENABLE_SSL
b0834be… stephan 406 return ssl_read_server(g.httpSSLConn, ptr, nmemb, 1);
f6263bb… drh 407 #else
f6263bb… drh 408 fossil_fatal("SSL not available");
1cd8163… stephan 409 /* NOT REACHED */
1cd8163… stephan 410 return 0;
f6263bb… drh 411 #endif
f6263bb… drh 412 }
f6263bb… drh 413
f6263bb… drh 414 /* Works like feof():
f6263bb… drh 415 **
f6263bb… drh 416 ** Return true if end-of-input has been reached.
f6263bb… drh 417 */
f6263bb… drh 418 int cgi_feof(void){
f6263bb… drh 419 if( !g.httpUseSSL ){
f6263bb… drh 420 return feof(g.httpIn);
f6263bb… drh 421 }
f6263bb… drh 422 #ifdef FOSSIL_ENABLE_SSL
f6263bb… drh 423 return ssl_eof(g.httpSSLConn);
f6263bb… drh 424 #else
f6263bb… drh 425 return 1;
f6263bb… drh 426 #endif
f6263bb… drh 427 }
f6263bb… drh 428
f6263bb… drh 429 /* Works like fwrite():
f6263bb… drh 430 **
f6263bb… drh 431 ** Try to output nmemb bytes of content. Return the number of
f6263bb… drh 432 ** bytes actually written.
f6263bb… drh 433 */
f6263bb… drh 434 static size_t cgi_fwrite(void *ptr, size_t nmemb){
f6263bb… drh 435 if( !g.httpUseSSL ){
f6263bb… drh 436 return fwrite(ptr, 1, nmemb, g.httpOut);
f6263bb… drh 437 }
f6263bb… drh 438 #ifdef FOSSIL_ENABLE_SSL
f6263bb… drh 439 return ssl_write_server(g.httpSSLConn, ptr, nmemb);
f6263bb… drh 440 #else
f6263bb… drh 441 fossil_fatal("SSL not available");
f6263bb… drh 442 #endif
f6263bb… drh 443 }
f6263bb… drh 444
f6263bb… drh 445 /* Works like fflush():
f6263bb… drh 446 **
f6263bb… drh 447 ** Make sure I/O has completed.
f6263bb… drh 448 */
f6263bb… drh 449 static void cgi_fflush(void){
f6263bb… drh 450 if( !g.httpUseSSL ){
f6263bb… drh 451 fflush(g.httpOut);
f6263bb… drh 452 }
f6263bb… drh 453 }
f6263bb… drh 454
7fcb462… stephan 455 /*
7fcb462… stephan 456 ** Given a Content-Type value, returns a string suitable for appending
7fcb462… stephan 457 ** to the Content-Type header for adding (or not) the "; charset=..."
ae8fc0e… drh 458 ** part. It returns an empty string for most types or if zReplyMimeType
7fcb462… stephan 459 ** is NULL.
7fcb462… stephan 460 **
7fcb462… stephan 461 ** See forum post f60dece061c364d1 for the discussions which lead to
7fcb462… stephan 462 ** this. Previously we always appended the charset, but WASM loaders
7fcb462… stephan 463 ** are pedantic and refuse to load any responses which have a
7fcb462… stephan 464 ** charset. Also, adding a charset is not strictly appropriate for
7fcb462… stephan 465 ** most types (and not required for many others which may ostensibly
7fcb462… stephan 466 ** benefit from one, as detailed in that forum post).
7fcb462… stephan 467 */
ae8fc0e… drh 468 static const char * content_type_charset(const char *zReplyMimeType){
ae8fc0e… drh 469 if(0==fossil_strncmp(zReplyMimeType,"text/",5)){
7fcb462… stephan 470 return "; charset=utf-8";
7fcb462… stephan 471 }
7fcb462… stephan 472 return "";
7fcb462… stephan 473 }
37ccaaf… drh 474
37ccaaf… drh 475 /*
37ccaaf… drh 476 ** Generate the reply to a web request. The output might be an
37ccaaf… drh 477 ** full HTTP response, or a CGI response, depending on how things have
37ccaaf… drh 478 ** be set up.
37ccaaf… drh 479 **
37ccaaf… drh 480 ** The reply consists of a response header (an HTTP or CGI response header)
37ccaaf… drh 481 ** followed by the concatenation of the content header and content body.
dbda8d6… drh 482 */
dbda8d6… drh 483 void cgi_reply(void){
2ac4ab2… drh 484 Blob hdr = BLOB_INITIALIZER;
ab0a0d7… drh 485 int total_size;
dbda8d6… drh 486 if( iReplyStatus<=0 ){
dbda8d6… drh 487 iReplyStatus = 200;
dbda8d6… drh 488 zReplyStatus = "OK";
dbda8d6… drh 489 }
dbda8d6… drh 490
dcc4866… drh 491 if( g.fullHttpReply ){
b6892cc… drh 492 if( rangeEnd>0
275da70… danield 493 && iReplyStatus==200
b6892cc… drh 494 && fossil_strcmp(P("REQUEST_METHOD"),"GET")==0
b6892cc… drh 495 ){
b6892cc… drh 496 iReplyStatus = 206;
8466a15… drh 497 zReplyStatus = "Partial Content";
b6892cc… drh 498 }
2ac4ab2… drh 499 blob_appendf(&hdr, "HTTP/1.0 %d %s\r\n", iReplyStatus, zReplyStatus);
2ac4ab2… drh 500 blob_appendf(&hdr, "Date: %s\r\n", cgi_rfc822_datestamp(time(0)));
2ac4ab2… drh 501 blob_appendf(&hdr, "Connection: close\r\n");
2ac4ab2… drh 502 blob_appendf(&hdr, "X-UA-Compatible: IE=edge\r\n");
7383450… drh 503 }else{
b6892cc… drh 504 assert( rangeEnd==0 );
2ac4ab2… drh 505 blob_appendf(&hdr, "Status: %d %s\r\n", iReplyStatus, zReplyStatus);
7383450… drh 506 }
bdde964… drh 507 if( etag_tag()[0]!=0
bdde964… drh 508 && iReplyStatus==200
ae8fc0e… drh 509 && strcmp(zReplyMimeType,"text/html")!=0
bdde964… drh 510 ){
bdde964… drh 511 /* Do not cache HTML replies as those will have been generated and
bdde964… drh 512 ** will likely, therefore, contains a nonce and we want that nonce to
bdde964… drh 513 ** be different every time. */
ad51cc6… florian 514 blob_appendf(&hdr, "ETag: \"%s\"\r\n", etag_tag());
2ac4ab2… drh 515 blob_appendf(&hdr, "Cache-Control: max-age=%d\r\n", etag_maxage());
ec5a063… drh 516 if( etag_mtime()>0 ){
2ac4ab2… drh 517 blob_appendf(&hdr, "Last-Modified: %s\r\n",
ec5a063… drh 518 cgi_rfc822_datestamp(etag_mtime()));
ec5a063… drh 519 }
ec5a063… drh 520 }else if( g.isConst ){
7383450… drh 521 /* isConst means that the reply is guaranteed to be invariant, even
7383450… drh 522 ** after configuration changes and/or Fossil binary recompiles. */
2ac4ab2… drh 523 blob_appendf(&hdr, "Cache-Control: max-age=315360000, immutable\r\n");
dbda8d6… drh 524 }else{
2ac4ab2… drh 525 blob_appendf(&hdr, "Cache-control: no-cache\r\n");
dbda8d6… drh 526 }
dbda8d6… drh 527
dbda8d6… drh 528 if( blob_size(&extraHeader)>0 ){
2ac4ab2… drh 529 blob_appendf(&hdr, "%s", blob_buffer(&extraHeader));
6d35cde… drh 530 }
6d35cde… drh 531
6d35cde… drh 532 /* Add headers to turn on useful security options in browsers. */
2ac4ab2… drh 533 blob_appendf(&hdr, "X-Frame-Options: SAMEORIGIN\r\n");
bdde964… drh 534 /* The previous stops fossil pages appearing in frames or iframes, preventing
6d35cde… drh 535 ** click-jacking attacks on supporting browsers.
6d35cde… drh 536 **
6d35cde… drh 537 ** Other good headers would be
6d35cde… drh 538 ** Strict-Transport-Security: max-age=62208000
6d35cde… drh 539 ** if we're using https. However, this would break sites which serve different
6d35cde… drh 540 ** content on http and https protocols. Also,
6d35cde… drh 541 ** X-Content-Security-Policy: allow 'self'
6d35cde… drh 542 ** would help mitigate some XSS and data injection attacks, but will break
6d35cde… drh 543 ** deliberate inclusion of external resources, such as JavaScript syntax
6d35cde… drh 544 ** highlighter scripts.
6d35cde… drh 545 **
6d35cde… drh 546 ** These headers are probably best added by the web server hosting fossil as
6d35cde… drh 547 ** a CGI script.
6d35cde… drh 548 */
6d35cde… drh 549
b6892cc… drh 550 if( iReplyStatus!=304 ) {
ae8fc0e… drh 551 blob_appendf(&hdr, "Content-Type: %s%s\r\n", zReplyMimeType,
ae8fc0e… drh 552 content_type_charset(zReplyMimeType));
ae8fc0e… drh 553 if( fossil_strcmp(zReplyMimeType,"application/x-fossil")==0 ){
fff9b67… drh 554 cgi_combine_header_and_body();
fff9b67… drh 555 blob_compress(&cgiContent[0], &cgiContent[0]);
fff9b67… drh 556 }
fff9b67… drh 557
b6892cc… drh 558 if( is_gzippable() && iReplyStatus!=206 ){
3f4b5d3… joel 559 int i;
5188969… jan.nijtmans 560 gzip_begin(0);
3f4b5d3… joel 561 for( i=0; i<2; i++ ){
3f4b5d3… joel 562 int size = blob_size(&cgiContent[i]);
3f4b5d3… joel 563 if( size>0 ) gzip_step(blob_buffer(&cgiContent[i]), size);
3f4b5d3… joel 564 blob_reset(&cgiContent[i]);
3f4b5d3… joel 565 }
3f4b5d3… joel 566 gzip_finish(&cgiContent[0]);
2ac4ab2… drh 567 blob_appendf(&hdr, "Content-Encoding: gzip\r\n");
2ac4ab2… drh 568 blob_appendf(&hdr, "Vary: Accept-Encoding\r\n");
3f4b5d3… joel 569 }
b312f5f… drh 570 total_size = blob_size(&cgiContent[0]) + blob_size(&cgiContent[1]);
b6892cc… drh 571 if( iReplyStatus==206 ){
2ac4ab2… drh 572 blob_appendf(&hdr, "Content-Range: bytes %d-%d/%d\r\n",
b6892cc… drh 573 rangeStart, rangeEnd-1, total_size);
275da70… danield 574 total_size = rangeEnd - rangeStart;
b6892cc… drh 575 }
2ac4ab2… drh 576 blob_appendf(&hdr, "Content-Length: %d\r\n", total_size);
ab0a0d7… drh 577 }else{
ab0a0d7… drh 578 total_size = 0;
22cb1e1… drh 579 }
2ac4ab2… drh 580 blob_appendf(&hdr, "\r\n");
f6263bb… drh 581 cgi_fwrite(blob_buffer(&hdr), blob_size(&hdr));
2ac4ab2… drh 582 blob_reset(&hdr);
6624350… drh 583 if( total_size>0
6624350… drh 584 && iReplyStatus!=304
5826ba3… drh 585 && fossil_strcmp(P("REQUEST_METHOD"),"HEAD")!=0
5826ba3… drh 586 ){
b312f5f… drh 587 int i, size;
b312f5f… drh 588 for(i=0; i<2; i++){
b312f5f… drh 589 size = blob_size(&cgiContent[i]);
b6892cc… drh 590 if( size<=rangeStart ){
b6892cc… drh 591 rangeStart -= size;
b6892cc… drh 592 }else{
b6892cc… drh 593 int n = size - rangeStart;
b6892cc… drh 594 if( n>total_size ){
b6892cc… drh 595 n = total_size;
b6892cc… drh 596 }
f6263bb… drh 597 cgi_fwrite(blob_buffer(&cgiContent[i])+rangeStart, n);
b6892cc… drh 598 rangeStart = 0;
b6892cc… drh 599 total_size -= n;
b312f5f… drh 600 }
b312f5f… drh 601 }
b312f5f… drh 602 }
f6263bb… drh 603 cgi_fflush();
4a7760e… drh 604 CGIDEBUG(("-------- END cgi ---------\n"));
d4e9df1… drh 605
d4e9df1… drh 606 /* After the webpage has been sent, do any useful background
69d332f… drh 607 ** processing.
d4e9df1… drh 608 */
fd31983… drh 609 g.cgiOutput = 2;
4180dc6… drh 610 if( g.db!=0 && iReplyStatus==200 ){
4180dc6… drh 611 backoffice_check_if_needed();
aa17077… drh 612 }
b312f5f… drh 613 }
b312f5f… drh 614
b312f5f… drh 615 /*
37ccaaf… drh 616 ** Generate an HTTP or CGI redirect response that causes a redirect
37ccaaf… drh 617 ** to the URL given in the argument.
dbda8d6… drh 618 **
dbda8d6… drh 619 ** The URL must be relative to the base of the fossil server.
dbda8d6… drh 620 */
4aba9ea… drh 621 NORETURN void cgi_redirect_with_status(
bee6dbd… mistachkin 622 const char *zURL,
bee6dbd… mistachkin 623 int iStat,
bee6dbd… mistachkin 624 const char *zStat
bee6dbd… mistachkin 625 ){
dbda8d6… drh 626 char *zLocation;
dbda8d6… drh 627 CGIDEBUG(("redirect to %s\n", zURL));
7fcb462… stephan 628 if( fossil_strncmp(zURL,"http:",5)==0
7fcb462… stephan 629 || fossil_strncmp(zURL,"https:",6)==0 ){
d0305b3… aku 630 zLocation = mprintf("Location: %s\r\n", zURL);
122a31d… drh 631 }else if( *zURL=='/' ){
ecb85f6… drh 632 int n1 = (int)strlen(g.zBaseURL);
ecb85f6… drh 633 int n2 = (int)strlen(g.zTop);
ecb85f6… drh 634 if( g.zBaseURL[n1-1]=='/' ) zURL++;
ecb85f6… drh 635 zLocation = mprintf("Location: %.*s%s\r\n", n1-n2, g.zBaseURL, zURL);
d0305b3… aku 636 }else{
63958fc… drh 637 zLocation = mprintf("Location: %s/%s\r\n", g.zBaseURL, zURL);
dbda8d6… drh 638 }
dbda8d6… drh 639 cgi_append_header(zLocation);
dbda8d6… drh 640 cgi_reset_content();
122a31d… drh 641 cgi_printf("<html>\n<p>Redirect to %h</p>\n</html>\n", zLocation);
bee6dbd… mistachkin 642 cgi_set_status(iStat, zStat);
dbda8d6… drh 643 free(zLocation);
dbda8d6… drh 644 cgi_reply();
932825b… drh 645 fossil_exit(0);
33c1cfd… drh 646 }
33c1cfd… drh 647 NORETURN void cgi_redirect_perm(const char *zURL){
33c1cfd… drh 648 cgi_redirect_with_status(zURL, 301, "Moved Permanently");
2069259… drh 649 }
bee6dbd… mistachkin 650 NORETURN void cgi_redirect(const char *zURL){
bee6dbd… mistachkin 651 cgi_redirect_with_status(zURL, 302, "Moved Temporarily");
bee6dbd… mistachkin 652 }
bee6dbd… mistachkin 653 NORETURN void cgi_redirect_with_method(const char *zURL){
bee6dbd… mistachkin 654 cgi_redirect_with_status(zURL, 307, "Temporary Redirect");
86d2b4e… drh 655 }
86d2b4e… drh 656 NORETURN void cgi_redirectf(const char *zFormat, ...){
d0305b3… aku 657 va_list ap;
d0305b3… aku 658 va_start(ap, zFormat);
d0305b3… aku 659 cgi_redirect(vmprintf(zFormat, ap));
d0305b3… aku 660 va_end(ap);
d0305b3… aku 661 }
d0305b3… aku 662
d0305b3… aku 663 /*
34cb476… drh 664 ** Add a "Content-disposition: attachment; filename=%s" header to the reply.
34cb476… drh 665 */
34cb476… drh 666 void cgi_content_disposition_filename(const char *zFilename){
0feb412… drh 667 char *z;
0feb412… drh 668 int i, n;
0feb412… drh 669
0feb412… drh 670 /* 0123456789 123456789 123456789 123456789 123456*/
0feb412… drh 671 z = mprintf("Content-Disposition: attachment; filename=\"%s\";\r\n",
0feb412… drh 672 file_tail(zFilename));
0feb412… drh 673 n = (int)strlen(z);
34cb476… drh 674 for(i=43; i<n-4; i++){
34cb476… drh 675 char c = z[i];
02e7c86… drh 676 if( fossil_isalnum(c) ) continue;
34cb476… drh 677 if( c=='.' || c=='-' || c=='/' ) continue;
34cb476… drh 678 z[i] = '_';
34cb476… drh 679 }
34cb476… drh 680 cgi_append_header(z);
34cb476… drh 681 fossil_free(z);
34cb476… drh 682 }
34cb476… drh 683
34cb476… drh 684 /*
59a51b8… drh 685 ** Return the URL for the caller. This is obtained from either the
37ccaaf… drh 686 ** "referer" CGI parameter, if it exists, or the HTTP_REFERER HTTP parameter.
59a51b8… drh 687 ** If neither exist, return zDefault.
59a51b8… drh 688 */
59a51b8… drh 689 const char *cgi_referer(const char *zDefault){
59a51b8… drh 690 const char *zRef = P("referer");
59a51b8… drh 691 if( zRef==0 ){
59a51b8… drh 692 zRef = P("HTTP_REFERER");
59a51b8… drh 693 if( zRef==0 ) zRef = zDefault;
59a51b8… drh 694 }
59a51b8… drh 695 return zRef;
59a51b8… drh 696 }
59a51b8… drh 697
7c71f00… drh 698
047802a… drh 699 /*
7c71f00… drh 700 ** Return true if the current request is coming from the same origin.
2269ac6… drh 701 **
2269ac6… drh 702 ** If the request comes from a different origin and bErrorLog is true, then
2269ac6… drh 703 ** put a warning message on the error log as this was a possible hack
2269ac6… drh 704 ** attempt.
047802a… drh 705 */
2269ac6… drh 706 int cgi_same_origin(int bErrorLog){
7c71f00… drh 707 const char *zRef;
3046c5e… drh 708 char *zToFree = 0;
047802a… drh 709 int nBase;
3046c5e… drh 710 int rc;
7c71f00… drh 711 if( g.zBaseURL==0 ) return 0;
7c71f00… drh 712 zRef = P("HTTP_REFERER");
047802a… drh 713 if( zRef==0 ) return 0;
3046c5e… drh 714 if( strchr(zRef,'%')!=0 ){
3046c5e… drh 715 zToFree = strdup(zRef);
3046c5e… drh 716 dehttpize(zToFree);
3046c5e… drh 717 zRef = zToFree;
3046c5e… drh 718 }
047802a… drh 719 nBase = (int)strlen(g.zBaseURL);
3046c5e… drh 720 if( fossil_strncmp(g.zBaseURL,zRef,nBase)!=0 ){
3046c5e… drh 721 rc = 0;
3046c5e… drh 722 }else if( zRef[nBase]!=0 && zRef[nBase]!='/' ){
3046c5e… drh 723 rc = 0;
3046c5e… drh 724 }else{
3046c5e… drh 725 rc = 1;
2269ac6… drh 726 }
2069259… drh 727 if( rc==0 && bErrorLog && fossil_strcmp(P("REQUST_METHOD"),"POST")==0 ){
2269ac6… drh 728 fossil_errorlog("warning: POST from different origin");
3046c5e… drh 729 }
3046c5e… drh 730 fossil_free(zToFree);
3046c5e… drh 731 return rc;
920ace1… drh 732 }
920ace1… drh 733
920ace1… drh 734 /*
920ace1… drh 735 ** Return true if the current CGI request is a POST request
920ace1… drh 736 */
920ace1… drh 737 static int cgi_is_post_request(void){
920ace1… drh 738 const char *zMethod = P("REQUEST_METHOD");
920ace1… drh 739 if( zMethod==0 ) return 0;
920ace1… drh 740 if( strcmp(zMethod,"POST")!=0 ) return 0;
920ace1… drh 741 return 1;
7c71f00… drh 742 }
7c71f00… drh 743
7c71f00… drh 744 /*
7c71f00… drh 745 ** Return true if the current request appears to be safe from a
920ace1… drh 746 ** Cross-Site Request Forgery (CSRF) attack. The level of checking
920ace1… drh 747 ** is determined by the parameter. The higher the number, the more
920ace1… drh 748 ** secure we are:
920ace1… drh 749 **
920ace1… drh 750 ** 0: Request must come from the same origin
920ace1… drh 751 ** 1: Same origin and must be a POST request
920ace1… drh 752 ** 2: All of the above plus must have a valid CSRF token
920ace1… drh 753 **
920ace1… drh 754 ** Results are cached in the g.okCsrf variable. The g.okCsrf value
920ace1… drh 755 ** has meaning as follows:
7c71f00… drh 756 **
920ace1… drh 757 ** -1: Not a secure request
920ace1… drh 758 ** 0: Status unknown
920ace1… drh 759 ** 1: Request comes from the same origin
920ace1… drh 760 ** 2: (1) plus it is a POST request
920ace1… drh 761 ** 3: (2) plus there is a valid "csrf" token in the request
37dfb4c… stephan 762 */
920ace1… drh 763 int cgi_csrf_safe(int securityLevel){
920ace1… drh 764 if( g.okCsrf<0 ) return 0;
920ace1… drh 765 if( g.okCsrf==0 ){
2269ac6… drh 766 if( !cgi_same_origin(1) ){
920ace1… drh 767 g.okCsrf = -1;
920ace1… drh 768 }else{
920ace1… drh 769 g.okCsrf = 1;
920ace1… drh 770 if( cgi_is_post_request() ){
920ace1… drh 771 g.okCsrf = 2;
920ace1… drh 772 if( fossil_strcmp(P("csrf"), g.zCsrfToken)==0 ){
920ace1… drh 773 g.okCsrf = 3;
920ace1… drh 774 }
920ace1… drh 775 }
920ace1… drh 776 }
37dfb4c… stephan 777 }
920ace1… drh 778 return g.okCsrf >= (securityLevel+1);
37dfb4c… stephan 779 }
37dfb4c… stephan 780
37dfb4c… stephan 781 /*
920ace1… drh 782 ** Verify that CSRF defenses are maximal - that the request comes from
920ace1… drh 783 ** the same origin, that it is a POST request, and that there is a valid
920ace1… drh 784 ** "csrf" token. If this is not the case, fail immediately.
7c71f00… drh 785 */
920ace1… drh 786 void cgi_csrf_verify(void){
920ace1… drh 787 if( !cgi_csrf_safe(2) ){
920ace1… drh 788 fossil_fatal("Cross-site Request Forgery detected");
7c71f00… drh 789 }
047802a… drh 790 }
047802a… drh 791
59a51b8… drh 792 /*
37ccaaf… drh 793 ** Information about all query parameters, post parameter, cookies and
37ccaaf… drh 794 ** CGI environment variables are stored in a hash table as follows:
dbda8d6… drh 795 */
dbda8d6… drh 796 static int nAllocQP = 0; /* Space allocated for aParamQP[] */
dbda8d6… drh 797 static int nUsedQP = 0; /* Space actually used in aParamQP[] */
dbda8d6… drh 798 static int sortQP = 0; /* True if aParamQP[] needs sorting */
dbda8d6… drh 799 static int seqQP = 0; /* Sequence numbers */
dbda8d6… drh 800 static struct QParam { /* One entry for each query parameter or cookie */
dbda8d6… drh 801 const char *zName; /* Parameter or cookie name */
dbda8d6… drh 802 const char *zValue; /* Value of the query parameter or cookie */
dbda8d6… drh 803 int seq; /* Order of insertion */
c0c0bae… drh 804 char isQP; /* True for query parameters */
c0c0bae… drh 805 char cTag; /* Tag on query parameters */
57f1e87… drh 806 char isFetched; /* 1 if the var is requested via P/PD() */
dbda8d6… drh 807 } *aParamQP; /* An array of all parameters and cookies */
dbda8d6… drh 808
dbda8d6… drh 809 /*
dbda8d6… drh 810 ** Add another query parameter or cookie to the parameter set.
dbda8d6… drh 811 ** zName is the name of the query parameter or cookie and zValue
dbda8d6… drh 812 ** is its fully decoded value.
dbda8d6… drh 813 **
dbda8d6… drh 814 ** zName and zValue are not copied and must not change or be
dbda8d6… drh 815 ** deallocated after this routine returns.
dbda8d6… drh 816 */
f8a2aa0… drh 817 void cgi_set_parameter_nocopy(const char *zName, const char *zValue, int isQP){
dbda8d6… drh 818 if( nAllocQP<=nUsedQP ){
dbda8d6… drh 819 nAllocQP = nAllocQP*2 + 10;
2827d44… drh 820 if( nAllocQP>1000 ){
2827d44… drh 821 /* Prevent a DOS service attack against the framework */
2827d44… drh 822 fossil_fatal("Too many query parameters");
2827d44… drh 823 }
8f41b2f… drh 824 aParamQP = fossil_realloc( aParamQP, nAllocQP*sizeof(aParamQP[0]) );
dbda8d6… drh 825 }
dbda8d6… drh 826 aParamQP[nUsedQP].zName = zName;
dbda8d6… drh 827 aParamQP[nUsedQP].zValue = zValue;
596f3c1… drh 828 if( g.fHttpTrace ){
596f3c1… drh 829 fprintf(stderr, "# cgi: %s = [%s]\n", zName, zValue);
596f3c1… drh 830 }
dbda8d6… drh 831 aParamQP[nUsedQP].seq = seqQP++;
f8a2aa0… drh 832 aParamQP[nUsedQP].isQP = isQP;
1a2aa2b… mistachkin 833 aParamQP[nUsedQP].cTag = 0;
57f1e87… drh 834 aParamQP[nUsedQP].isFetched = 0;
dbda8d6… drh 835 nUsedQP++;
dbda8d6… drh 836 sortQP = 1;
19bbd2c… drh 837 }
19bbd2c… drh 838
19bbd2c… drh 839 /*
19bbd2c… drh 840 ** Add another query parameter or cookie to the parameter set.
19bbd2c… drh 841 ** zName is the name of the query parameter or cookie and zValue
19bbd2c… drh 842 ** is its fully decoded value. zName will be modified to be an
19bbd2c… drh 843 ** all lowercase string.
19bbd2c… drh 844 **
19bbd2c… drh 845 ** zName and zValue are not copied and must not change or be
19bbd2c… drh 846 ** deallocated after this routine returns. This routine changes
19bbd2c… drh 847 ** all ASCII alphabetic characters in zName to lower case. The
19bbd2c… drh 848 ** caller must not change them back.
19bbd2c… drh 849 */
19bbd2c… drh 850 void cgi_set_parameter_nocopy_tolower(
19bbd2c… drh 851 char *zName,
19bbd2c… drh 852 const char *zValue,
19bbd2c… drh 853 int isQP
19bbd2c… drh 854 ){
19bbd2c… drh 855 int i;
19bbd2c… drh 856 for(i=0; zName[i]; i++){ zName[i] = fossil_tolower(zName[i]); }
19bbd2c… drh 857 cgi_set_parameter_nocopy(zName, zValue, isQP);
dbda8d6… drh 858 }
dbda8d6… drh 859
dbda8d6… drh 860 /*
dbda8d6… drh 861 ** Add another query parameter or cookie to the parameter set.
dbda8d6… drh 862 ** zName is the name of the query parameter or cookie and zValue
dbda8d6… drh 863 ** is its fully decoded value.
dbda8d6… drh 864 **
dbda8d6… drh 865 ** Copies are made of both the zName and zValue parameters.
dbda8d6… drh 866 */
dbda8d6… drh 867 void cgi_set_parameter(const char *zName, const char *zValue){
140cb31… drh 868 cgi_set_parameter_nocopy(fossil_strdup(zName),fossil_strdup(zValue), 0);
5e17369… andygoth 869 }
5e17369… andygoth 870 void cgi_set_query_parameter(const char *zName, const char *zValue){
140cb31… drh 871 cgi_set_parameter_nocopy(fossil_strdup(zName),fossil_strdup(zValue), 1);
d0305b3… aku 872 }
d0305b3… aku 873
d0305b3… aku 874 /*
d0305b3… aku 875 ** Replace a parameter with a new value.
d0305b3… aku 876 */
d0305b3… aku 877 void cgi_replace_parameter(const char *zName, const char *zValue){
d0305b3… aku 878 int i;
d0305b3… aku 879 for(i=0; i<nUsedQP; i++){
32ad9a1… drh 880 if( fossil_strcmp(aParamQP[i].zName,zName)==0 ){
32ad9a1… drh 881 aParamQP[i].zValue = zValue;
32ad9a1… drh 882 return;
32ad9a1… drh 883 }
32ad9a1… drh 884 }
f8a2aa0… drh 885 cgi_set_parameter_nocopy(zName, zValue, 0);
f8a2aa0… drh 886 }
c0c0bae… drh 887 void cgi_replace_query_parameter(const char *zName, const char *zValue){
c0c0bae… drh 888 int i;
c0c0bae… drh 889 for(i=0; i<nUsedQP; i++){
c0c0bae… drh 890 if( fossil_strcmp(aParamQP[i].zName,zName)==0 ){
c0c0bae… drh 891 aParamQP[i].zValue = zValue;
c0c0bae… drh 892 assert( aParamQP[i].isQP );
c0c0bae… drh 893 return;
c0c0bae… drh 894 }
c0c0bae… drh 895 }
c0c0bae… drh 896 cgi_set_parameter_nocopy(zName, zValue, 1);
19bbd2c… drh 897 }
19bbd2c… drh 898 void cgi_replace_query_parameter_tolower(char *zName, const char *zValue){
19bbd2c… drh 899 int i;
19bbd2c… drh 900 for(i=0; zName[i]; i++){ zName[i] = fossil_tolower(zName[i]); }
19bbd2c… drh 901 cgi_replace_query_parameter(zName, zValue);
5e17369… andygoth 902 }
5e17369… andygoth 903
5e17369… andygoth 904 /*
5e17369… andygoth 905 ** Delete a parameter.
5e17369… andygoth 906 */
5e17369… andygoth 907 void cgi_delete_parameter(const char *zName){
5e17369… andygoth 908 int i;
5e17369… andygoth 909 for(i=0; i<nUsedQP; i++){
5e17369… andygoth 910 if( fossil_strcmp(aParamQP[i].zName,zName)==0 ){
5e17369… andygoth 911 --nUsedQP;
5e17369… andygoth 912 if( i<nUsedQP ){
5e17369… andygoth 913 memmove(aParamQP+i, aParamQP+i+1, sizeof(*aParamQP)*(nUsedQP-i));
5e17369… andygoth 914 }
5e17369… andygoth 915 return;
5e17369… andygoth 916 }
5e17369… andygoth 917 }
5e17369… andygoth 918 }
5e17369… andygoth 919 void cgi_delete_query_parameter(const char *zName){
5e17369… andygoth 920 int i;
5e17369… andygoth 921 for(i=0; i<nUsedQP; i++){
5e17369… andygoth 922 if( fossil_strcmp(aParamQP[i].zName,zName)==0 ){
5e17369… andygoth 923 assert( aParamQP[i].isQP );
5e17369… andygoth 924 --nUsedQP;
5e17369… andygoth 925 if( i<nUsedQP ){
5e17369… andygoth 926 memmove(aParamQP+i, aParamQP+i+1, sizeof(*aParamQP)*(nUsedQP-i));
5e17369… andygoth 927 }
5e17369… andygoth 928 return;
5e17369… andygoth 929 }
5e17369… andygoth 930 }
5e17369… andygoth 931 }
5e17369… andygoth 932
5e17369… andygoth 933 /*
1a0b304… drh 934 ** Return the number of query parameters. Cookies and environment variables
1a0b304… drh 935 ** do not count. Also, do not count the special QP "name".
1a0b304… drh 936 */
1a0b304… drh 937 int cgi_qp_count(void){
1a0b304… drh 938 int cnt = 0;
1a0b304… drh 939 int i;
1a0b304… drh 940 for(i=0; i<nUsedQP; i++){
1a0b304… drh 941 if( aParamQP[i].isQP && fossil_strcmp(aParamQP[i].zName,"name")!=0 ) cnt++;
1a0b304… drh 942 }
1a0b304… drh 943 return cnt;
1a0b304… drh 944 }
1a0b304… drh 945
1a0b304… drh 946 /*
33d3bf3… km 947 ** Add an environment variable value to the parameter set. The zName
33d3bf3… km 948 ** portion is fixed but a copy is made of zValue.
dbda8d6… drh 949 */
dbda8d6… drh 950 void cgi_setenv(const char *zName, const char *zValue){
140cb31… drh 951 cgi_set_parameter_nocopy(zName, fossil_strdup(zValue), 0);
0c1419a… stephan 952 }
0c1419a… stephan 953
0c1419a… stephan 954 /*
0c1419a… stephan 955 ** Returns true if NUL-terminated z contains any non-NUL
0c1419a… stephan 956 ** control characters (<0x20, 32d).
0c1419a… stephan 957 */
654fe05… drh 958 static int contains_ctrl(const char *zIn){
654fe05… drh 959 const unsigned char *z = (const unsigned char*)zIn;
0c1419a… stephan 960 assert(z);
654fe05… drh 961 for( ; *z>=0x20; ++z ){}
0c1419a… stephan 962 return 0!=*z;
19bbd2c… drh 963 }
dbda8d6… drh 964
dbda8d6… drh 965 /*
dbda8d6… drh 966 ** Add a list of query parameters or cookies to the parameter set.
dbda8d6… drh 967 **
dbda8d6… drh 968 ** Each parameter is of the form NAME=VALUE. Both the NAME and the
dbda8d6… drh 969 ** VALUE may be url-encoded ("+" for space, "%HH" for other special
dbda8d6… drh 970 ** characters). But this routine assumes that NAME contains no
dbda8d6… drh 971 ** special character and therefore does not decode it.
dbda8d6… drh 972 **
33d3bf3… km 973 ** If NAME begins with something other than a lower-case letter then
dbda8d6… drh 974 ** the entire NAME=VALUE term is ignored. Hence:
dbda8d6… drh 975 **
dbda8d6… drh 976 ** * cookies and query parameters that have uppercase names
dbda8d6… drh 977 ** are ignored.
dbda8d6… drh 978 **
dbda8d6… drh 979 ** * it is impossible for a cookie or query parameter to
dbda8d6… drh 980 ** override the value of an environment variable since
dbda8d6… drh 981 ** environment variables always have uppercase names.
dbda8d6… drh 982 **
6c02983… drh 983 ** 2018-03-29: Also ignore the entry if NAME that contains any characters
1862890… stephan 984 ** other than [-a-zA-Z0-9_]. There are no known exploits involving unusual
6c02983… drh 985 ** names that contain characters outside that set, but it never hurts to
6c02983… drh 986 ** be extra cautious when sanitizing inputs.
6c02983… drh 987 **
dbda8d6… drh 988 ** Parameters are separated by the "terminator" character. Whitespace
dbda8d6… drh 989 ** before the NAME is ignored.
dbda8d6… drh 990 **
dbda8d6… drh 991 ** The input string "z" is modified but no copies is made. "z"
dbda8d6… drh 992 ** should not be deallocated or changed again after this routine
dbda8d6… drh 993 ** returns or it will corrupt the parameter table.
0c1419a… stephan 994 **
0c1419a… stephan 995 ** If bPermitCtrl is false and the decoded value of any entry in z
0c1419a… stephan 996 ** contains control characters (<0x20, 32d) then that key/value pair
0c1419a… stephan 997 ** are skipped.
dbda8d6… drh 998 */
0c1419a… stephan 999 static void add_param_list(char *z, int terminator, int bPermitCtrl){
f8a2aa0… drh 1000 int isQP = terminator=='&';
dbda8d6… drh 1001 while( *z ){
dbda8d6… drh 1002 char *zName;
dbda8d6… drh 1003 char *zValue;
2fac809… drh 1004 while( fossil_isspace(*z) ){ z++; }
dbda8d6… drh 1005 zName = z;
dbda8d6… drh 1006 while( *z && *z!='=' && *z!=terminator ){ z++; }
dbda8d6… drh 1007 if( *z=='=' ){
dbda8d6… drh 1008 *z = 0;
dbda8d6… drh 1009 z++;
dbda8d6… drh 1010 zValue = z;
dbda8d6… drh 1011 while( *z && *z!=terminator ){ z++; }
dbda8d6… drh 1012 if( *z ){
dbda8d6… drh 1013 *z = 0;
dbda8d6… drh 1014 z++;
dbda8d6… drh 1015 }
dbda8d6… drh 1016 dehttpize(zValue);
dbda8d6… drh 1017 }else{
dbda8d6… drh 1018 if( *z ){ *z++ = 0; }
dbda8d6… drh 1019 zValue = "";
dbda8d6… drh 1020 }
19bbd2c… drh 1021 if( zName[0] && fossil_no_strange_characters(zName+1) ){
0c1419a… stephan 1022 if( 0==bPermitCtrl && contains_ctrl(zValue) ){
0c1419a… stephan 1023 continue /* Reject it. An argument could be made
0c1419a… stephan 1024 ** for break instead of continue. */;
0c1419a… stephan 1025 }else if( fossil_islower(zName[0]) ){
19bbd2c… drh 1026 cgi_set_parameter_nocopy(zName, zValue, isQP);
19bbd2c… drh 1027 }else if( fossil_isupper(zName[0]) ){
19bbd2c… drh 1028 cgi_set_parameter_nocopy_tolower(zName, zValue, isQP);
19bbd2c… drh 1029 }
dbda8d6… drh 1030 }
796dcfe… drh 1031 #ifdef FOSSIL_ENABLE_JSON
796dcfe… drh 1032 json_setenv( zName, cson_value_new_string(zValue,strlen(zValue)) );
796dcfe… drh 1033 #endif /* FOSSIL_ENABLE_JSON */
dbda8d6… drh 1034 }
dbda8d6… drh 1035 }
dbda8d6… drh 1036
dbda8d6… drh 1037 /*
dbda8d6… drh 1038 ** *pz is a string that consists of multiple lines of text. This
dbda8d6… drh 1039 ** routine finds the end of the current line of text and converts
dbda8d6… drh 1040 ** the "\n" or "\r\n" that ends that line into a "\000". It then
dbda8d6… drh 1041 ** advances *pz to the beginning of the next line and returns the
dbda8d6… drh 1042 ** previous value of *pz (which is the start of the current line.)
dbda8d6… drh 1043 */
dbda8d6… drh 1044 static char *get_line_from_string(char **pz, int *pLen){
dbda8d6… drh 1045 char *z = *pz;
dbda8d6… drh 1046 int i;
dbda8d6… drh 1047 if( z[0]==0 ) return 0;
dbda8d6… drh 1048 for(i=0; z[i]; i++){
dbda8d6… drh 1049 if( z[i]=='\n' ){
dbda8d6… drh 1050 if( i>0 && z[i-1]=='\r' ){
dbda8d6… drh 1051 z[i-1] = 0;
dbda8d6… drh 1052 }else{
dbda8d6… drh 1053 z[i] = 0;
dbda8d6… drh 1054 }
dbda8d6… drh 1055 i++;
dbda8d6… drh 1056 break;
dbda8d6… drh 1057 }
dbda8d6… drh 1058 }
dbda8d6… drh 1059 *pz = &z[i];
dbda8d6… drh 1060 *pLen -= i;
dbda8d6… drh 1061 return z;
dbda8d6… drh 1062 }
dbda8d6… drh 1063
dbda8d6… drh 1064 /*
dbda8d6… drh 1065 ** The input *pz points to content that is terminated by a "\r\n"
58f00d3… ashepilko 1066 ** followed by the boundary marker zBoundary. An extra "--" may or
58f00d3… ashepilko 1067 ** may not be appended to the boundary marker. There are *pLen characters
dbda8d6… drh 1068 ** in *pz.
dbda8d6… drh 1069 **
dbda8d6… drh 1070 ** This routine adds a "\000" to the end of the content (overwriting
dbda8d6… drh 1071 ** the "\r\n") and returns a pointer to the content. The *pz input
58f00d3… ashepilko 1072 ** is adjusted to point to the first line following the boundary.
dbda8d6… drh 1073 ** The length of the content is stored in *pnContent.
dbda8d6… drh 1074 */
dbda8d6… drh 1075 static char *get_bounded_content(
dbda8d6… drh 1076 char **pz, /* Content taken from here */
dbda8d6… drh 1077 int *pLen, /* Number of bytes of data in (*pz)[] */
58f00d3… ashepilko 1078 char *zBoundary, /* Boundary text marking the end of content */
dbda8d6… drh 1079 int *pnContent /* Write the size of the content here */
dbda8d6… drh 1080 ){
dbda8d6… drh 1081 char *z = *pz;
dbda8d6… drh 1082 int len = *pLen;
dbda8d6… drh 1083 int i;
58f00d3… ashepilko 1084 int nBoundary = strlen(zBoundary);
dbda8d6… drh 1085 *pnContent = len;
dbda8d6… drh 1086 for(i=0; i<len; i++){
7fcb462… stephan 1087 if( z[i]=='\n' && fossil_strncmp(zBoundary, &z[i+1],
7fcb462… stephan 1088 nBoundary)==0 ){
dbda8d6… drh 1089 if( i>0 && z[i-1]=='\r' ) i--;
dbda8d6… drh 1090 z[i] = 0;
dbda8d6… drh 1091 *pnContent = i;
58f00d3… ashepilko 1092 i += nBoundary;
dbda8d6… drh 1093 break;
dbda8d6… drh 1094 }
dbda8d6… drh 1095 }
dbda8d6… drh 1096 *pz = &z[i];
dbda8d6… drh 1097 get_line_from_string(pz, pLen);
45f3516… jan.nijtmans 1098 return z;
dbda8d6… drh 1099 }
dbda8d6… drh 1100
dbda8d6… drh 1101 /*
dbda8d6… drh 1102 ** Tokenize a line of text into as many as nArg tokens. Make
dbda8d6… drh 1103 ** azArg[] point to the start of each token.
dbda8d6… drh 1104 **
dbda8d6… drh 1105 ** Tokens consist of space or semi-colon delimited words or
dbda8d6… drh 1106 ** strings inside double-quotes. Example:
dbda8d6… drh 1107 **
dbda8d6… drh 1108 ** content-disposition: form-data; name="fn"; filename="index.html"
dbda8d6… drh 1109 **
dbda8d6… drh 1110 ** The line above is tokenized as follows:
dbda8d6… drh 1111 **
dbda8d6… drh 1112 ** azArg[0] = "content-disposition:"
dbda8d6… drh 1113 ** azArg[1] = "form-data"
dbda8d6… drh 1114 ** azArg[2] = "name="
dbda8d6… drh 1115 ** azArg[3] = "fn"
dbda8d6… drh 1116 ** azArg[4] = "filename="
dbda8d6… drh 1117 ** azArg[5] = "index.html"
dbda8d6… drh 1118 ** azArg[6] = 0;
dbda8d6… drh 1119 **
dbda8d6… drh 1120 ** '\000' characters are inserted in z[] at the end of each token.
dbda8d6… drh 1121 ** This routine returns the total number of tokens on the line, 6
dbda8d6… drh 1122 ** in the example above.
dbda8d6… drh 1123 */
dbda8d6… drh 1124 static int tokenize_line(char *z, int mxArg, char **azArg){
dbda8d6… drh 1125 int i = 0;
dbda8d6… drh 1126 while( *z ){
2fac809… drh 1127 while( fossil_isspace(*z) || *z==';' ){ z++; }
dbda8d6… drh 1128 if( *z=='"' && z[1] ){
dbda8d6… drh 1129 *z = 0;
dbda8d6… drh 1130 z++;
dbda8d6… drh 1131 if( i<mxArg-1 ){ azArg[i++] = z; }
dbda8d6… drh 1132 while( *z && *z!='"' ){ z++; }
dbda8d6… drh 1133 if( *z==0 ) break;
dbda8d6… drh 1134 *z = 0;
dbda8d6… drh 1135 z++;
dbda8d6… drh 1136 }else{
dbda8d6… drh 1137 if( i<mxArg-1 ){ azArg[i++] = z; }
2fac809… drh 1138 while( *z && !fossil_isspace(*z) && *z!=';' && *z!='"' ){ z++; }
dbda8d6… drh 1139 if( *z && *z!='"' ){
dbda8d6… drh 1140 *z = 0;
dbda8d6… drh 1141 z++;
dbda8d6… drh 1142 }
dbda8d6… drh 1143 }
dbda8d6… drh 1144 }
dbda8d6… drh 1145 azArg[i] = 0;
dbda8d6… drh 1146 return i;
dbda8d6… drh 1147 }
dbda8d6… drh 1148
dbda8d6… drh 1149 /*
dbda8d6… drh 1150 ** Scan the multipart-form content and make appropriate entries
dbda8d6… drh 1151 ** into the parameter table.
dbda8d6… drh 1152 **
dbda8d6… drh 1153 ** The content string "z" is modified by this routine but it is
dbda8d6… drh 1154 ** not copied. The calling function must not deallocate or modify
dbda8d6… drh 1155 ** "z" after this routine finishes or it could corrupt the parameter
dbda8d6… drh 1156 ** table.
dbda8d6… drh 1157 */
dbda8d6… drh 1158 static void process_multipart_form_data(char *z, int len){
dbda8d6… drh 1159 char *zLine;
dbda8d6… drh 1160 int nArg, i;
58f00d3… ashepilko 1161 char *zBoundary;
dbda8d6… drh 1162 char *zValue;
dbda8d6… drh 1163 char *zName = 0;
dbda8d6… drh 1164 int showBytes = 0;
dbda8d6… drh 1165 char *azArg[50];
dbda8d6… drh 1166
58f00d3… ashepilko 1167 zBoundary = get_line_from_string(&z, &len);
58f00d3… ashepilko 1168 if( zBoundary==0 ) return;
dbda8d6… drh 1169 while( (zLine = get_line_from_string(&z, &len))!=0 ){
dbda8d6… drh 1170 if( zLine[0]==0 ){
dbda8d6… drh 1171 int nContent = 0;
58f00d3… ashepilko 1172 zValue = get_bounded_content(&z, &len, zBoundary, &nContent);
19bbd2c… drh 1173 if( zName && zValue ){
19bbd2c… drh 1174 if( fossil_islower(zName[0]) ){
19bbd2c… drh 1175 cgi_set_parameter_nocopy(zName, zValue, 1);
19bbd2c… drh 1176 if( showBytes ){
19bbd2c… drh 1177 cgi_set_parameter_nocopy(mprintf("%s:bytes", zName),
19bbd2c… drh 1178 mprintf("%d",nContent), 1);
19bbd2c… drh 1179 }
19bbd2c… drh 1180 }else if( fossil_isupper(zName[0]) ){
19bbd2c… drh 1181 cgi_set_parameter_nocopy_tolower(zName, zValue, 1);
19bbd2c… drh 1182 if( showBytes ){
19bbd2c… drh 1183 cgi_set_parameter_nocopy_tolower(mprintf("%s:bytes", zName),
19bbd2c… drh 1184 mprintf("%d",nContent), 1);
19bbd2c… drh 1185 }
dbda8d6… drh 1186 }
dbda8d6… drh 1187 }
dbda8d6… drh 1188 zName = 0;
dbda8d6… drh 1189 showBytes = 0;
dbda8d6… drh 1190 }else{
3cb9ba4… andygoth 1191 nArg = tokenize_line(zLine, count(azArg), azArg);
dbda8d6… drh 1192 for(i=0; i<nArg; i++){
2fac809… drh 1193 int c = fossil_tolower(azArg[i][0]);
fac950a… drh 1194 int n = strlen(azArg[i]);
fac950a… drh 1195 if( c=='c' && sqlite3_strnicmp(azArg[i],"content-disposition:",n)==0 ){
dbda8d6… drh 1196 i++;
fac950a… drh 1197 }else if( c=='n' && sqlite3_strnicmp(azArg[i],"name=",n)==0 ){
dbda8d6… drh 1198 zName = azArg[++i];
fac950a… drh 1199 }else if( c=='f' && sqlite3_strnicmp(azArg[i],"filename=",n)==0 ){
dbda8d6… drh 1200 char *z = azArg[++i];
19bbd2c… drh 1201 if( zName && z ){
19bbd2c… drh 1202 if( fossil_islower(zName[0]) ){
19bbd2c… drh 1203 cgi_set_parameter_nocopy(mprintf("%s:filename",zName), z, 1);
19bbd2c… drh 1204 }else if( fossil_isupper(zName[0]) ){
19bbd2c… drh 1205 cgi_set_parameter_nocopy_tolower(mprintf("%s:filename",zName),
19bbd2c… drh 1206 z, 1);
19bbd2c… drh 1207 }
dbda8d6… drh 1208 }
dbda8d6… drh 1209 showBytes = 1;
fac950a… drh 1210 }else if( c=='c' && sqlite3_strnicmp(azArg[i],"content-type:",n)==0 ){
dbda8d6… drh 1211 char *z = azArg[++i];
19bbd2c… drh 1212 if( zName && z ){
19bbd2c… drh 1213 if( fossil_islower(zName[0]) ){
19bbd2c… drh 1214 cgi_set_parameter_nocopy(mprintf("%s:mimetype",zName), z, 1);
19bbd2c… drh 1215 }else if( fossil_isupper(zName[0]) ){
19bbd2c… drh 1216 cgi_set_parameter_nocopy_tolower(mprintf("%s:mimetype",zName),
19bbd2c… drh 1217 z, 1);
19bbd2c… drh 1218 }
dbda8d6… drh 1219 }
dbda8d6… drh 1220 }
dbda8d6… drh 1221 }
dbda8d6… drh 1222 }
45f3516… jan.nijtmans 1223 }
796dcfe… drh 1224 }
796dcfe… drh 1225
796dcfe… drh 1226
796dcfe… drh 1227 #ifdef FOSSIL_ENABLE_JSON
796dcfe… drh 1228 /*
7f5877e… stephan 1229 ** Reads a JSON object from the given blob, which is assumed to have
7f5877e… stephan 1230 ** been populated by the caller from stdin, the SSL API, or a file, as
7f5877e… stephan 1231 ** appropriate for the particular use case. On success g.json.post is
7f5877e… stephan 1232 ** updated to hold the content. On error a FSL_JSON_E_INVALID_REQUEST
7f5877e… stephan 1233 ** response is output and fossil_exit() is called (in HTTP mode exit
7f5877e… stephan 1234 ** code 0 is used).
7f5877e… stephan 1235 */
7f5877e… stephan 1236 void cgi_parse_POST_JSON( Blob * pIn ){
7f5877e… stephan 1237 cson_value * jv = NULL;
4dae795… stephan 1238 cson_parse_info pinfo = cson_parse_info_empty;
e7f13b8… stephan 1239 assert(g.json.gc.a && "json_bootstrap_early() was not called!");
7f5877e… stephan 1240 jv = cson_parse_Blob(pIn, &pinfo);
7f5877e… stephan 1241 if( jv==NULL ){
796dcfe… drh 1242 goto invalidRequest;
796dcfe… drh 1243 }else{
796dcfe… drh 1244 json_gc_add( "POST.JSON", jv );
796dcfe… drh 1245 g.json.post.v = jv;
796dcfe… drh 1246 g.json.post.o = cson_value_get_object( jv );
796dcfe… drh 1247 if( !g.json.post.o ){ /* we don't support non-Object (Array) requests */
796dcfe… drh 1248 goto invalidRequest;
796dcfe… drh 1249 }
796dcfe… drh 1250 }
796dcfe… drh 1251 return;
796dcfe… drh 1252 invalidRequest:
796dcfe… drh 1253 cgi_set_content_type(json_guess_content_type());
4dae795… stephan 1254 if(0 != pinfo.errorCode){ /* fancy error message */
4dae795… stephan 1255 char * msg = mprintf("JSON parse error at line %u, column %u, "
4dae795… stephan 1256 "byte offset %u: %s",
4dae795… stephan 1257 pinfo.line, pinfo.col, pinfo.length,
4dae795… stephan 1258 cson_rc_string(pinfo.errorCode));
4dae795… stephan 1259 json_err( FSL_JSON_E_INVALID_REQUEST, msg, 1 );
7f5877e… stephan 1260 fossil_free(msg);
4dae795… stephan 1261 }else if(jv && !g.json.post.o){
4dae795… stephan 1262 json_err( FSL_JSON_E_INVALID_REQUEST,
4dae795… stephan 1263 "Request envelope must be a JSON Object (not array).", 1 );
4dae795… stephan 1264 }else{ /* generic error message */
4dae795… stephan 1265 json_err( FSL_JSON_E_INVALID_REQUEST, NULL, 1 );
4dae795… stephan 1266 }
796dcfe… drh 1267 fossil_exit( g.isHTTP ? 0 : 1);
796dcfe… drh 1268 }
796dcfe… drh 1269 #endif /* FOSSIL_ENABLE_JSON */
796dcfe… drh 1270
4f8c897… drh 1271 /*
4f8c897… drh 1272 ** Log HTTP traffic to a file. Begin the log on first use. Close the log
4f8c897… drh 1273 ** when the argument is NULL.
4f8c897… drh 1274 */
4f8c897… drh 1275 void cgi_trace(const char *z){
4f8c897… drh 1276 static FILE *pLog = 0;
4f8c897… drh 1277 if( g.fHttpTrace==0 ) return;
4f8c897… drh 1278 if( z==0 ){
4f8c897… drh 1279 if( pLog ) fclose(pLog);
4f8c897… drh 1280 pLog = 0;
4f8c897… drh 1281 return;
4f8c897… drh 1282 }
4f8c897… drh 1283 if( pLog==0 ){
4f8c897… drh 1284 char zFile[50];
1e79991… drh 1285 #if defined(_WIN32)
4f8c897… drh 1286 unsigned r;
4f8c897… drh 1287 sqlite3_randomness(sizeof(r), &r);
4f8c897… drh 1288 sqlite3_snprintf(sizeof(zFile), zFile, "httplog-%08x.txt", r);
1e79991… drh 1289 #else
1e79991… drh 1290 sqlite3_snprintf(sizeof(zFile), zFile, "httplog-%05d.txt", getpid());
1e79991… drh 1291 #endif
4f8c897… drh 1292 pLog = fossil_fopen(zFile, "wb");
4f8c897… drh 1293 if( pLog ){
4f8c897… drh 1294 fprintf(stderr, "# open log on %s\n", zFile);
4f8c897… drh 1295 }else{
4f8c897… drh 1296 fprintf(stderr, "# failed to open %s\n", zFile);
4f8c897… drh 1297 return;
4f8c897… drh 1298 }
4f8c897… drh 1299 }
4f8c897… drh 1300 fputs(z, pLog);
4f8c897… drh 1301 }
4f8c897… drh 1302
a2e7472… drh 1303 /* Forward declaration */
a8e33fb… drh 1304 static NORETURN void malformed_request(const char *zMsg, ...);
1b6ec17… stephan 1305
1b6ec17… stephan 1306 /*
1862890… stephan 1307 ** Checks the QUERY_STRING environment variable, sets it up via
1862890… stephan 1308 ** add_param_list() and, if found, applies its "skin" setting. Returns
1862890… stephan 1309 ** 0 if no QUERY_STRING is set, else it returns a bitmask of:
1862890… stephan 1310 **
1862890… stephan 1311 ** 0x01 = QUERY_STRING was set up
1862890… stephan 1312 ** 0x02 = "skin" URL param arg was processed
1862890… stephan 1313 ** 0x04 = "x-f-l-c" cookie arg was processed.
1862890… stephan 1314 **
1862890… stephan 1315 * In the case of the skin, the cookie may still need flushing
1862890… stephan 1316 ** by the page, via cookie_render().
1b6ec17… stephan 1317 */
1b6ec17… stephan 1318 int cgi_setup_query_string(void){
1b6ec17… stephan 1319 int rc = 0;
1b6ec17… stephan 1320 char * z = (char*)P("QUERY_STRING");
1b6ec17… stephan 1321 if( z ){
1862890… stephan 1322 rc = 0x01;
1b6ec17… stephan 1323 z = fossil_strdup(z);
0c1419a… stephan 1324 add_param_list(z, '&', 0);
1b6ec17… stephan 1325 z = (char*)P("skin");
5feac63… stephan 1326 if( z ){
24e015d… drh 1327 char *zErr = skin_use_alternative(z, 2, SKIN_FROM_QPARAM);
1862890… stephan 1328 rc |= 0x02;
5feac63… stephan 1329 if( !zErr && P("once")==0 ){
1b6ec17… stephan 1330 cookie_write_parameter("skin","skin",z);
5feac63… stephan 1331 /* Per /chat discussion, passing ?skin=... without "once"
5feac63… stephan 1332 ** implies the "udc" argument, so we force that into the
5feac63… stephan 1333 ** environment here. */
5feac63… stephan 1334 cgi_set_parameter_nocopy("udc", "1", 1);
1b6ec17… stephan 1335 }
1b6ec17… stephan 1336 fossil_free(zErr);
1b6ec17… stephan 1337 }
1862890… stephan 1338 }
1862890… stephan 1339 if( !g.syncInfo.zLoginCard && 0!=(z=(char*)P("x-f-l-c")) ){
ca90659… stephan 1340 /* x-f-l-c (X-Fossil-Login-Card) transmitted via cookie instead of
ca90659… stephan 1341 ** in the sync payload. The format of this value is the same as a
ca90659… stephan 1342 ** "login" card, as parsed by xfer.c:page_xfer(). */
1862890… stephan 1343 rc |= 0x04;
1862890… stephan 1344 g.syncInfo.zLoginCard = fossil_strdup(z);
1862890… stephan 1345 g.syncInfo.fLoginCardMode |= 0x02;
1862890… stephan 1346 cgi_delete_parameter("x-f-l-c");
1b6ec17… stephan 1347 }
1b6ec17… stephan 1348 return rc;
1b6ec17… stephan 1349 }
dbda8d6… drh 1350
dbda8d6… drh 1351 /*
dbda8d6… drh 1352 ** Initialize the query parameter database. Information is pulled from
dbda8d6… drh 1353 ** the QUERY_STRING environment variable (if it exists), from standard
dbda8d6… drh 1354 ** input if there is POST data, and from HTTP_COOKIE.
a68280c… drh 1355 **
63a84cb… drh 1356 ** REQUEST_URI, PATH_INFO, and SCRIPT_NAME are related as follows:
a68280c… drh 1357 **
a68280c… drh 1358 ** REQUEST_URI == SCRIPT_NAME + PATH_INFO
e514eee… drh 1359 **
e514eee… drh 1360 ** Or if QUERY_STRING is not empty:
e514eee… drh 1361 **
e514eee… drh 1362 ** REQUEST_URI == SCRIPT_NAME + PATH_INFO + '?' + QUERY_STRING
140cb31… drh 1363 **
63a84cb… drh 1364 ** Where "+" means concatenate. Fossil requires SCRIPT_NAME. If
63a84cb… drh 1365 ** REQUEST_URI is provided but PATH_INFO is not, then PATH_INFO is
63a84cb… drh 1366 ** computed from REQUEST_URI and SCRIPT_NAME. If PATH_INFO is provided
63a84cb… drh 1367 ** but REQUEST_URI is not, then compute REQUEST_URI from PATH_INFO and
63a84cb… drh 1368 ** SCRIPT_NAME. If neither REQUEST_URI nor PATH_INFO are provided, then
63a84cb… drh 1369 ** assume that PATH_INFO is an empty string and set REQUEST_URI equal
63a84cb… drh 1370 ** to PATH_INFO.
63a84cb… drh 1371 **
140cb31… drh 1372 ** Sometimes PATH_INFO is missing and SCRIPT_NAME is not a prefix of
140cb31… drh 1373 ** REQUEST_URI. (See https://fossil-scm.org/forum/forumpost/049e8650ed)
140cb31… drh 1374 ** In that case, truncate SCRIPT_NAME so that it is a proper prefix
140cb31… drh 1375 ** of REQUEST_URI.
140cb31… drh 1376 **
63a84cb… drh 1377 ** SCGI typically omits PATH_INFO. CGI sometimes omits REQUEST_URI and
63a84cb… drh 1378 ** PATH_INFO when it is empty.
d6f6934… drh 1379 **
d6f6934… drh 1380 ** CGI Parameter quick reference:
d6f6934… drh 1381 **
e514eee… drh 1382 ** REQUEST_URI
e514eee… drh 1383 ** _____________|________________
e514eee… drh 1384 ** / \
e514eee… drh 1385 ** https://fossil-scm.org/forum/info/12736b30c072551a?t=c
e514eee… drh 1386 ** \___/ \____________/\____/\____________________/ \_/
e514eee… drh 1387 ** | | | | |
e514eee… drh 1388 ** | HTTP_HOST | PATH_INFO QUERY_STRING
e514eee… drh 1389 ** | |
e514eee… drh 1390 ** REQUEST_SCHEMA SCRIPT_NAME
275da70… danield 1391 **
dbda8d6… drh 1392 */
dbda8d6… drh 1393 void cgi_init(void){
dbda8d6… drh 1394 char *z;
dbda8d6… drh 1395 const char *zType;
ea09902… danield 1396 const char *zSemi;
dbda8d6… drh 1397 int len;
a2e7472… drh 1398 const char *zRequestUri = cgi_parameter("REQUEST_URI",0);
9601b6c… drh 1399 const char *zScriptName = cgi_parameter("SCRIPT_NAME",0);
9601b6c… drh 1400 const char *zPathInfo = cgi_parameter("PATH_INFO",0);
a8e33fb… drh 1401 const char *zContentLength = 0;
c06e0b2… drh 1402 #ifdef _WIN32
c06e0b2… drh 1403 const char *zServerSoftware = cgi_parameter("SERVER_SOFTWARE",0);
c06e0b2… drh 1404 #endif
a2e7472… drh 1405
796dcfe… drh 1406 #ifdef FOSSIL_ENABLE_JSON
e7f13b8… stephan 1407 const int noJson = P("no_json")!=0;
796dcfe… drh 1408 #endif
796dcfe… drh 1409 g.isHTTP = 1;
b312f5f… drh 1410 cgi_destination(CGI_BODY);
d6f6934… drh 1411
d6f6934… drh 1412 /* We must have SCRIPT_NAME. If the web server did not supply it, try
d6f6934… drh 1413 ** to compute it from REQUEST_URI and PATH_INFO. */
d6f6934… drh 1414 if( zScriptName==0 ){
d6f6934… drh 1415 if( zRequestUri==0 || zPathInfo==0 ){
d6f6934… drh 1416 malformed_request("missing SCRIPT_NAME"); /* Does not return */
d6f6934… drh 1417 }
ea09902… danield 1418 z = (char*)strstr(zRequestUri,zPathInfo);
e514eee… drh 1419 if( z==0 ){
e514eee… drh 1420 malformed_request("PATH_INFO not found in REQUEST_URI");
d6f6934… drh 1421 }
e514eee… drh 1422 zScriptName = fossil_strndup(zRequestUri,(int)(z-zRequestUri));
d6f6934… drh 1423 cgi_set_parameter("SCRIPT_NAME", zScriptName);
d6f6934… drh 1424 }
d6f6934… drh 1425
c06e0b2… drh 1426 #ifdef _WIN32
c06e0b2… drh 1427 /* The Microsoft IIS web server does not define REQUEST_URI, instead it uses
c06e0b2… drh 1428 ** PATH_INFO for virtually the same purpose. Define REQUEST_URI the same as
275da70… danield 1429 ** PATH_INFO and redefine PATH_INFO with SCRIPT_NAME removed from the
c06e0b2… drh 1430 ** beginning. */
c06e0b2… drh 1431 if( zServerSoftware && strstr(zServerSoftware, "Microsoft-IIS") ){
c06e0b2… drh 1432 int i, j;
c06e0b2… drh 1433 cgi_set_parameter("REQUEST_URI", zPathInfo);
c06e0b2… drh 1434 for(i=0; zPathInfo[i]==zScriptName[i] && zPathInfo[i]; i++){}
c06e0b2… drh 1435 for(j=i; zPathInfo[j] && zPathInfo[j]!='?'; j++){}
140cb31… drh 1436 zPathInfo = fossil_strndup(zPathInfo+i, j-i);
c06e0b2… drh 1437 cgi_replace_parameter("PATH_INFO", zPathInfo);
c06e0b2… drh 1438 }
c06e0b2… drh 1439 #endif
a68280c… drh 1440 if( zRequestUri==0 ){
a68280c… drh 1441 const char *z = zPathInfo;
e514eee… drh 1442 const char *zQS = cgi_parameter("QUERY_STRING",0);
a68280c… drh 1443 if( zPathInfo==0 ){
a68280c… drh 1444 malformed_request("missing PATH_INFO and/or REQUEST_URI");
a68280c… drh 1445 }
a68280c… drh 1446 if( z[0]=='/' ) z++;
e514eee… drh 1447 if( zQS && zQS[0] ){
e514eee… drh 1448 zRequestUri = mprintf("%s/%s?%s", zScriptName, z, zQS);
e514eee… drh 1449 }else{
e514eee… drh 1450 zRequestUri = mprintf("%s/%s", zScriptName, z);
e514eee… drh 1451 }
a68280c… drh 1452 cgi_set_parameter("REQUEST_URI", zRequestUri);
a68280c… drh 1453 }
a68280c… drh 1454 if( zPathInfo==0 ){
a2e7472… drh 1455 int i, j;
a2e7472… drh 1456 for(i=0; zRequestUri[i]==zScriptName[i] && zRequestUri[i]; i++){}
d01b3c9… drh 1457 for(j=i; zRequestUri[j] && zRequestUri[j]!='?'; j++){}
140cb31… drh 1458 zPathInfo = fossil_strndup(zRequestUri+i, j-i);
140cb31… drh 1459 cgi_set_parameter_nocopy("PATH_INFO", zPathInfo, 0);
140cb31… drh 1460 if( j>i && zScriptName[i]!=0 ){
140cb31… drh 1461 /* If SCRIPT_NAME is not a prefix of REQUEST_URI, truncate it so
140cb31… drh 1462 ** that it is. See https://fossil-scm.org/forum/forumpost/049e8650ed
140cb31… drh 1463 */
140cb31… drh 1464 char *zNew = fossil_strndup(zScriptName, i);
140cb31… drh 1465 cgi_replace_parameter("SCRIPT_NAME", zNew);
140cb31… drh 1466 }
a2e7472… drh 1467 }
39bef92… stephan 1468 #ifdef FOSSIL_ENABLE_JSON
e7f13b8… stephan 1469 if(noJson==0 && json_request_is_json_api(zPathInfo)){
39bef92… stephan 1470 /* We need to change some following behaviour depending on whether
39bef92… stephan 1471 ** we are operating in JSON mode or not. We cannot, however, be
39bef92… stephan 1472 ** certain whether we should/need to be in JSON mode until the
39bef92… stephan 1473 ** PATH_INFO is set up.
39bef92… stephan 1474 */
39bef92… stephan 1475 g.json.isJsonMode = 1;
e7f13b8… stephan 1476 json_bootstrap_early();
39bef92… stephan 1477 }else{
39bef92… stephan 1478 assert(!g.json.isJsonMode &&
39bef92… stephan 1479 "Internal misconfiguration of g.json.isJsonMode");
39bef92… stephan 1480 }
39bef92… stephan 1481 #endif
dbda8d6… drh 1482 z = (char*)P("HTTP_COOKIE");
dbda8d6… drh 1483 if( z ){
140cb31… drh 1484 z = fossil_strdup(z);
0c1419a… stephan 1485 add_param_list(z, ';', 0);
3339420… drh 1486 z = (char*)cookie_value("skin",0);
3339420… drh 1487 if(z){
24e015d… drh 1488 skin_use_alternative(z, 2, SKIN_FROM_COOKIE);
3339420… drh 1489 }
45f3516… jan.nijtmans 1490 }
45f3516… jan.nijtmans 1491
1b6ec17… stephan 1492 cgi_setup_query_string();
796dcfe… drh 1493
796dcfe… drh 1494 z = (char*)P("REMOTE_ADDR");
796dcfe… drh 1495 if( z ){
140cb31… drh 1496 g.zIpAddr = fossil_strdup(z);
19bbd2c… drh 1497 }
19bbd2c… drh 1498
a8e33fb… drh 1499 zContentLength = P("CONTENT_LENGTH");
a8e33fb… drh 1500 if( zContentLength==0 ){
a8e33fb… drh 1501 len = 0;
a8e33fb… drh 1502 if( sqlite3_stricmp(PD("REQUEST_METHOD",""),"POST")==0 ){
a8e33fb… drh 1503 malformed_request("missing CONTENT_LENGTH on a POST method");
a8e33fb… drh 1504 }
a8e33fb… drh 1505 }else{
a8e33fb… drh 1506 len = atoi(zContentLength);
a8e33fb… drh 1507 }
19bbd2c… drh 1508 zType = P("CONTENT_TYPE");
19bbd2c… drh 1509 zSemi = zType ? strchr(zType, ';') : 0;
19bbd2c… drh 1510 if( zSemi ){
140cb31… drh 1511 g.zContentType = fossil_strndup(zType, (int)(zSemi-zType));
19bbd2c… drh 1512 zType = g.zContentType;
19bbd2c… drh 1513 }else{
19bbd2c… drh 1514 g.zContentType = zType;
19bbd2c… drh 1515 }
98b16c7… drh 1516 blob_zero(&g.cgiIn);
796dcfe… drh 1517 if( len>0 && zType ){
c5c7dd5… drh 1518 if( blob_read_from_cgi(&g.cgiIn, len)<len ){
c5c7dd5… drh 1519 char *zMsg = mprintf("CGI content-length mismatch: Wanted %d bytes"
c5c7dd5… drh 1520 " but got only %d\n", len, blob_size(&g.cgiIn));
c5c7dd5… drh 1521 malformed_request(zMsg);
c5c7dd5… drh 1522 }
ec56c69… drh 1523 if( fossil_strcmp(zType, "application/x-fossil")==0 ){
796dcfe… drh 1524 blob_uncompress(&g.cgiIn, &g.cgiIn);
796dcfe… drh 1525 }
796dcfe… drh 1526 #ifdef FOSSIL_ENABLE_JSON
c5c7dd5… drh 1527 if( noJson==0 && g.json.isJsonMode!=0
c5c7dd5… drh 1528 && json_can_consume_content_type(zType)!=0 ){
c5c7dd5… drh 1529 cgi_parse_POST_JSON(&g.cgiIn);
c5c7dd5… drh 1530 cgi_set_content_type(json_guess_content_type());
796dcfe… drh 1531 }
c5c7dd5… drh 1532 #endif /* FOSSIL_ENABLE_JSON */
796dcfe… drh 1533 }
ec56c69… drh 1534 }
796dcfe… drh 1535
ec56c69… drh 1536 /*
ec56c69… drh 1537 ** Decode POST parameter information in the cgiIn content, if any.
ec56c69… drh 1538 */
ec56c69… drh 1539 void cgi_decode_post_parameters(void){
ec56c69… drh 1540 int len = blob_size(&g.cgiIn);
ec56c69… drh 1541 if( len==0 ) return;
ec56c69… drh 1542 if( fossil_strcmp(g.zContentType,"application/x-www-form-urlencoded")==0
7fcb462… stephan 1543 || fossil_strncmp(g.zContentType,"multipart/form-data",19)==0
ec56c69… drh 1544 ){
ec56c69… drh 1545 char *z = blob_str(&g.cgiIn);
ec56c69… drh 1546 cgi_trace(z);
ec56c69… drh 1547 if( g.zContentType[0]=='a' ){
0c1419a… stephan 1548 add_param_list(z, '&', 1);
ec56c69… drh 1549 }else{
ec56c69… drh 1550 process_multipart_form_data(z, len);
ec56c69… drh 1551 }
ec56c69… drh 1552 blob_init(&g.cgiIn, 0, 0);
ec56c69… drh 1553 }
dbda8d6… drh 1554 }
dbda8d6… drh 1555
dbda8d6… drh 1556 /*
dbda8d6… drh 1557 ** This is the comparison function used to sort the aParamQP[] array of
dbda8d6… drh 1558 ** query parameters and cookies.
dbda8d6… drh 1559 */
dbda8d6… drh 1560 static int qparam_compare(const void *a, const void *b){
dbda8d6… drh 1561 struct QParam *pA = (struct QParam*)a;
dbda8d6… drh 1562 struct QParam *pB = (struct QParam*)b;
dbda8d6… drh 1563 int c;
32ad9a1… drh 1564 c = fossil_strcmp(pA->zName, pB->zName);
dbda8d6… drh 1565 if( c==0 ){
dbda8d6… drh 1566 c = pA->seq - pB->seq;
dbda8d6… drh 1567 }
dbda8d6… drh 1568 return c;
dbda8d6… drh 1569 }
dbda8d6… drh 1570
dbda8d6… drh 1571 /*
dbda8d6… drh 1572 ** Return the value of a query parameter or cookie whose name is zName.
dbda8d6… drh 1573 ** If there is no query parameter or cookie named zName and the first
dbda8d6… drh 1574 ** character of zName is uppercase, then check to see if there is an
dbda8d6… drh 1575 ** environment variable by that name and return it if there is. As
dbda8d6… drh 1576 ** a last resort when nothing else matches, return zDefault.
dbda8d6… drh 1577 */
dbda8d6… drh 1578 const char *cgi_parameter(const char *zName, const char *zDefault){
dbda8d6… drh 1579 int lo, hi, mid, c;
dbda8d6… drh 1580
dbda8d6… drh 1581 /* The sortQP flag is set whenever a new query parameter is inserted.
dbda8d6… drh 1582 ** It indicates that we need to resort the query parameters.
dbda8d6… drh 1583 */
dbda8d6… drh 1584 if( sortQP ){
dbda8d6… drh 1585 int i, j;
dbda8d6… drh 1586 qsort(aParamQP, nUsedQP, sizeof(aParamQP[0]), qparam_compare);
dbda8d6… drh 1587 sortQP = 0;
dbda8d6… drh 1588 /* After sorting, remove duplicate parameters. The secondary sort
dbda8d6… drh 1589 ** key is aParamQP[].seq and we keep the first entry. That means
dbda8d6… drh 1590 ** with duplicate calls to cgi_set_parameter() the second and
dbda8d6… drh 1591 ** subsequent calls are effectively no-ops. */
dbda8d6… drh 1592 for(i=j=1; i<nUsedQP; i++){
32ad9a1… drh 1593 if( fossil_strcmp(aParamQP[i].zName,aParamQP[i-1].zName)==0 ){
dbda8d6… drh 1594 continue;
dbda8d6… drh 1595 }
dbda8d6… drh 1596 if( j<i ){
dbda8d6… drh 1597 memcpy(&aParamQP[j], &aParamQP[i], sizeof(aParamQP[j]));
dbda8d6… drh 1598 }
dbda8d6… drh 1599 j++;
dbda8d6… drh 1600 }
dbda8d6… drh 1601 nUsedQP = j;
dbda8d6… drh 1602 }
dbda8d6… drh 1603
4a7760e… drh 1604 /* Invoking with a NULL zName is just a way to cause the parameters
4a7760e… drh 1605 ** to be sorted. So go ahead and bail out in that case */
4a7760e… drh 1606 if( zName==0 || zName[0]==0 ) return 0;
4a7760e… drh 1607
dbda8d6… drh 1608 /* Do a binary search for a matching query parameter */
dbda8d6… drh 1609 lo = 0;
dbda8d6… drh 1610 hi = nUsedQP-1;
dbda8d6… drh 1611 while( lo<=hi ){
dbda8d6… drh 1612 mid = (lo+hi)/2;
32ad9a1… drh 1613 c = fossil_strcmp(aParamQP[mid].zName, zName);
dbda8d6… drh 1614 if( c==0 ){
dbda8d6… drh 1615 CGIDEBUG(("mem-match [%s] = [%s]\n", zName, aParamQP[mid].zValue));
57f1e87… drh 1616 aParamQP[mid].isFetched = 1;
dbda8d6… drh 1617 return aParamQP[mid].zValue;
dbda8d6… drh 1618 }else if( c>0 ){
dbda8d6… drh 1619 hi = mid-1;
dbda8d6… drh 1620 }else{
dbda8d6… drh 1621 lo = mid+1;
dbda8d6… drh 1622 }
dbda8d6… drh 1623 }
dbda8d6… drh 1624
dbda8d6… drh 1625 /* If no match is found and the name begins with an upper-case
dbda8d6… drh 1626 ** letter, then check to see if there is an environment variable
d6f6934… drh 1627 ** with the given name.
dbda8d6… drh 1628 */
4a7760e… drh 1629 if( fossil_isupper(zName[0]) ){
5715208… drh 1630 const char *zValue = fossil_getenv(zName);
d6f6934… drh 1631 if( zValue ){
f8a2aa0… drh 1632 cgi_set_parameter_nocopy(zName, zValue, 0);
dbda8d6… drh 1633 CGIDEBUG(("env-match [%s] = [%s]\n", zName, zValue));
dbda8d6… drh 1634 return zValue;
dbda8d6… drh 1635 }
dbda8d6… drh 1636 }
dbda8d6… drh 1637 CGIDEBUG(("no-match [%s]\n", zName));
dbda8d6… drh 1638 return zDefault;
534c10f… stephan 1639 }
534c10f… stephan 1640
534c10f… stephan 1641 /*
de66eea… drh 1642 ** Return TRUE if the specific parameter exists and is a query parameter.
de66eea… drh 1643 ** Return FALSE if the parameter is a cookie or environment variable.
de66eea… drh 1644 */
de66eea… drh 1645 int cgi_is_qp(const char *zName){
de66eea… drh 1646 int i;
de66eea… drh 1647 if( zName==0 || fossil_isupper(zName[0]) ) return 0;
de66eea… drh 1648 for(i=0; i<nUsedQP; i++){
de66eea… drh 1649 if( fossil_strcmp(aParamQP[i].zName,zName)==0 ){
de66eea… drh 1650 return aParamQP[i].isQP;
de66eea… drh 1651 }
de66eea… drh 1652 }
de66eea… drh 1653 return 0;
de66eea… drh 1654 }
de66eea… drh 1655
de66eea… drh 1656 /*
534c10f… stephan 1657 ** Renders the "begone, spider" page and exits.
534c10f… stephan 1658 */
57f1e87… drh 1659 static void cgi_begone_spider(const char *zName){
534c10f… stephan 1660 Blob content = empty_blob;
534c10f… stephan 1661 cgi_set_content(&content);
534c10f… stephan 1662 style_set_current_feature("test");
57f1e87… drh 1663 style_submenu_enable(0);
d3cb62f… drh 1664 style_header("Malicious Query Detected");
57f1e87… drh 1665 @ <h2>Begone, Knave!</h2>
57f1e87… drh 1666 @ <p>This page was generated because Fossil detected an (unsuccessful)
57f1e87… drh 1667 @ SQL injection attack or other nefarious content in your HTTP request.
57f1e87… drh 1668 @
57f1e87… drh 1669 @ <p>If you believe you are innocent and have reached this page in error,
57f1e87… drh 1670 @ contact the Fossil developers on the Fossil-SCM Forum. Type
d3cb62f… drh 1671 @ "fossil-scm forum" into any search engine to locate the Fossil-SCM Forum.
534c10f… stephan 1672 style_finish_page();
57f1e87… drh 1673 cgi_set_status(418,"I'm a teapot");
534c10f… stephan 1674 cgi_reply();
0204f4a… drh 1675 fossil_errorlog("Xpossible hack attempt - 418 response on \"%s\"", zName);
534c10f… stephan 1676 exit(0);
534c10f… stephan 1677 }
534c10f… stephan 1678
534c10f… stephan 1679 /*
8612122… drh 1680 ** If looks_like_attack() returns true for the given string, call
eb7fad0… drh 1681 ** cgi_begone_spider() and does not return, else this function has no
534c10f… stephan 1682 ** side effects. The range of checks performed by this function may
534c10f… stephan 1683 ** be extended in the future.
00ae239… drh 1684 **
00ae239… drh 1685 ** Checks are omitted for any logged-in user.
00ae239… drh 1686 **
8612122… drh 1687 ** This is the primary defense against attack. Fossil should easily be
d83638e… danield 1688 ** proof against SQL injection and XSS attacks even without this
8612122… drh 1689 ** routine. Rather, this is an attempt to avoid denial-of-service caused
8612122… drh 1690 ** by persistent spiders that hammer the server with dozens or hundreds of
8612122… drh 1691 ** probes per seconds as they look for vulnerabilities. In other
00ae239… drh 1692 ** words, this is an effort to reduce the CPU load imposed by malicious
8612122… drh 1693 ** spiders. Though those routine might help make attacks harder, it is
8612122… drh 1694 ** not itself an impenetrably barrier against attack and should not be
8612122… drh 1695 ** relied upon as the only defense.
534c10f… stephan 1696 */
57f1e87… drh 1697 void cgi_value_spider_check(const char *zTxt, const char *zName){
8612122… drh 1698 if( g.zLogin==0 && looks_like_attack(zTxt) ){
57f1e87… drh 1699 cgi_begone_spider(zName);
534c10f… stephan 1700 }
534c10f… stephan 1701 }
534c10f… stephan 1702
534c10f… stephan 1703 /*
534c10f… stephan 1704 ** A variant of cgi_parameter() with the same semantics except that if
534c10f… stephan 1705 ** cgi_parameter(zName,zDefault) returns a value other than zDefault
534c10f… stephan 1706 ** then it passes that value to cgi_value_spider_check().
534c10f… stephan 1707 */
8612122… drh 1708 const char *cgi_parameter_no_attack(const char *zName, const char *zDefault){
534c10f… stephan 1709 const char *zTxt = cgi_parameter(zName, zDefault);
534c10f… stephan 1710
534c10f… stephan 1711 if( zTxt!=zDefault ){
57f1e87… drh 1712 cgi_value_spider_check(zTxt, zName);
534c10f… stephan 1713 }
534c10f… stephan 1714 return zTxt;
a339229… drh 1715 }
a339229… drh 1716
a339229… drh 1717 /*
a339229… drh 1718 ** Return the value of the first defined query parameter or cookie whose
a339229… drh 1719 ** name appears in the list of arguments. Or if no parameter is found,
a339229… drh 1720 ** return NULL.
a339229… drh 1721 */
a339229… drh 1722 const char *cgi_coalesce(const char *zName, ...){
a339229… drh 1723 va_list ap;
a339229… drh 1724 const char *z;
a339229… drh 1725 const char *zX;
a339229… drh 1726 if( zName==0 ) return 0;
a339229… drh 1727 z = cgi_parameter(zName, 0);
a339229… drh 1728 va_start(ap, zName);
a339229… drh 1729 while( z==0 && (zX = va_arg(ap,const char*))!=0 ){
a339229… drh 1730 z = cgi_parameter(zX, 0);
a339229… drh 1731 }
a339229… drh 1732 va_end(ap);
a339229… drh 1733 return z;
99fcc43… drh 1734 }
99fcc43… drh 1735
99fcc43… drh 1736 /*
655e782… drh 1737 ** Return the value of a CGI parameter with leading and trailing
99fcc43… drh 1738 ** spaces removed and with internal \r\n changed to just \n
655e782… drh 1739 */
655e782… drh 1740 char *cgi_parameter_trimmed(const char *zName, const char *zDefault){
655e782… drh 1741 const char *zIn;
99fcc43… drh 1742 char *zOut, c;
99fcc43… drh 1743 int i, j;
655e782… drh 1744 zIn = cgi_parameter(zName, 0);
655e782… drh 1745 if( zIn==0 ) zIn = zDefault;
9a2e5f4… drh 1746 if( zIn==0 ) return 0;
655e782… drh 1747 while( fossil_isspace(zIn[0]) ) zIn++;
655e782… drh 1748 zOut = fossil_strdup(zIn);
99fcc43… drh 1749 for(i=j=0; (c = zOut[i])!=0; i++){
99fcc43… drh 1750 if( c=='\r' && zOut[i+1]=='\n' ) continue;
99fcc43… drh 1751 zOut[j++] = c;
99fcc43… drh 1752 }
99fcc43… drh 1753 zOut[j] = 0;
99fcc43… drh 1754 while( j>0 && fossil_isspace(zOut[j-1]) ) zOut[--j] = 0;
655e782… drh 1755 return zOut;
c0c0bae… drh 1756 }
c0c0bae… drh 1757
c0c0bae… drh 1758 /*
c0c0bae… drh 1759 ** Return true if the CGI parameter zName exists and is not equal to 0,
c0c0bae… drh 1760 ** or "no" or "off".
c0c0bae… drh 1761 */
c0c0bae… drh 1762 int cgi_parameter_boolean(const char *zName){
c0c0bae… drh 1763 const char *zIn = cgi_parameter(zName, 0);
c0c0bae… drh 1764 if( zIn==0 ) return 0;
c0c0bae… drh 1765 return zIn[0]==0 || is_truth(zIn);
b77f1aa… drh 1766 }
b77f1aa… drh 1767
b77f1aa… drh 1768 /*
b77f1aa… drh 1769 ** Return either an empty string "" or the string "checked" depending
b77f1aa… drh 1770 ** on whether or not parameter zName has value iValue. If parameter
b77f1aa… drh 1771 ** zName does not exist, that is assumed to be the same as value 0.
b77f1aa… drh 1772 **
b77f1aa… drh 1773 ** This routine implements the PCK(x) and PIF(x,y) macros. The PIF(x,y)
b77f1aa… drh 1774 ** macro generateds " checked" if the value of parameter x equals integer y.
b77f1aa… drh 1775 ** PCK(x) is the same as PIF(x,1). These macros are used to generate
b77f1aa… drh 1776 ** the "checked" attribute on checkbox and radio controls of forms.
b77f1aa… drh 1777 */
b77f1aa… drh 1778 const char *cgi_parameter_checked(const char *zName, int iValue){
b77f1aa… drh 1779 const char *zIn = cgi_parameter(zName,0);
b77f1aa… drh 1780 int x;
b77f1aa… drh 1781 if( zIn==0 ){
b77f1aa… drh 1782 x = 0;
b77f1aa… drh 1783 }else if( !fossil_isdigit(zIn[0]) ){
b77f1aa… drh 1784 x = is_truth(zIn);
b77f1aa… drh 1785 }else{
b77f1aa… drh 1786 x = atoi(zIn);
b77f1aa… drh 1787 }
b77f1aa… drh 1788 return x==iValue ? "checked" : "";
db0c512… drh 1789 }
db0c512… drh 1790
db0c512… drh 1791 /*
d0305b3… aku 1792 ** Return the name of the i-th CGI parameter. Return NULL if there
db0c512… drh 1793 ** are fewer than i registered CGI parameters.
d0305b3… aku 1794 */
d0305b3… aku 1795 const char *cgi_parameter_name(int i){
d0305b3… aku 1796 if( i>=0 && i<nUsedQP ){
d0305b3… aku 1797 return aParamQP[i].zName;
d0305b3… aku 1798 }else{
d0305b3… aku 1799 return 0;
d0305b3… aku 1800 }
dbda8d6… drh 1801 }
dbda8d6… drh 1802
dbda8d6… drh 1803 /*
dbda8d6… drh 1804 ** Print CGI debugging messages.
dbda8d6… drh 1805 */
dbda8d6… drh 1806 void cgi_debug(const char *zFormat, ...){
dbda8d6… drh 1807 va_list ap;
dbda8d6… drh 1808 if( g.fDebug ){
dbda8d6… drh 1809 va_start(ap, zFormat);
dbda8d6… drh 1810 vfprintf(g.fDebug, zFormat, ap);
dbda8d6… drh 1811 va_end(ap);
dbda8d6… drh 1812 fflush(g.fDebug);
dbda8d6… drh 1813 }
dbda8d6… drh 1814 }
dbda8d6… drh 1815
dbda8d6… drh 1816 /*
dbda8d6… drh 1817 ** Return true if any of the query parameters in the argument
dbda8d6… drh 1818 ** list are defined.
dbda8d6… drh 1819 */
dbda8d6… drh 1820 int cgi_any(const char *z, ...){
dbda8d6… drh 1821 va_list ap;
dbda8d6… drh 1822 char *z2;
dbda8d6… drh 1823 if( cgi_parameter(z,0)!=0 ) return 1;
dbda8d6… drh 1824 va_start(ap, z);
dbda8d6… drh 1825 while( (z2 = va_arg(ap, char*))!=0 ){
dbda8d6… drh 1826 if( cgi_parameter(z2,0)!=0 ) return 1;
dbda8d6… drh 1827 }
dbda8d6… drh 1828 va_end(ap);
dbda8d6… drh 1829 return 0;
dbda8d6… drh 1830 }
dbda8d6… drh 1831
dbda8d6… drh 1832 /*
dbda8d6… drh 1833 ** Return true if all of the query parameters in the argument list
dbda8d6… drh 1834 ** are defined.
dbda8d6… drh 1835 */
dbda8d6… drh 1836 int cgi_all(const char *z, ...){
dbda8d6… drh 1837 va_list ap;
dbda8d6… drh 1838 char *z2;
dbda8d6… drh 1839 if( cgi_parameter(z,0)==0 ) return 0;
dbda8d6… drh 1840 va_start(ap, z);
dbda8d6… drh 1841 while( (z2 = va_arg(ap, char*))==0 ){
dbda8d6… drh 1842 if( cgi_parameter(z2,0)==0 ) return 0;
dbda8d6… drh 1843 }
dbda8d6… drh 1844 va_end(ap);
dbda8d6… drh 1845 return 1;
dbda8d6… drh 1846 }
dbda8d6… drh 1847
dbda8d6… drh 1848 /*
4a7760e… drh 1849 ** Load all relevant environment variables into the parameter buffer.
4a7760e… drh 1850 ** Invoke this routine prior to calling cgi_print_all() in order to see
4a7760e… drh 1851 ** the full CGI environment. This routine intended for debugging purposes
4a7760e… drh 1852 ** only.
4a7760e… drh 1853 */
4a7760e… drh 1854 void cgi_load_environment(void){
4a7760e… drh 1855 /* The following is a list of environment variables that Fossil considers
4a7760e… drh 1856 ** to be "relevant". */
4a7760e… drh 1857 static const char *const azCgiVars[] = {
4a7760e… drh 1858 "COMSPEC", "DOCUMENT_ROOT", "GATEWAY_INTERFACE", "SCGI",
4a7760e… drh 1859 "HTTP_ACCEPT", "HTTP_ACCEPT_CHARSET", "HTTP_ACCEPT_ENCODING",
2ce7110… drh 1860 "HTTP_ACCEPT_LANGUAGE", "HTTP_AUTHENTICATION",
4a7760e… drh 1861 "HTTP_CONNECTION", "HTTP_HOST",
4a7760e… drh 1862 "HTTP_IF_NONE_MATCH", "HTTP_IF_MODIFIED_SINCE",
4a7760e… drh 1863 "HTTP_USER_AGENT", "HTTP_REFERER", "PATH_INFO", "PATH_TRANSLATED",
4a7760e… drh 1864 "QUERY_STRING", "REMOTE_ADDR", "REMOTE_PORT",
282bdf0… drh 1865 "REMOTE_USER", "REQUEST_METHOD", "REQUEST_SCHEME",
f101e94… drh 1866 "REQUEST_URI", "SCRIPT_FILENAME", "SCRIPT_NAME", "SERVER_NAME",
f101e94… drh 1867 "SERVER_PROTOCOL", "HOME", "FOSSIL_HOME", "USERNAME", "USER",
f101e94… drh 1868 "FOSSIL_USER", "SQLITE_TMPDIR", "TMPDIR",
4a7760e… drh 1869 "TEMP", "TMP", "FOSSIL_VFS",
4a7760e… drh 1870 "FOSSIL_FORCE_TICKET_MODERATION", "FOSSIL_FORCE_WIKI_MODERATION",
4a7760e… drh 1871 "FOSSIL_TCL_PATH", "TH1_DELETE_INTERP", "TH1_ENABLE_DOCS",
4a7760e… drh 1872 "TH1_ENABLE_HOOKS", "TH1_ENABLE_TCL", "REMOTE_HOST",
9c40ddb… drh 1873 "CONTENT_TYPE", "CONTENT_LENGTH",
4a7760e… drh 1874 };
4a7760e… drh 1875 int i;
4a7760e… drh 1876 for(i=0; i<count(azCgiVars); i++) (void)P(azCgiVars[i]);
4a7760e… drh 1877 }
4a7760e… drh 1878
4a7760e… drh 1879 /*
4a7760e… drh 1880 ** Print all query parameters on standard output.
4a7760e… drh 1881 ** This is used for testing and debugging.
4d32db8… drh 1882 **
4d32db8… drh 1883 ** Omit the values of the cookies unless showAll is true.
4a7760e… drh 1884 **
4a7760e… drh 1885 ** The eDest parameter determines where the output is shown:
4a7760e… drh 1886 **
4a7760e… drh 1887 ** eDest==0: Rendering as HTML into the CGI reply
0204f4a… drh 1888 ** eDest==1: Written to fossil_trace
4a7760e… drh 1889 ** eDest==2: Written to cgi_debug
0204f4a… drh 1890 ** eDest==3: Written to out (Used only by fossil_errorlog())
4d32db8… drh 1891 */
0204f4a… drh 1892 void cgi_print_all(int showAll, unsigned int eDest, FILE *out){
4d32db8… drh 1893 int i;
dbda8d6… drh 1894 cgi_parameter("",""); /* Force the parameters into sorted order */
dbda8d6… drh 1895 for(i=0; i<nUsedQP; i++){
4d32db8… drh 1896 const char *zName = aParamQP[i].zName;
0204f4a… drh 1897 const char *zValue = aParamQP[i].zValue;
0204f4a… drh 1898 if( fossil_stricmp("HTTP_COOKIE",zName)==0
0204f4a… drh 1899 || fossil_strnicmp("fossil-",zName,7)==0
0204f4a… drh 1900 ){
0204f4a… drh 1901 if( !showAll ) continue;
0204f4a… drh 1902 if( eDest==3 ) zValue = "...";
4a7760e… drh 1903 }
4a7760e… drh 1904 switch( eDest ){
4a7760e… drh 1905 case 0: {
0204f4a… drh 1906 cgi_printf("%h = %h <br>\n", zName, zValue);
4a7760e… drh 1907 break;
4a7760e… drh 1908 }
57f1e87… drh 1909 case 1: {
0204f4a… drh 1910 fossil_trace("%s = %s\n", zName, zValue);
4a7760e… drh 1911 break;
4a7760e… drh 1912 }
4a7760e… drh 1913 case 2: {
0204f4a… drh 1914 cgi_debug("%s = %s\n", zName, zValue);
0204f4a… drh 1915 break;
0204f4a… drh 1916 }
0204f4a… drh 1917 case 3: {
c62e25a… stephan 1918 if( zValue!=0 && strlen(zValue)>100 ){
0204f4a… drh 1919 fprintf(out,"%s = %.100s...\n", zName, zValue);
0204f4a… drh 1920 }else{
0204f4a… drh 1921 fprintf(out,"%s = %s\n", zName, zValue);
0204f4a… drh 1922 }
4a7760e… drh 1923 break;
4a7760e… drh 1924 }
4a7760e… drh 1925 }
7b00def… drh 1926 }
7b00def… drh 1927 }
7b00def… drh 1928
7b00def… drh 1929 /*
7b00def… drh 1930 ** Put information about the N-th parameter into arguments.
7b00def… drh 1931 ** Return non-zero on success, and return 0 if there is no N-th parameter.
7b00def… drh 1932 */
7b00def… drh 1933 int cgi_param_info(
7b00def… drh 1934 int N,
7b00def… drh 1935 const char **pzName,
7b00def… drh 1936 const char **pzValue,
7b00def… drh 1937 int *pbIsQP
7b00def… drh 1938 ){
7b00def… drh 1939 if( N>=0 && N<nUsedQP ){
7b00def… drh 1940 *pzName = aParamQP[N].zName;
7b00def… drh 1941 *pzValue = aParamQP[N].zValue;
7b00def… drh 1942 *pbIsQP = aParamQP[N].isQP;
7b00def… drh 1943 return 1;
7b00def… drh 1944 }else{
7b00def… drh 1945 *pzName = 0;
7b00def… drh 1946 *pzValue = 0;
7b00def… drh 1947 *pbIsQP = 0;
7b00def… drh 1948 return 0;
f8a2aa0… drh 1949 }
f8a2aa0… drh 1950 }
f8a2aa0… drh 1951
f8a2aa0… drh 1952 /*
c0c0bae… drh 1953 ** Export all untagged query parameters (but not cookies or environment
c0c0bae… drh 1954 ** variables) as hidden values of a form.
f8a2aa0… drh 1955 */
f8a2aa0… drh 1956 void cgi_query_parameters_to_hidden(void){
f8a2aa0… drh 1957 int i;
f8a2aa0… drh 1958 const char *zN, *zV;
f8a2aa0… drh 1959 for(i=0; i<nUsedQP; i++){
c0c0bae… drh 1960 if( aParamQP[i].isQP==0 || aParamQP[i].cTag ) continue;
f8a2aa0… drh 1961 zN = aParamQP[i].zName;
f8a2aa0… drh 1962 zV = aParamQP[i].zValue;
f8a2aa0… drh 1963 @ <input type="hidden" name="%h(zN)" value="%h(zV)">
c0c0bae… drh 1964 }
c0c0bae… drh 1965 }
c0c0bae… drh 1966
c0c0bae… drh 1967 /*
c0c0bae… drh 1968 ** Export all untagged query parameters (but not cookies or environment
c0c0bae… drh 1969 ** variables) to the HQuery object.
c0c0bae… drh 1970 */
c0c0bae… drh 1971 void cgi_query_parameters_to_url(HQuery *p){
c0c0bae… drh 1972 int i;
c0c0bae… drh 1973 for(i=0; i<nUsedQP; i++){
c0c0bae… drh 1974 if( aParamQP[i].isQP==0 || aParamQP[i].cTag ) continue;
c0c0bae… drh 1975 url_add_parameter(p, aParamQP[i].zName, aParamQP[i].zValue);
c0c0bae… drh 1976 }
7b00def… drh 1977 }
7b00def… drh 1978
7b00def… drh 1979 /*
aa4159f… drh 1980 ** Reconstruct the URL into memory obtained from fossil_malloc() and
aa4159f… drh 1981 ** return a pointer to that URL.
aa4159f… drh 1982 */
aa4159f… drh 1983 char *cgi_reconstruct_original_url(void){
aa4159f… drh 1984 int i;
aa4159f… drh 1985 char cSep = '?';
aa4159f… drh 1986 Blob url;
aa4159f… drh 1987 blob_init(&url, 0, 0);
aa4159f… drh 1988 blob_appendf(&url, "%s/%s", g.zBaseURL, g.zPath);
aa4159f… drh 1989 for(i=0; i<nUsedQP; i++){
aa4159f… drh 1990 if( aParamQP[i].isQP ){
aa4159f… drh 1991 struct QParam *p = &aParamQP[i];
aa4159f… drh 1992 if( p->zValue && p->zValue[0] ){
aa4159f… drh 1993 blob_appendf(&url, "%c%t=%t", cSep, p->zName, p->zValue);
aa4159f… drh 1994 }else{
aa4159f… drh 1995 blob_appendf(&url, "%c%t", cSep, p->zName);
aa4159f… drh 1996 }
aa4159f… drh 1997 cSep = '&';
aa4159f… drh 1998 }
aa4159f… drh 1999 }
0e675ad… drh 2000 return blob_str(&url);
aa4159f… drh 2001 }
aa4159f… drh 2002
aa4159f… drh 2003 /*
c0c0bae… drh 2004 ** Tag query parameter zName so that it is not exported by
c0c0bae… drh 2005 ** cgi_query_parameters_to_hidden(). Or if zName==0, then
c0c0bae… drh 2006 ** untag all query parameters.
c0c0bae… drh 2007 */
c0c0bae… drh 2008 void cgi_tag_query_parameter(const char *zName){
c0c0bae… drh 2009 int i;
c0c0bae… drh 2010 if( zName==0 ){
c0c0bae… drh 2011 for(i=0; i<nUsedQP; i++) aParamQP[i].cTag = 0;
c0c0bae… drh 2012 }else{
c0c0bae… drh 2013 for(i=0; i<nUsedQP; i++){
c0c0bae… drh 2014 if( strcmp(zName,aParamQP[i].zName)==0 ) aParamQP[i].cTag = 1;
c0c0bae… drh 2015 }
0a51263… drh 2016 }
b8e3dc1… jan.nijtmans 2017 }
dbda8d6… drh 2018
dbda8d6… drh 2019 /*
dbda8d6… drh 2020 ** This routine works like "printf" except that it has the
dbda8d6… drh 2021 ** extra formatting capabilities such as %h and %t.
dbda8d6… drh 2022 */
dbda8d6… drh 2023 void cgi_printf(const char *zFormat, ...){
dbda8d6… drh 2024 va_list ap;
dbda8d6… drh 2025 va_start(ap,zFormat);
b312f5f… drh 2026 vxprintf(pContent,zFormat,ap);
dbda8d6… drh 2027 va_end(ap);
dbda8d6… drh 2028 }
dbda8d6… drh 2029
dbda8d6… drh 2030 /*
dbda8d6… drh 2031 ** This routine works like "vprintf" except that it has the
dbda8d6… drh 2032 ** extra formatting capabilities such as %h and %t.
dbda8d6… drh 2033 */
dbda8d6… drh 2034 void cgi_vprintf(const char *zFormat, va_list ap){
b312f5f… drh 2035 vxprintf(pContent,zFormat,ap);
dbda8d6… drh 2036 }
dbda8d6… drh 2037
dbda8d6… drh 2038
dbda8d6… drh 2039 /*
dbda8d6… drh 2040 ** Send a reply indicating that the HTTP request was malformed
dbda8d6… drh 2041 */
a8e33fb… drh 2042 static NORETURN void malformed_request(const char *zMsg, ...){
a8e33fb… drh 2043 va_list ap;
a8e33fb… drh 2044 char *z;
a8e33fb… drh 2045 va_start(ap, zMsg);
a8e33fb… drh 2046 z = vmprintf(zMsg, ap);
a8e33fb… drh 2047 va_end(ap);
a8e33fb… drh 2048 cgi_set_status(400, "Bad Request");
ae8fc0e… drh 2049 zReplyMimeType = "text/plain";
a8e33fb… drh 2050 if( g.zReqType==0 ) g.zReqType = "WWW";
a8e33fb… drh 2051 if( g.zReqType[0]=='C' && PD("SERVER_SOFTWARE",0)!=0 ){
a8e33fb… drh 2052 const char *zServer = PD("SERVER_SOFTWARE","");
a8e33fb… drh 2053 cgi_printf("Bad CGI Request from \"%s\": %s\n",zServer,z);
a8e33fb… drh 2054 }else{
a8e33fb… drh 2055 cgi_printf("Bad %s Request: %s\n", g.zReqType, z);
a8e33fb… drh 2056 }
a8e33fb… drh 2057 fossil_free(z);
dbda8d6… drh 2058 cgi_reply();
932825b… drh 2059 fossil_exit(0);
dbda8d6… drh 2060 }
dbda8d6… drh 2061
dbda8d6… drh 2062 /*
dbda8d6… drh 2063 ** Panic and die while processing a webpage.
dbda8d6… drh 2064 */
86d2b4e… drh 2065 NORETURN void cgi_panic(const char *zFormat, ...){
dbda8d6… drh 2066 va_list ap;
dbda8d6… drh 2067 cgi_reset_content();
796dcfe… drh 2068 #ifdef FOSSIL_ENABLE_JSON
796dcfe… drh 2069 if( g.json.isJsonMode ){
796dcfe… drh 2070 char * zMsg;
796dcfe… drh 2071 va_start(ap, zFormat);
796dcfe… drh 2072 zMsg = vmprintf(zFormat,ap);
796dcfe… drh 2073 va_end(ap);
796dcfe… drh 2074 json_err( FSL_JSON_E_PANIC, zMsg, 1 );
796dcfe… drh 2075 free(zMsg);
796dcfe… drh 2076 fossil_exit( g.isHTTP ? 0 : 1 );
796dcfe… drh 2077 }else
796dcfe… drh 2078 #endif /* FOSSIL_ENABLE_JSON */
796dcfe… drh 2079 {
796dcfe… drh 2080 cgi_set_status(500, "Internal Server Error");
796dcfe… drh 2081 cgi_printf(
796dcfe… drh 2082 "<html><body><h1>Internal Server Error</h1>\n"
796dcfe… drh 2083 "<plaintext>"
796dcfe… drh 2084 );
796dcfe… drh 2085 va_start(ap, zFormat);
796dcfe… drh 2086 vxprintf(pContent,zFormat,ap);
796dcfe… drh 2087 va_end(ap);
796dcfe… drh 2088 cgi_reply();
796dcfe… drh 2089 fossil_exit(1);
796dcfe… drh 2090 }
796dcfe… drh 2091 }
796dcfe… drh 2092
29b558a… drh 2093 /* z[] is the value of an X-FORWARDED-FOR: line in an HTTP header.
59f790b… joel 2094 ** Return a pointer to a string containing the real IP address, or a
59f790b… joel 2095 ** NULL pointer to stick with the IP address previously computed and
29b558a… drh 2096 ** loaded into g.zIpAddr.
29b558a… drh 2097 */
59f790b… joel 2098 static const char *cgi_accept_forwarded_for(const char *z){
59f790b… joel 2099 int i;
96dcb7e… drh 2100 if( !cgi_is_loopback(g.zIpAddr) ){
96dcb7e… drh 2101 /* Only accept X-FORWARDED-FOR if input coming from the local machine */
96dcb7e… drh 2102 return 0;
96dcb7e… drh 2103 }
59f790b… joel 2104 i = strlen(z)-1;
59f790b… joel 2105 while( i>=0 && z[i]!=',' && !fossil_isspace(z[i]) ) i--;
59f790b… joel 2106 return &z[++i];
29b558a… drh 2107 }
29b558a… drh 2108
dbda8d6… drh 2109 /*
dbda8d6… drh 2110 ** Remove the first space-delimited token from a string and return
dbda8d6… drh 2111 ** a pointer to it. Add a NULL to the string to terminate the token.
dbda8d6… drh 2112 ** Make *zLeftOver point to the start of the next token.
dbda8d6… drh 2113 */
dbda8d6… drh 2114 static char *extract_token(char *zInput, char **zLeftOver){
dbda8d6… drh 2115 char *zResult = 0;
dbda8d6… drh 2116 if( zInput==0 ){
dbda8d6… drh 2117 if( zLeftOver ) *zLeftOver = 0;
dbda8d6… drh 2118 return 0;
dbda8d6… drh 2119 }
2fac809… drh 2120 while( fossil_isspace(*zInput) ){ zInput++; }
dbda8d6… drh 2121 zResult = zInput;
2fac809… drh 2122 while( *zInput && !fossil_isspace(*zInput) ){ zInput++; }
dbda8d6… drh 2123 if( *zInput ){
dbda8d6… drh 2124 *zInput = 0;
dbda8d6… drh 2125 zInput++;
2fac809… drh 2126 while( fossil_isspace(*zInput) ){ zInput++; }
dbda8d6… drh 2127 }
dbda8d6… drh 2128 if( zLeftOver ){ *zLeftOver = zInput; }
dbda8d6… drh 2129 return zResult;
dbda8d6… drh 2130 }
dbda8d6… drh 2131
dbda8d6… drh 2132 /*
7ce8400… drh 2133 ** All possible forms of an IP address. Needed to work around GCC strict
7ce8400… drh 2134 ** aliasing rules.
7ce8400… drh 2135 */
7ce8400… drh 2136 typedef union {
7ce8400… drh 2137 struct sockaddr sa; /* Abstract superclass */
7ce8400… drh 2138 struct sockaddr_in sa4; /* IPv4 */
7ce8400… drh 2139 struct sockaddr_in6 sa6; /* IPv6 */
7ce8400… drh 2140 struct sockaddr_storage sas; /* Should be the maximum of the above 3 */
7ce8400… drh 2141 } address;
7ce8400… drh 2142
7ce8400… drh 2143 /*
9979edb… drh 2144 ** Determine the IP address on the other side of a connection.
9979edb… drh 2145 ** Return a pointer to a string. Or return 0 if unable.
9979edb… drh 2146 **
9979edb… drh 2147 ** The string is held in a static buffer that is overwritten on
9979edb… drh 2148 ** each call.
9979edb… drh 2149 */
9979edb… drh 2150 char *cgi_remote_ip(int fd){
7ce8400… drh 2151 address remoteAddr;
7ce8400… drh 2152 socklen_t size = sizeof(remoteAddr);
7ce8400… drh 2153 static char zHost[NI_MAXHOST];
7ce8400… drh 2154 if( getpeername(0, &remoteAddr.sa, &size) ){
7ce8400… drh 2155 return 0;
7ce8400… drh 2156 }
7ce8400… drh 2157 if( getnameinfo(&remoteAddr.sa, size, zHost, sizeof(zHost), 0, 0,
7ce8400… drh 2158 NI_NUMERICHOST) ){
9979edb… drh 2159 return 0;
9979edb… drh 2160 }
7ce8400… drh 2161 return zHost;
9979edb… drh 2162 }
9979edb… drh 2163
9979edb… drh 2164 /*
dbda8d6… drh 2165 ** This routine handles a single HTTP request which is coming in on
ecb85f6… drh 2166 ** g.httpIn and which replies on g.httpOut
dbda8d6… drh 2167 **
ecb85f6… drh 2168 ** The HTTP request is read from g.httpIn and is used to initialize
ecb85f6… drh 2169 ** entries in the cgi_parameter() hash, as if those entries were
ecb85f6… drh 2170 ** environment variables. A call to cgi_init() completes
dbda8d6… drh 2171 ** the setup. Once all the setup is finished, this procedure returns
dbda8d6… drh 2172 ** and subsequent code handles the actual generation of the webpage.
dbda8d6… drh 2173 */
e2e016c… drh 2174 void cgi_handle_http_request(const char *zIpAddr){
dbda8d6… drh 2175 char *z, *zToken;
dbda8d6… drh 2176 int i;
282bdf0… drh 2177 const char *zScheme = "http";
dbda8d6… drh 2178 char zLine[2000]; /* A single line of input. */
dcc4866… drh 2179 g.fullHttpReply = 1;
a8e33fb… drh 2180 g.zReqType = "HTTP";
1862890… stephan 2181
f6263bb… drh 2182 if( cgi_fgets(zLine, sizeof(zLine))==0 ){
a8e33fb… drh 2183 malformed_request("missing header");
dbda8d6… drh 2184 }
03f07b5… drh 2185 blob_append(&g.httpHeader, zLine, -1);
4f8c897… drh 2186 cgi_trace(zLine);
dbda8d6… drh 2187 zToken = extract_token(zLine, &z);
dbda8d6… drh 2188 if( zToken==0 ){
a2e7472… drh 2189 malformed_request("malformed HTTP header");
dbda8d6… drh 2190 }
2ac4ab2… drh 2191 if( fossil_strcmp(zToken,"GET")!=0
2ac4ab2… drh 2192 && fossil_strcmp(zToken,"POST")!=0
2ac4ab2… drh 2193 && fossil_strcmp(zToken,"HEAD")!=0
2ac4ab2… drh 2194 ){
9cabc13… florian 2195 malformed_request("unsupported HTTP method: \"%s\" - Fossil only supports "
a8e33fb… drh 2196 "GET, POST, and HEAD", zToken);
dbda8d6… drh 2197 }
dbda8d6… drh 2198 cgi_setenv("GATEWAY_INTERFACE","CGI/1.0");
dbda8d6… drh 2199 cgi_setenv("REQUEST_METHOD",zToken);
dbda8d6… drh 2200 zToken = extract_token(z, &z);
dbda8d6… drh 2201 if( zToken==0 ){
a8e33fb… drh 2202 malformed_request("malformed URI in the HTTP header");
dbda8d6… drh 2203 }
e514eee… drh 2204 cgi_setenv("REQUEST_URI", zToken);
a2e7472… drh 2205 cgi_setenv("SCRIPT_NAME", "");
dbda8d6… drh 2206 for(i=0; zToken[i] && zToken[i]!='?'; i++){}
dbda8d6… drh 2207 if( zToken[i] ) zToken[i++] = 0;
dbda8d6… drh 2208 cgi_setenv("PATH_INFO", zToken);
dbda8d6… drh 2209 cgi_setenv("QUERY_STRING", &zToken[i]);
9979edb… drh 2210 if( zIpAddr==0 ){
898a70c… stephan 2211 zIpAddr = cgi_remote_ip(fossil_fileno(g.httpIn));
e2e016c… drh 2212 }
45f3516… jan.nijtmans 2213 if( zIpAddr ){
04f7535… drh 2214 cgi_setenv("REMOTE_ADDR", zIpAddr);
140cb31… drh 2215 g.zIpAddr = fossil_strdup(zIpAddr);
03f07b5… drh 2216 }
45f3516… jan.nijtmans 2217
03f07b5… drh 2218 /* Get all the optional fields that follow the first line.
03f07b5… drh 2219 */
f6263bb… drh 2220 while( cgi_fgets(zLine,sizeof(zLine)) ){
03f07b5… drh 2221 char *zFieldName;
03f07b5… drh 2222 char *zVal;
03f07b5… drh 2223
03f07b5… drh 2224 cgi_trace(zLine);
03f07b5… drh 2225 blob_append(&g.httpHeader, zLine, -1);
03f07b5… drh 2226 zFieldName = extract_token(zLine,&zVal);
03f07b5… drh 2227 if( zFieldName==0 || *zFieldName==0 ) break;
03f07b5… drh 2228 while( fossil_isspace(*zVal) ){ zVal++; }
03f07b5… drh 2229 i = strlen(zVal);
03f07b5… drh 2230 while( i>0 && fossil_isspace(zVal[i-1]) ){ i--; }
03f07b5… drh 2231 zVal[i] = 0;
03f07b5… drh 2232 for(i=0; zFieldName[i]; i++){
03f07b5… drh 2233 zFieldName[i] = fossil_tolower(zFieldName[i]);
03f07b5… drh 2234 }
3f4b5d3… joel 2235 if( fossil_strcmp(zFieldName,"accept-encoding:")==0 ){
cfc7aca… drh 2236 cgi_setenv("HTTP_ACCEPT_ENCODING", zVal);
3f4b5d3… joel 2237 }else if( fossil_strcmp(zFieldName,"content-length:")==0 ){
03f07b5… drh 2238 cgi_setenv("CONTENT_LENGTH", zVal);
03f07b5… drh 2239 }else if( fossil_strcmp(zFieldName,"content-type:")==0 ){
03f07b5… drh 2240 cgi_setenv("CONTENT_TYPE", zVal);
03f07b5… drh 2241 }else if( fossil_strcmp(zFieldName,"cookie:")==0 ){
03f07b5… drh 2242 cgi_setenv("HTTP_COOKIE", zVal);
03f07b5… drh 2243 }else if( fossil_strcmp(zFieldName,"https:")==0 ){
03f07b5… drh 2244 cgi_setenv("HTTPS", zVal);
282bdf0… drh 2245 zScheme = "https";
03f07b5… drh 2246 }else if( fossil_strcmp(zFieldName,"host:")==0 ){
0872ecb… sdr 2247 char *z;
03f07b5… drh 2248 cgi_setenv("HTTP_HOST", zVal);
0872ecb… sdr 2249 z = strchr(zVal, ':');
0872ecb… sdr 2250 if( z ) z[0] = 0;
f101e94… drh 2251 cgi_setenv("SERVER_NAME", zVal);
03f07b5… drh 2252 }else if( fossil_strcmp(zFieldName,"if-none-match:")==0 ){
03f07b5… drh 2253 cgi_setenv("HTTP_IF_NONE_MATCH", zVal);
03f07b5… drh 2254 }else if( fossil_strcmp(zFieldName,"if-modified-since:")==0 ){
03f07b5… drh 2255 cgi_setenv("HTTP_IF_MODIFIED_SINCE", zVal);
03f07b5… drh 2256 }else if( fossil_strcmp(zFieldName,"referer:")==0 ){
03f07b5… drh 2257 cgi_setenv("HTTP_REFERER", zVal);
03f07b5… drh 2258 }else if( fossil_strcmp(zFieldName,"user-agent:")==0 ){
03f07b5… drh 2259 cgi_setenv("HTTP_USER_AGENT", zVal);
315cf24… drh 2260 }else if( fossil_strcmp(zFieldName,"authorization:")==0 ){
315cf24… drh 2261 cgi_setenv("HTTP_AUTHORIZATION", zVal);
926a27c… stephan 2262 }else if( fossil_strcmp(zFieldName,"accept-language:")==0 ){
926a27c… stephan 2263 cgi_setenv("HTTP_ACCEPT_LANGUAGE", zVal);
03f07b5… drh 2264 }else if( fossil_strcmp(zFieldName,"x-forwarded-for:")==0 ){
59f790b… joel 2265 const char *zIpAddr = cgi_accept_forwarded_for(zVal);
59f790b… joel 2266 if( zIpAddr!=0 ){
140cb31… drh 2267 g.zIpAddr = fossil_strdup(zIpAddr);
03f07b5… drh 2268 cgi_replace_parameter("REMOTE_ADDR", g.zIpAddr);
03f07b5… drh 2269 }
b6892cc… drh 2270 }else if( fossil_strcmp(zFieldName,"range:")==0 ){
b6892cc… drh 2271 int x1 = 0;
b6892cc… drh 2272 int x2 = 0;
b6892cc… drh 2273 if( sscanf(zVal,"bytes=%d-%d",&x1,&x2)==2 && x1>=0 && x1<=x2 ){
b6892cc… drh 2274 rangeStart = x1;
b6892cc… drh 2275 rangeEnd = x2+1;
b6892cc… drh 2276 }
dbb5e2d… drh 2277 }
dbb5e2d… drh 2278 }
282bdf0… drh 2279 cgi_setenv("REQUEST_SCHEME",zScheme);
dbb5e2d… drh 2280 cgi_init();
dbb5e2d… drh 2281 cgi_trace(0);
dbb5e2d… drh 2282 }
dbb5e2d… drh 2283
dbb5e2d… drh 2284 /*
dbb5e2d… drh 2285 ** This routine handles a single HTTP request from an SSH client which is
dbb5e2d… drh 2286 ** coming in on g.httpIn and which replies on g.httpOut
dbb5e2d… drh 2287 **
dbb5e2d… drh 2288 ** Once all the setup is finished, this procedure returns
dbb5e2d… drh 2289 ** and subsequent code handles the actual generation of the webpage.
dbb5e2d… drh 2290 **
dbb5e2d… drh 2291 ** It is called in a loop so some variables will need to be replaced
dbb5e2d… drh 2292 */
dbb5e2d… drh 2293 void cgi_handle_ssh_http_request(const char *zIpAddr){
dbb5e2d… drh 2294 static int nCycles = 0;
dbb5e2d… drh 2295 static char *zCmd = 0;
dbb5e2d… drh 2296 char *z, *zToken;
7531b94… andybradford 2297 char *zMethod;
088be21… andybradford 2298 int i;
be76a57… drh 2299 size_t n;
dbb5e2d… drh 2300 char zLine[2000]; /* A single line of input. */
dbb5e2d… drh 2301
f6263bb… drh 2302 assert( !g.httpUseSSL );
a588e55… mistachkin 2303 #ifdef FOSSIL_ENABLE_JSON
e7f13b8… stephan 2304 if( nCycles==0 ){ json_bootstrap_early(); }
a588e55… mistachkin 2305 #endif
dbb5e2d… drh 2306 if( zIpAddr ){
45f3516… jan.nijtmans 2307 if( nCycles==0 ){
dbb5e2d… drh 2308 cgi_setenv("REMOTE_ADDR", zIpAddr);
140cb31… drh 2309 g.zIpAddr = fossil_strdup(zIpAddr);
dbb5e2d… drh 2310 }
dbb5e2d… drh 2311 }else{
31c7bdb… larrybr 2312 fossil_fatal("missing SSH IP address");
dbb5e2d… drh 2313 }
a8e33fb… drh 2314 g.zReqType = "HTTP";
dbb5e2d… drh 2315 if( fgets(zLine, sizeof(zLine),g.httpIn)==0 ){
dbb5e2d… drh 2316 malformed_request("missing HTTP header");
dbb5e2d… drh 2317 }
dbb5e2d… drh 2318 cgi_trace(zLine);
dbb5e2d… drh 2319 zToken = extract_token(zLine, &z);
dbb5e2d… drh 2320 if( zToken==0 ){
dbb5e2d… drh 2321 malformed_request("malformed HTTP header");
dbb5e2d… drh 2322 }
dbb5e2d… drh 2323
dbb5e2d… drh 2324 if( fossil_strcmp(zToken, "echo")==0 ){
dbb5e2d… drh 2325 /* start looking for probes to complete transport_open */
dbb5e2d… drh 2326 zCmd = cgi_handle_ssh_probes(zLine, sizeof(zLine), z, zToken);
dbb5e2d… drh 2327 if( fgets(zLine, sizeof(zLine),g.httpIn)==0 ){
dbb5e2d… drh 2328 malformed_request("missing HTTP header");
dbb5e2d… drh 2329 }
dbb5e2d… drh 2330 cgi_trace(zLine);
dbb5e2d… drh 2331 zToken = extract_token(zLine, &z);
dbb5e2d… drh 2332 if( zToken==0 ){
dbb5e2d… drh 2333 malformed_request("malformed HTTP header");
dbb5e2d… drh 2334 }
dbb5e2d… drh 2335 }else if( zToken && strlen(zToken)==0 && zCmd ){
dbb5e2d… drh 2336 /* transport_flip request and continued transport_open */
dbb5e2d… drh 2337 cgi_handle_ssh_transport(zCmd);
dbb5e2d… drh 2338 if( fgets(zLine, sizeof(zLine),g.httpIn)==0 ){
dbb5e2d… drh 2339 malformed_request("missing HTTP header");
dbb5e2d… drh 2340 }
dbb5e2d… drh 2341 cgi_trace(zLine);
dbb5e2d… drh 2342 zToken = extract_token(zLine, &z);
dbb5e2d… drh 2343 if( zToken==0 ){
dbb5e2d… drh 2344 malformed_request("malformed HTTP header");
dbb5e2d… drh 2345 }
dbb5e2d… drh 2346 }
dbb5e2d… drh 2347
7531b94… andybradford 2348 zMethod = fossil_strdup(zToken);
dbb5e2d… drh 2349 if( fossil_strcmp(zToken,"GET")!=0 && fossil_strcmp(zToken,"POST")!=0
dbb5e2d… drh 2350 && fossil_strcmp(zToken,"HEAD")!=0 ){
dbb5e2d… drh 2351 malformed_request("unsupported HTTP method");
dbb5e2d… drh 2352 }
dbb5e2d… drh 2353
dbb5e2d… drh 2354 if( nCycles==0 ){
dbb5e2d… drh 2355 cgi_setenv("GATEWAY_INTERFACE","CGI/1.0");
dbb5e2d… drh 2356 cgi_setenv("REQUEST_METHOD",zToken);
dbb5e2d… drh 2357 }
dbb5e2d… drh 2358
dbb5e2d… drh 2359 zToken = extract_token(z, &z);
dbb5e2d… drh 2360 if( zToken==0 ){
dbb5e2d… drh 2361 malformed_request("malformed URL in HTTP header");
be76a57… drh 2362 }
be76a57… drh 2363 n = strlen(g.zRepositoryName);
be76a57… drh 2364 if( fossil_strncmp(g.zRepositoryName, zToken, n)==0
be76a57… drh 2365 && (zToken[n]=='/' || zToken[n]==0)
7531b94… andybradford 2366 && fossil_strcmp(zMethod,"GET")==0
be76a57… drh 2367 ){
be76a57… drh 2368 zToken += n;
ee445fe… andybradford 2369 if( zToken && strlen(zToken)==0 ){
ee445fe… andybradford 2370 malformed_request("malformed URL in HTTP header");
ee445fe… andybradford 2371 }
2f9920a… drh 2372 }
dbb5e2d… drh 2373 if( nCycles==0 ){
dbb5e2d… drh 2374 cgi_setenv("REQUEST_URI", zToken);
dbb5e2d… drh 2375 cgi_setenv("SCRIPT_NAME", "");
dbb5e2d… drh 2376 }
dbb5e2d… drh 2377
dbb5e2d… drh 2378 for(i=0; zToken[i] && zToken[i]!='?'; i++){}
dbb5e2d… drh 2379 if( zToken[i] ) zToken[i++] = 0;
dbb5e2d… drh 2380 if( nCycles==0 ){
dbb5e2d… drh 2381 cgi_setenv("PATH_INFO", zToken);
2f9920a… drh 2382 cgi_setenv("QUERY_STRING",&zToken[i]);
dbb5e2d… drh 2383 }else{
140cb31… drh 2384 cgi_replace_parameter("PATH_INFO", fossil_strdup(zToken));
2f9920a… drh 2385 cgi_replace_parameter("QUERY_STRING",fossil_strdup(&zToken[i]));
dbb5e2d… drh 2386 }
45f3516… jan.nijtmans 2387
dbb5e2d… drh 2388 /* Get all the optional fields that follow the first line.
dbb5e2d… drh 2389 */
dbb5e2d… drh 2390 while( fgets(zLine,sizeof(zLine),g.httpIn) ){
dbb5e2d… drh 2391 char *zFieldName;
dbb5e2d… drh 2392 char *zVal;
dbb5e2d… drh 2393
dbb5e2d… drh 2394 cgi_trace(zLine);
dbb5e2d… drh 2395 zFieldName = extract_token(zLine,&zVal);
dbb5e2d… drh 2396 if( zFieldName==0 || *zFieldName==0 ) break;
dbb5e2d… drh 2397 while( fossil_isspace(*zVal) ){ zVal++; }
dbb5e2d… drh 2398 i = strlen(zVal);
dbb5e2d… drh 2399 while( i>0 && fossil_isspace(zVal[i-1]) ){ i--; }
dbb5e2d… drh 2400 zVal[i] = 0;
dbb5e2d… drh 2401 for(i=0; zFieldName[i]; i++){
dbb5e2d… drh 2402 zFieldName[i] = fossil_tolower(zFieldName[i]);
dbb5e2d… drh 2403 }
dbb5e2d… drh 2404 if( fossil_strcmp(zFieldName,"content-length:")==0 ){
088be21… andybradford 2405 if( nCycles==0 ){
524a3fe… andybradford 2406 cgi_setenv("CONTENT_LENGTH", zVal);
088be21… andybradford 2407 }else{
524a3fe… andybradford 2408 cgi_replace_parameter("CONTENT_LENGTH", zVal);
088be21… andybradford 2409 }
dbb5e2d… drh 2410 }else if( fossil_strcmp(zFieldName,"content-type:")==0 ){
088be21… andybradford 2411 if( nCycles==0 ){
524a3fe… andybradford 2412 cgi_setenv("CONTENT_TYPE", zVal);
088be21… andybradford 2413 }
dbb5e2d… drh 2414 }else if( fossil_strcmp(zFieldName,"host:")==0 ){
dbb5e2d… drh 2415 if( nCycles==0 ){
dbb5e2d… drh 2416 cgi_setenv("HTTP_HOST", zVal);
dbb5e2d… drh 2417 }
dbb5e2d… drh 2418 }else if( fossil_strcmp(zFieldName,"user-agent:")==0 ){
dbb5e2d… drh 2419 if( nCycles==0 ){
dbb5e2d… drh 2420 cgi_setenv("HTTP_USER_AGENT", zVal);
dbb5e2d… drh 2421 }
dbb5e2d… drh 2422 }else if( fossil_strcmp(zFieldName,"x-fossil-transport:")==0 ){
dbb5e2d… drh 2423 if( fossil_strnicmp(zVal, "ssh", 3)==0 ){
dbb5e2d… drh 2424 if( nCycles==0 ){
dbb5e2d… drh 2425 g.fSshClient |= CGI_SSH_FOSSIL;
dbb5e2d… drh 2426 g.fullHttpReply = 0;
dbb5e2d… drh 2427 }
dbb5e2d… drh 2428 }
dbb5e2d… drh 2429 }
dbb5e2d… drh 2430 }
dbb5e2d… drh 2431
dbb5e2d… drh 2432 if( nCycles==0 ){
dbb5e2d… drh 2433 if( ! ( g.fSshClient & CGI_SSH_FOSSIL ) ){
dbb5e2d… drh 2434 /* did not find new fossil ssh transport */
dbb5e2d… drh 2435 g.fSshClient &= ~CGI_SSH_CLIENT;
dbb5e2d… drh 2436 g.fullHttpReply = 1;
dbb5e2d… drh 2437 cgi_replace_parameter("REMOTE_ADDR", "127.0.0.1");
03f07b5… drh 2438 }
03f07b5… drh 2439 }
dbb5e2d… drh 2440
dbb5e2d… drh 2441 cgi_reset_content();
dbb5e2d… drh 2442 cgi_destination(CGI_BODY);
dbb5e2d… drh 2443
2f9920a… drh 2444 cgi_init();
4f8c897… drh 2445 cgi_trace(0);
dbb5e2d… drh 2446 nCycles++;
dbb5e2d… drh 2447 }
dbb5e2d… drh 2448
dbb5e2d… drh 2449 /*
dbb5e2d… drh 2450 ** This routine handles the old fossil SSH probes
dbb5e2d… drh 2451 */
dbb5e2d… drh 2452 char *cgi_handle_ssh_probes(char *zLine, int zSize, char *z, char *zToken){
dbb5e2d… drh 2453 /* Start looking for probes */
f6263bb… drh 2454 assert( !g.httpUseSSL );
dbb5e2d… drh 2455 while( fossil_strcmp(zToken, "echo")==0 ){
dbb5e2d… drh 2456 zToken = extract_token(z, &z);
dbb5e2d… drh 2457 if( zToken==0 ){
dbb5e2d… drh 2458 malformed_request("malformed probe");
dbb5e2d… drh 2459 }
dbb5e2d… drh 2460 if( fossil_strncmp(zToken, "test", 4)==0 ||
dbb5e2d… drh 2461 fossil_strncmp(zToken, "probe-", 6)==0 ){
dbb5e2d… drh 2462 fprintf(g.httpOut, "%s\n", zToken);
dbb5e2d… drh 2463 fflush(g.httpOut);
dbb5e2d… drh 2464 }else{
dbb5e2d… drh 2465 malformed_request("malformed probe");
dbb5e2d… drh 2466 }
dbb5e2d… drh 2467 if( fgets(zLine, zSize, g.httpIn)==0 ){
dbb5e2d… drh 2468 malformed_request("malformed probe");
dbb5e2d… drh 2469 }
dbb5e2d… drh 2470 cgi_trace(zLine);
dbb5e2d… drh 2471 zToken = extract_token(zLine, &z);
dbb5e2d… drh 2472 if( zToken==0 ){
dbb5e2d… drh 2473 malformed_request("malformed probe");
dbb5e2d… drh 2474 }
dbb5e2d… drh 2475 }
dbb5e2d… drh 2476
dbb5e2d… drh 2477 /* Got all probes now first transport_open is completed
dbb5e2d… drh 2478 ** so return the command that was requested
dbb5e2d… drh 2479 */
dbb5e2d… drh 2480 g.fSshClient |= CGI_SSH_COMPAT;
140cb31… drh 2481 return fossil_strdup(zToken);
dbb5e2d… drh 2482 }
dbb5e2d… drh 2483
dbb5e2d… drh 2484 /*
dbb5e2d… drh 2485 ** This routine handles the old fossil SSH transport_flip
dbb5e2d… drh 2486 ** and transport_open communications if detected.
dbb5e2d… drh 2487 */
dbb5e2d… drh 2488 void cgi_handle_ssh_transport(const char *zCmd){
dbb5e2d… drh 2489 char *z, *zToken;
dbb5e2d… drh 2490 char zLine[2000]; /* A single line of input. */
dbb5e2d… drh 2491
f6263bb… drh 2492 assert( !g.httpUseSSL );
dbb5e2d… drh 2493 /* look for second newline of transport_flip */
dbb5e2d… drh 2494 if( fgets(zLine, sizeof(zLine),g.httpIn)==0 ){
dbb5e2d… drh 2495 malformed_request("incorrect transport_flip");
dbb5e2d… drh 2496 }
dbb5e2d… drh 2497 cgi_trace(zLine);
dbb5e2d… drh 2498 zToken = extract_token(zLine, &z);
dbb5e2d… drh 2499 if( zToken && strlen(zToken)==0 ){
dbb5e2d… drh 2500 /* look for path to fossil */
dbb5e2d… drh 2501 if( fgets(zLine, sizeof(zLine),g.httpIn)==0 ){
b9b3ce3… jan.nijtmans 2502 if( zCmd==0 ){
dbb5e2d… drh 2503 malformed_request("missing fossil command");
dbb5e2d… drh 2504 }else{
dbb5e2d… drh 2505 /* no new command so exit */
dbb5e2d… drh 2506 fossil_exit(0);
dbb5e2d… drh 2507 }
dbb5e2d… drh 2508 }
dbb5e2d… drh 2509 cgi_trace(zLine);
dbb5e2d… drh 2510 zToken = extract_token(zLine, &z);
dbb5e2d… drh 2511 if( zToken==0 ){
dbb5e2d… drh 2512 malformed_request("malformed fossil command");
dbb5e2d… drh 2513 }
dbb5e2d… drh 2514 /* see if we've seen the command */
dbb5e2d… drh 2515 if( zCmd && zCmd[0] && fossil_strcmp(zToken, zCmd)==0 ){
dbb5e2d… drh 2516 return;
dbb5e2d… drh 2517 }else{
dbb5e2d… drh 2518 malformed_request("transport_open failed");
dbb5e2d… drh 2519 }
dbb5e2d… drh 2520 }else{
dbb5e2d… drh 2521 malformed_request("transport_flip failed");
dbb5e2d… drh 2522 }
a2e7472… drh 2523 }
a2e7472… drh 2524
a2e7472… drh 2525 /*
a2e7472… drh 2526 ** This routine handles a single SCGI request which is coming in on
a2e7472… drh 2527 ** g.httpIn and which replies on g.httpOut
a2e7472… drh 2528 **
a2e7472… drh 2529 ** The SCGI request is read from g.httpIn and is used to initialize
a2e7472… drh 2530 ** entries in the cgi_parameter() hash, as if those entries were
a2e7472… drh 2531 ** environment variables. A call to cgi_init() completes
a2e7472… drh 2532 ** the setup. Once all the setup is finished, this procedure returns
a2e7472… drh 2533 ** and subsequent code handles the actual generation of the webpage.
a2e7472… drh 2534 */
a2e7472… drh 2535 void cgi_handle_scgi_request(void){
a2e7472… drh 2536 char *zHdr;
a2e7472… drh 2537 char *zToFree;
a2e7472… drh 2538 int nHdr = 0;
a2e7472… drh 2539 int nRead;
7807ec4… mistachkin 2540 int c, n, m;
a2e7472… drh 2541
f6263bb… drh 2542 assert( !g.httpUseSSL );
7807ec4… mistachkin 2543 while( (c = fgetc(g.httpIn))!=EOF && fossil_isdigit((char)c) ){
7807ec4… mistachkin 2544 nHdr = nHdr*10 + (char)c - '0';
a2e7472… drh 2545 }
a2e7472… drh 2546 if( nHdr<16 ) malformed_request("SCGI header too short");
a2e7472… drh 2547 zToFree = zHdr = fossil_malloc(nHdr);
a2e7472… drh 2548 nRead = (int)fread(zHdr, 1, nHdr, g.httpIn);
a2e7472… drh 2549 if( nRead<nHdr ) malformed_request("cannot read entire SCGI header");
a2e7472… drh 2550 nHdr = nRead;
a2e7472… drh 2551 while( nHdr ){
a2e7472… drh 2552 for(n=0; n<nHdr && zHdr[n]; n++){}
a2e7472… drh 2553 for(m=n+1; m<nHdr && zHdr[m]; m++){}
a2e7472… drh 2554 if( m>=nHdr ) malformed_request("SCGI header formatting error");
a2e7472… drh 2555 cgi_set_parameter(zHdr, zHdr+n+1);
a2e7472… drh 2556 zHdr += m+1;
a2e7472… drh 2557 nHdr -= m+1;
a2e7472… drh 2558 }
a2e7472… drh 2559 fossil_free(zToFree);
6b2cc46… danield 2560 (void)fgetc(g.httpIn); /* Read past the "," separating header from content */
a2e7472… drh 2561 cgi_init();
dbda8d6… drh 2562 }
dbda8d6… drh 2563
0e42cc1… drh 2564 #if INTERFACE
45f3516… jan.nijtmans 2565 /*
0e42cc1… drh 2566 ** Bitmap values for the flags parameter to cgi_http_server().
0e42cc1… drh 2567 */
0e42cc1… drh 2568 #define HTTP_SERVER_LOCALHOST 0x0001 /* Bind to 127.0.0.1 only */
a2e7472… drh 2569 #define HTTP_SERVER_SCGI 0x0002 /* SCGI instead of HTTP */
1f8a4ec… mistachkin 2570 #define HTTP_SERVER_HAD_REPOSITORY 0x0004 /* Was the repository open? */
1f8a4ec… mistachkin 2571 #define HTTP_SERVER_HAD_CHECKOUT 0x0008 /* Was a checkout open? */
d976b47… drh 2572 #define HTTP_SERVER_REPOLIST 0x0010 /* Allow repo listing */
f6263bb… drh 2573 #define HTTP_SERVER_NOFORK 0x0020 /* Do not call fork() */
effdada… drh 2574 #define HTTP_SERVER_UNIXSOCKET 0x0040 /* Use a unix-domain socket */
0e42cc1… drh 2575
0e42cc1… drh 2576 #endif /* INTERFACE */
0e42cc1… drh 2577
dbda8d6… drh 2578 /*
dbda8d6… drh 2579 ** Maximum number of child processes that we can have running
05ec15c… drh 2580 ** at one time. Set this to 0 for "no limit".
dbda8d6… drh 2581 */
05ec15c… drh 2582 #ifndef FOSSIL_MAX_CONNECTIONS
05ec15c… drh 2583 # define FOSSIL_MAX_CONNECTIONS 1000
05ec15c… drh 2584 #endif
dbda8d6… drh 2585
dbda8d6… drh 2586 /*
dbda8d6… drh 2587 ** Implement an HTTP server daemon listening on port iPort.
dbda8d6… drh 2588 **
dbda8d6… drh 2589 ** As new connections arrive, fork a child and let child return
dbda8d6… drh 2590 ** out of this procedure call. The child will handle the request.
dbda8d6… drh 2591 ** The parent never returns from this procedure.
e2e016c… drh 2592 **
e2e016c… drh 2593 ** Return 0 to each child as it runs. If unable to establish a
e2e016c… drh 2594 ** listening socket, return non-zero.
dbda8d6… drh 2595 */
5dfbf7e… drh 2596 int cgi_http_server(
5dfbf7e… drh 2597 int mnPort, int mxPort, /* Range of TCP ports to try */
5dfbf7e… drh 2598 const char *zBrowser, /* Run this browser, if not NULL */
5dfbf7e… drh 2599 const char *zIpAddr, /* Bind to this IP address, if not null */
5dfbf7e… drh 2600 int flags /* HTTP_SERVER_* flags */
5dfbf7e… drh 2601 ){
3564af0… drh 2602 #if defined(_WIN32)
d8ceb4a… drh 2603 /* Use win32_http_server() instead */
932825b… drh 2604 fossil_exit(1);
d0305b3… aku 2605 #else
945e0ae… drh 2606 int listen4 = -1; /* Main socket; IPv4 or unix-domain */
945e0ae… drh 2607 int listen6 = -1; /* Aux socket for corresponding IPv6 */
945e0ae… drh 2608 int mxListen = -1; /* Maximum of listen4 and listen6 */
945e0ae… drh 2609 int connection; /* An incoming connection */
41c7caa… drh 2610 int nRequest = 0; /* Number of requests handled so far */
dbda8d6… drh 2611 fd_set readfds; /* Set of file descriptors for select() */
c345445… drh 2612 socklen_t lenaddr; /* Length of the inaddr structure */
dbda8d6… drh 2613 int child; /* PID of the child process */
dbda8d6… drh 2614 int nchildren = 0; /* Number of child processes */
dbda8d6… drh 2615 struct timeval delay; /* How long to wait inside select() */
945e0ae… drh 2616 struct sockaddr_in6 inaddr6; /* Address for IPv6 */
945e0ae… drh 2617 struct sockaddr_in inaddr4; /* Address for IPv4 */
7fc2902… drh 2618 struct sockaddr_un uxaddr; /* The address for unix-domain sockets */
0efd9e6… jan.nijtmans 2619 int opt = 1; /* setsockopt flag */
7fc2902… drh 2620 int rc; /* Result code from system calls */
7fc2902… drh 2621 int iPort = mnPort; /* Port to try to use */
945e0ae… drh 2622 const char *zRequestType; /* Type of requests to listen for */
945e0ae… drh 2623
945e0ae… drh 2624
945e0ae… drh 2625 if( flags & HTTP_SERVER_SCGI ){
945e0ae… drh 2626 zRequestType = "SCGI";
945e0ae… drh 2627 }else if( g.httpUseSSL ){
945e0ae… drh 2628 zRequestType = "TLS-encrypted HTTPS";
945e0ae… drh 2629 }else{
945e0ae… drh 2630 zRequestType = "HTTP";
945e0ae… drh 2631 }
945e0ae… drh 2632
945e0ae… drh 2633 if( flags & HTTP_SERVER_UNIXSOCKET ){
945e0ae… drh 2634 /* CASE 1: A unix socket named g.zSockName. After creation, set the
945e0ae… drh 2635 ** permissions on the new socket to g.zSockMode and make the
945e0ae… drh 2636 ** owner of the socket be g.zSockOwner.
945e0ae… drh 2637 */
945e0ae… drh 2638 assert( g.zSockName!=0 );
945e0ae… drh 2639 memset(&uxaddr, 0, sizeof(uxaddr));
945e0ae… drh 2640 if( strlen(g.zSockName)>sizeof(uxaddr.sun_path) ){
945e0ae… drh 2641 fossil_fatal("name of unix socket too big: %s\nmax size: %d\n",
945e0ae… drh 2642 g.zSockName, (int)sizeof(uxaddr.sun_path));
945e0ae… drh 2643 }
945e0ae… drh 2644 if( file_isdir(g.zSockName, ExtFILE)!=0 ){
945e0ae… drh 2645 if( !file_issocket(g.zSockName) ){
945e0ae… drh 2646 fossil_fatal("cannot name socket \"%s\" because another object"
945e0ae… drh 2647 " with that name already exists", g.zSockName);
945e0ae… drh 2648 }else{
945e0ae… drh 2649 unlink(g.zSockName);
945e0ae… drh 2650 }
945e0ae… drh 2651 }
945e0ae… drh 2652 uxaddr.sun_family = AF_UNIX;
945e0ae… drh 2653 strncpy(uxaddr.sun_path, g.zSockName, sizeof(uxaddr.sun_path)-1);
945e0ae… drh 2654 listen4 = socket(AF_UNIX, SOCK_STREAM, 0);
945e0ae… drh 2655 if( listen4<0 ){
945e0ae… drh 2656 fossil_fatal("unable to create a unix socket named %s",
945e0ae… drh 2657 g.zSockName);
945e0ae… drh 2658 }
945e0ae… drh 2659 mxListen = listen4;
945e0ae… drh 2660 listen6 = -1;
945e0ae… drh 2661
945e0ae… drh 2662 /* Set the access permission for the new socket. Default to 0660.
945e0ae… drh 2663 ** But use an alternative specified by --socket-mode if available.
945e0ae… drh 2664 ** Do this before bind() to avoid a race condition. */
945e0ae… drh 2665 if( g.zSockMode ){
945e0ae… drh 2666 file_set_mode(g.zSockName, listen4, g.zSockMode, 0);
945e0ae… drh 2667 }else{
945e0ae… drh 2668 file_set_mode(g.zSockName, listen4, "0660", 1);
945e0ae… drh 2669 }
945e0ae… drh 2670 rc = bind(listen4, (struct sockaddr*)&uxaddr, sizeof(uxaddr));
945e0ae… drh 2671 /* Set the owner of the socket if requested by --socket-owner. This
945e0ae… drh 2672 ** must wait until after bind(), after the filesystem object has been
945e0ae… drh 2673 ** created. See https://lkml.org/lkml/2004/11/1/84 and
945e0ae… drh 2674 ** https://fossil-scm.org/forum/forumpost/7517680ef9684c57 */
945e0ae… drh 2675 if( g.zSockOwner ){
945e0ae… drh 2676 file_set_owner(g.zSockName, listen4, g.zSockOwner);
945e0ae… drh 2677 }
945e0ae… drh 2678 fossil_print("Listening for %s requests on unix socket %s\n",
945e0ae… drh 2679 zRequestType, g.zSockName);
945e0ae… drh 2680 fflush(stdout);
945e0ae… drh 2681 }else if( zIpAddr && strchr(zIpAddr,':')!=0 ){
945e0ae… drh 2682 /* CASE 2: TCP on IPv6 IP address specified by zIpAddr and on port iPort.
945e0ae… drh 2683 */
945e0ae… drh 2684 assert( mnPort==mxPort );
945e0ae… drh 2685 memset(&inaddr6, 0, sizeof(inaddr6));
945e0ae… drh 2686 inaddr6.sin6_family = AF_INET6;
945e0ae… drh 2687 inaddr6.sin6_port = htons(iPort);
945e0ae… drh 2688 if( inet_pton(AF_INET6, zIpAddr, &inaddr6.sin6_addr)==0 ){
945e0ae… drh 2689 fossil_fatal("not a valid IPv6 address: %s", zIpAddr);
945e0ae… drh 2690 }
945e0ae… drh 2691 listen6 = socket(AF_INET6, SOCK_STREAM, 0);
945e0ae… drh 2692 if( listen6>0 ){
945e0ae… drh 2693 opt = 1;
945e0ae… drh 2694 setsockopt(listen6, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
945e0ae… drh 2695 rc = bind(listen6, (struct sockaddr*)&inaddr6, sizeof(inaddr6));
945e0ae… drh 2696 if( rc<0 ){
945e0ae… drh 2697 close(listen6);
945e0ae… drh 2698 listen6 = -1;
945e0ae… drh 2699 }
945e0ae… drh 2700 }
945e0ae… drh 2701 if( listen6<0 ){
945e0ae… drh 2702 fossil_fatal("cannot open a listening socket on [%s]:%d",
945e0ae… drh 2703 zIpAddr, mnPort);
945e0ae… drh 2704 }
945e0ae… drh 2705 mxListen = listen6;
945e0ae… drh 2706 listen4 = -1;
945e0ae… drh 2707 fossil_print("Listening for %s requests on [%s]:%d\n",
945e0ae… drh 2708 zRequestType, zIpAddr, iPort);
945e0ae… drh 2709 fflush(stdout);
945e0ae… drh 2710 }else if( zIpAddr && zIpAddr[0] ){
945e0ae… drh 2711 /* CASE 3: TCP on IPv4 IP address specified by zIpAddr and on port iPort.
945e0ae… drh 2712 */
945e0ae… drh 2713 assert( mnPort==mxPort );
945e0ae… drh 2714 memset(&inaddr4, 0, sizeof(inaddr4));
945e0ae… drh 2715 inaddr4.sin_family = AF_INET;
945e0ae… drh 2716 inaddr4.sin_port = htons(iPort);
945e0ae… drh 2717 if( strcmp(zIpAddr, "localhost")==0 ) zIpAddr = "127.0.0.1";
945e0ae… drh 2718 inaddr4.sin_addr.s_addr = inet_addr(zIpAddr);
945e0ae… drh 2719 if( inaddr4.sin_addr.s_addr == INADDR_NONE ){
945e0ae… drh 2720 fossil_fatal("not a valid IPv4 address: %s", zIpAddr);
945e0ae… drh 2721 }
945e0ae… drh 2722 listen4 = socket(AF_INET, SOCK_STREAM, 0);
945e0ae… drh 2723 if( listen4>0 ){
945e0ae… drh 2724 setsockopt(listen4, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
945e0ae… drh 2725 rc = bind(listen4, (struct sockaddr*)&inaddr4, sizeof(inaddr4));
945e0ae… drh 2726 if( rc<0 ){
85067dc… drh 2727 close(listen4);
945e0ae… drh 2728 listen4 = -1;
945e0ae… drh 2729 }
945e0ae… drh 2730 }
945e0ae… drh 2731 if( listen4<0 ){
945e0ae… drh 2732 fossil_fatal("cannot open a listening socket on %s:%d",
945e0ae… drh 2733 zIpAddr, mnPort);
945e0ae… drh 2734 }
945e0ae… drh 2735 mxListen = listen4;
945e0ae… drh 2736 listen6 = -1;
945e0ae… drh 2737 fossil_print("Listening for %s requests on TCP port %s:%d\n",
945e0ae… drh 2738 zRequestType, zIpAddr, iPort);
945e0ae… drh 2739 fflush(stdout);
945e0ae… drh 2740 }else{
945e0ae… drh 2741 /* CASE 4: Listen on all available IP addresses, or on only loopback
945e0ae… drh 2742 ** addresses (if HTTP_SERVER_LOCALHOST). The TCP port is the
945e0ae… drh 2743 ** first available in the range of mnPort..mxPort. Listen
945e0ae… drh 2744 ** on both IPv4 and IPv6, if possible. The TCP port scan is done
945e0ae… drh 2745 ** on IPv4.
945e0ae… drh 2746 */
945e0ae… drh 2747 while( iPort<=mxPort ){
945e0ae… drh 2748 const char *zProto;
945e0ae… drh 2749 memset(&inaddr4, 0, sizeof(inaddr4));
945e0ae… drh 2750 inaddr4.sin_family = AF_INET;
945e0ae… drh 2751 inaddr4.sin_port = htons(iPort);
945e0ae… drh 2752 if( flags & HTTP_SERVER_LOCALHOST ){
945e0ae… drh 2753 inaddr4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
945e0ae… drh 2754 }else{
945e0ae… drh 2755 inaddr4.sin_addr.s_addr = htonl(INADDR_ANY);
945e0ae… drh 2756 }
945e0ae… drh 2757 listen4 = socket(AF_INET, SOCK_STREAM, 0);
945e0ae… drh 2758 if( listen4>0 ){
945e0ae… drh 2759 setsockopt(listen4, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
945e0ae… drh 2760 rc = bind(listen4, (struct sockaddr*)&inaddr4, sizeof(inaddr4));
945e0ae… drh 2761 if( rc<0 ){
945e0ae… drh 2762 close(listen4);
945e0ae… drh 2763 listen4 = -1;
945e0ae… drh 2764 }
945e0ae… drh 2765 }
945e0ae… drh 2766 if( listen4<0 ){
945e0ae… drh 2767 iPort++;
945e0ae… drh 2768 continue;
945e0ae… drh 2769 }
945e0ae… drh 2770 mxListen = listen4;
945e0ae… drh 2771
945e0ae… drh 2772 /* If we get here, that means we found an open TCP port at iPort for
945e0ae… drh 2773 ** IPv4. Try to set up a corresponding IPv6 socket on the same port.
945e0ae… drh 2774 */
945e0ae… drh 2775 memset(&inaddr6, 0, sizeof(inaddr6));
945e0ae… drh 2776 inaddr6.sin6_family = AF_INET6;
945e0ae… drh 2777 inaddr6.sin6_port = htons(iPort);
945e0ae… drh 2778 if( flags & HTTP_SERVER_LOCALHOST ){
945e0ae… drh 2779 inaddr6.sin6_addr = in6addr_loopback;
945e0ae… drh 2780 }else{
945e0ae… drh 2781 inaddr6.sin6_addr = in6addr_any;
945e0ae… drh 2782 }
945e0ae… drh 2783 listen6 = socket(AF_INET6, SOCK_STREAM, 0);
945e0ae… drh 2784 if( listen6>0 ){
945e0ae… drh 2785 setsockopt(listen6, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
945e0ae… drh 2786 setsockopt(listen6, IPPROTO_IPV6, IPV6_V6ONLY, &opt, sizeof(opt));
945e0ae… drh 2787 rc = bind(listen6, (struct sockaddr*)&inaddr6, sizeof(inaddr6));
945e0ae… drh 2788 if( rc<0 ){
945e0ae… drh 2789 close(listen6);
945e0ae… drh 2790 listen6 = -1;
945e0ae… drh 2791 }
945e0ae… drh 2792 }
945e0ae… drh 2793 if( listen6<0 ){
945e0ae… drh 2794 zProto = "IPv4 only";
945e0ae… drh 2795 }else{
945e0ae… drh 2796 zProto = "IPv4 and IPv6";
945e0ae… drh 2797 if( listen6>listen4 ) mxListen = listen6;
945e0ae… drh 2798 }
945e0ae… drh 2799
945e0ae… drh 2800 fossil_print("Listening for %s requests on TCP port %s%d, %s\n",
945e0ae… drh 2801 zRequestType,
945e0ae… drh 2802 (flags & HTTP_SERVER_LOCALHOST)!=0 ? "localhost:" : "",
945e0ae… drh 2803 iPort, zProto);
945e0ae… drh 2804 fflush(stdout);
945e0ae… drh 2805 break;
945e0ae… drh 2806 }
945e0ae… drh 2807 if( iPort>mxPort ){
945e0ae… drh 2808 fossil_fatal("no available TCP ports in the range %d..%d",
945e0ae… drh 2809 mnPort, mxPort);
945e0ae… drh 2810 }
945e0ae… drh 2811 }
945e0ae… drh 2812
945e0ae… drh 2813 /* If we get to this point, that means there is at least one listening
945e0ae… drh 2814 ** socket on either listen4 or listen6 and perhaps on both. */
945e0ae… drh 2815 assert( listen4>0 || listen6>0 );
945e0ae… drh 2816 if( listen4>0 ) listen(listen4,10);
945e0ae… drh 2817 if( listen6>0 ) listen(listen6,10);
effdada… drh 2818 if( zBrowser && (flags & HTTP_SERVER_UNIXSOCKET)==0 ){
49b0ff1… drh 2819 assert( strstr(zBrowser,"%d")!=0 );
49b0ff1… drh 2820 zBrowser = mprintf(zBrowser /*works-like:"%d"*/, iPort);
0efd9e6… jan.nijtmans 2821 #if defined(__CYGWIN__)
0efd9e6… jan.nijtmans 2822 /* On Cygwin, we can do better than "echo" */
7fcb462… stephan 2823 if( fossil_strncmp(zBrowser, "echo ", 5)==0 ){
0efd9e6… jan.nijtmans 2824 wchar_t *wUrl = fossil_utf8_to_unicode(zBrowser+5);
0efd9e6… jan.nijtmans 2825 wUrl[wcslen(wUrl)-2] = 0; /* Strip terminating " &" */
c05cc27… jan.nijtmans 2826 if( (size_t)ShellExecuteW(0, L"open", wUrl, 0, 0, 1)<33 ){
0efd9e6… jan.nijtmans 2827 fossil_warning("cannot start browser\n");
0efd9e6… jan.nijtmans 2828 }
0efd9e6… jan.nijtmans 2829 }else
0efd9e6… jan.nijtmans 2830 #endif
f2fcdbc… drh 2831 if( fossil_system(zBrowser)<0 ){
553159a… drh 2832 fossil_warning("cannot start browser: %s\n", zBrowser);
553159a… drh 2833 }
0a51263… drh 2834 }
945e0ae… drh 2835
e2bdc10… danield 2836 /* What for incoming requests. For each request, fork() a child process
945e0ae… drh 2837 ** to deal with that request. The child process returns. The parent
945e0ae… drh 2838 ** keeps on listening and never returns.
945e0ae… drh 2839 */
0a51263… drh 2840 while( 1 ){
05ec15c… drh 2841 #if FOSSIL_MAX_CONNECTIONS>0
05ec15c… drh 2842 while( nchildren>=FOSSIL_MAX_CONNECTIONS ){
05ec15c… drh 2843 if( wait(0)>=0 ) nchildren--;
0a51263… drh 2844 }
05ec15c… drh 2845 #endif
05ec15c… drh 2846 delay.tv_sec = 0;
05ec15c… drh 2847 delay.tv_usec = 100000;
0a51263… drh 2848 FD_ZERO(&readfds);
945e0ae… drh 2849 assert( listen4>0 || listen6>0 );
945e0ae… drh 2850 if( listen4>0 ) FD_SET( listen4, &readfds);
945e0ae… drh 2851 if( listen6>0 ) FD_SET( listen6, &readfds);
945e0ae… drh 2852 select( mxListen+1, &readfds, 0, 0, &delay);
945e0ae… drh 2853 if( listen4>0 && FD_ISSET(listen4, &readfds) ){
945e0ae… drh 2854 lenaddr = sizeof(inaddr4);
945e0ae… drh 2855 connection = accept(listen4, (struct sockaddr*)&inaddr4, &lenaddr);
945e0ae… drh 2856 }else if( listen6>0 && FD_ISSET(listen6, &readfds) ){
945e0ae… drh 2857 lenaddr = sizeof(inaddr6);
945e0ae… drh 2858 connection = accept(listen6, (struct sockaddr*)&inaddr6, &lenaddr);
945e0ae… drh 2859 }else{
945e0ae… drh 2860 connection = -1;
945e0ae… drh 2861 }
945e0ae… drh 2862 if( connection>=0 ){
945e0ae… drh 2863 if( flags & HTTP_SERVER_NOFORK ){
945e0ae… drh 2864 child = 0;
945e0ae… drh 2865 }else{
945e0ae… drh 2866 child = fork();
945e0ae… drh 2867 }
945e0ae… drh 2868 if( child!=0 ){
945e0ae… drh 2869 if( child>0 ){
945e0ae… drh 2870 nchildren++;
945e0ae… drh 2871 nRequest++;
945e0ae… drh 2872 }
945e0ae… drh 2873 close(connection);
945e0ae… drh 2874 }else{
945e0ae… drh 2875 int nErr = 0, fd;
945e0ae… drh 2876 g.zSockName = 0 /* avoid deleting the socket via atexit() */;
945e0ae… drh 2877 close(0);
945e0ae… drh 2878 fd = dup(connection);
945e0ae… drh 2879 if( fd!=0 ) nErr++;
945e0ae… drh 2880 close(1);
945e0ae… drh 2881 fd = dup(connection);
945e0ae… drh 2882 if( fd!=1 ) nErr++;
945e0ae… drh 2883 if( 0 && !g.fAnyTrace ){
945e0ae… drh 2884 close(2);
945e0ae… drh 2885 fd = dup(connection);
945e0ae… drh 2886 if( fd!=2 ) nErr++;
945e0ae… drh 2887 }
945e0ae… drh 2888 close(connection);
945e0ae… drh 2889 if( listen4>0 ) close(listen4);
945e0ae… drh 2890 if( listen6>0 ) close(listen6);
945e0ae… drh 2891 g.nPendingRequest = nchildren+1;
945e0ae… drh 2892 g.nRequest = nRequest+1;
945e0ae… drh 2893 return nErr;
dbda8d6… drh 2894 }
dbda8d6… drh 2895 }
dbda8d6… drh 2896 /* Bury dead children */
05ec15c… drh 2897 if( nchildren ){
05ec15c… drh 2898 while(1){
05ec15c… drh 2899 int iStatus = 0;
05ec15c… drh 2900 pid_t x = waitpid(-1, &iStatus, WNOHANG);
05ec15c… drh 2901 if( x<=0 ) break;
83b171b… drh 2902 if( WIFSIGNALED(iStatus) && g.fAnyTrace ){
83b171b… drh 2903 fprintf(stderr, "/***** Child %d exited on signal %d (%s) *****/\n",
83b171b… drh 2904 x, WTERMSIG(iStatus), strsignal(WTERMSIG(iStatus)));
83b171b… drh 2905 }
05ec15c… drh 2906 nchildren--;
05ec15c… drh 2907 }
70a94d0… jan.nijtmans 2908 }
dbda8d6… drh 2909 }
45f3516… jan.nijtmans 2910 /* NOT REACHED */
932825b… drh 2911 fossil_exit(1);
d0305b3… aku 2912 #endif
79b7902… drh 2913 /* NOT REACHED */
79b7902… drh 2914 return 0;
dbda8d6… drh 2915 }
e2e016c… drh 2916
dbda8d6… drh 2917
dbda8d6… drh 2918 /*
dbda8d6… drh 2919 ** Name of days and months.
dbda8d6… drh 2920 */
6032dd5… jan.nijtmans 2921 static const char *const azDays[] =
dbda8d6… drh 2922 {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", 0};
6032dd5… jan.nijtmans 2923 static const char *const azMonths[] =
dbda8d6… drh 2924 {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
dbda8d6… drh 2925 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", 0};
dbda8d6… drh 2926
dbda8d6… drh 2927
dbda8d6… drh 2928 /*
ab0a0d7… drh 2929 ** Returns an RFC822-formatted time string suitable for HTTP headers.
ab0a0d7… drh 2930 ** The timezone is always GMT. The value returned is always a
d2a94aa… drh 2931 ** string obtained from mprintf() and must be freed using fossil_free()
d2a94aa… drh 2932 ** to avoid a memory leak.
dbda8d6… drh 2933 **
dbda8d6… drh 2934 ** See http://www.faqs.org/rfcs/rfc822.html, section 5
dbda8d6… drh 2935 ** and http://www.faqs.org/rfcs/rfc2616.html, section 3.3.
dbda8d6… drh 2936 */
dbda8d6… drh 2937 char *cgi_rfc822_datestamp(time_t now){
dbda8d6… drh 2938 struct tm *pTm;
dbda8d6… drh 2939 pTm = gmtime(&now);
ab0a0d7… drh 2940 if( pTm==0 ){
ab0a0d7… drh 2941 return mprintf("");
ab0a0d7… drh 2942 }else{
d2a94aa… drh 2943 return mprintf("%s, %d %s %02d %02d:%02d:%02d +0000",
ab0a0d7… drh 2944 azDays[pTm->tm_wday], pTm->tm_mday, azMonths[pTm->tm_mon],
ab0a0d7… drh 2945 pTm->tm_year+1900, pTm->tm_hour, pTm->tm_min, pTm->tm_sec);
d2a94aa… drh 2946 }
d2a94aa… drh 2947 }
d2a94aa… drh 2948
d2a94aa… drh 2949 /*
4a7760e… drh 2950 ** Returns an ISO8601-formatted time string suitable for debugging
4a7760e… drh 2951 ** purposes.
4a7760e… drh 2952 **
4a7760e… drh 2953 ** The value returned is always a string obtained from mprintf() and must
4a7760e… drh 2954 ** be freed using fossil_free() to avoid a memory leak.
4a7760e… drh 2955 */
4a7760e… drh 2956 char *cgi_iso8601_datestamp(void){
4a7760e… drh 2957 struct tm *pTm;
4a7760e… drh 2958 time_t now = time(0);
4a7760e… drh 2959 pTm = gmtime(&now);
4a7760e… drh 2960 if( pTm==0 ){
4a7760e… drh 2961 return mprintf("");
4a7760e… drh 2962 }else{
4a7760e… drh 2963 return mprintf("%04d-%02d-%02d %02d:%02d:%02d",
6389c99… drh 2964 pTm->tm_year+1900, pTm->tm_mon+1, pTm->tm_mday,
4a7760e… drh 2965 pTm->tm_hour, pTm->tm_min, pTm->tm_sec);
4a7760e… drh 2966 }
4a7760e… drh 2967 }
4a7760e… drh 2968
4a7760e… drh 2969 /*
dbda8d6… drh 2970 ** Parse an RFC822-formatted timestamp as we'd expect from HTTP and return
dbda8d6… drh 2971 ** a Unix epoch time. <= zero is returned on failure.
dbda8d6… drh 2972 **
dbda8d6… drh 2973 ** Note that this won't handle all the _allowed_ HTTP formats, just the
dbda8d6… drh 2974 ** most popular one (the one generated by cgi_rfc822_datestamp(), actually).
dbda8d6… drh 2975 */
dbda8d6… drh 2976 time_t cgi_rfc822_parsedate(const char *zDate){
f89eb80… drh 2977 int mday, mon, year, yday, hour, min, sec;
f89eb80… drh 2978 char zIgnore[4];
f89eb80… drh 2979 char zMonth[4];
f89eb80… drh 2980 static const char *const azMonths[] =
f89eb80… drh 2981 {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
f89eb80… drh 2982 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", 0};
f89eb80… drh 2983 if( 7==sscanf(zDate, "%3[A-Za-z], %d %3[A-Za-z] %d %d:%d:%d", zIgnore,
f89eb80… drh 2984 &mday, zMonth, &year, &hour, &min, &sec)){
f89eb80… drh 2985 if( year > 1900 ) year -= 1900;
f89eb80… drh 2986 for(mon=0; azMonths[mon]; mon++){
7fcb462… stephan 2987 if( !fossil_strncmp( azMonths[mon], zMonth, 3 )){
f89eb80… drh 2988 int nDay;
f89eb80… drh 2989 int isLeapYr;
f89eb80… drh 2990 static int priorDays[] =
f89eb80… drh 2991 { 0, 31, 59, 90,120,151,181,212,243,273,304,334 };
f89eb80… drh 2992 if( mon<0 ){
f89eb80… drh 2993 int nYear = (11 - mon)/12;
f89eb80… drh 2994 year -= nYear;
f89eb80… drh 2995 mon += nYear*12;
f89eb80… drh 2996 }else if( mon>11 ){
f89eb80… drh 2997 year += mon/12;
f89eb80… drh 2998 mon %= 12;
f89eb80… drh 2999 }
f89eb80… drh 3000 isLeapYr = year%4==0 && (year%100!=0 || (year+300)%400==0);
f89eb80… drh 3001 yday = priorDays[mon] + mday - 1;
f89eb80… drh 3002 if( isLeapYr && mon>1 ) yday++;
f89eb80… drh 3003 nDay = (year-70)*365 + (year-69)/4 - year/100 + (year+300)/400 + yday;
f89eb80… drh 3004 return ((time_t)(nDay*24 + hour)*60 + min)*60 + sec;
f89eb80… drh 3005 }
f89eb80… drh 3006 }
f89eb80… drh 3007 }
f89eb80… drh 3008 return 0;
dbda8d6… drh 3009 }
dbda8d6… drh 3010
dbda8d6… drh 3011 /*
dbda8d6… drh 3012 ** Check the objectTime against the If-Modified-Since request header. If the
dbda8d6… drh 3013 ** object time isn't any newer than the header, we immediately send back
dbda8d6… drh 3014 ** a 304 reply and exit.
dbda8d6… drh 3015 */
dbda8d6… drh 3016 void cgi_modified_since(time_t objectTime){
dbda8d6… drh 3017 const char *zIf = P("HTTP_IF_MODIFIED_SINCE");
dbda8d6… drh 3018 if( zIf==0 ) return;
dbda8d6… drh 3019 if( objectTime > cgi_rfc822_parsedate(zIf) ) return;
dbda8d6… drh 3020 cgi_set_status(304,"Not Modified");
dbda8d6… drh 3021 cgi_reset_content();
dbda8d6… drh 3022 cgi_reply();
932825b… drh 3023 fossil_exit(0);
dbb5e2d… drh 3024 }
dbb5e2d… drh 3025
dbb5e2d… drh 3026 /*
dbb5e2d… drh 3027 ** Check to see if the remote client is SSH and return
dbb5e2d… drh 3028 ** its IP or return default
dbb5e2d… drh 3029 */
dbb5e2d… drh 3030 const char *cgi_ssh_remote_addr(const char *zDefault){
dbb5e2d… drh 3031 char *zIndex;
dbb5e2d… drh 3032 const char *zSshConn = fossil_getenv("SSH_CONNECTION");
dbb5e2d… drh 3033
dbb5e2d… drh 3034 if( zSshConn && zSshConn[0] ){
140cb31… drh 3035 char *zSshClient = fossil_strdup(zSshConn);
dbb5e2d… drh 3036 if( (zIndex = strchr(zSshClient,' '))!=0 ){
dbb5e2d… drh 3037 zSshClient[zIndex-zSshClient] = '\0';
dbb5e2d… drh 3038 return zSshClient;
dbb5e2d… drh 3039 }
dbb5e2d… drh 3040 }
dbb5e2d… drh 3041 return zDefault;
96dcb7e… drh 3042 }
96dcb7e… drh 3043
96dcb7e… drh 3044 /*
96dcb7e… drh 3045 ** Return true if information is coming from the loopback network.
96dcb7e… drh 3046 */
96dcb7e… drh 3047 int cgi_is_loopback(const char *zIpAddr){
96dcb7e… drh 3048 return fossil_strcmp(zIpAddr, "127.0.0.1")==0 ||
696e148… drh 3049 fossil_strcmp(zIpAddr, "::ffff:127.0.0.1")==0 ||
696e148… drh 3050 fossil_strcmp(zIpAddr, "::1")==0;
c720327… drh 3051 }
c720327… drh 3052
c720327… drh 3053 /*
c720327… drh 3054 ** Return true if the HTTP request is likely to be from a small-screen
c720327… drh 3055 ** mobile device.
c720327… drh 3056 **
c720327… drh 3057 ** The returned value is a guess. Use it only for setting up defaults.
c720327… drh 3058 */
c720327… drh 3059 int cgi_from_mobile(void){
c720327… drh 3060 const char *zAgent = P("HTTP_USER_AGENT");
c720327… drh 3061 if( zAgent==0 ) return 0;
b76eebe… drh 3062 if( sqlite3_strglob("*iPad*", zAgent)==0 ) return 0;
c720327… drh 3063 return sqlite3_strlike("%mobile%", zAgent, 0)==0;
57f1e87… drh 3064 }
57f1e87… drh 3065
57f1e87… drh 3066 /*
57f1e87… drh 3067 ** Look for query or POST parameters that:
57f1e87… drh 3068 **
57f1e87… drh 3069 ** (1) Have not been used
57f1e87… drh 3070 ** (2) Appear to be malicious attempts to break into or otherwise
57f1e87… drh 3071 ** harm the system, for example via SQL injection
57f1e87… drh 3072 **
57f1e87… drh 3073 ** If any such parameters are seen, a 418 ("I'm a teapot") return is
57f1e87… drh 3074 ** generated and processing aborts - this routine does not return.
57f1e87… drh 3075 **
57f1e87… drh 3076 ** When Fossil is launched via CGI from althttpd, the 418 return signals
57f1e87… drh 3077 ** the webserver to put the requestor IP address into "timeout", blocking
57f1e87… drh 3078 ** subsequent requests for 5 minutes.
57f1e87… drh 3079 **
57f1e87… drh 3080 ** Fossil is not subject to any SQL injections, as far as anybody knows.
57f1e87… drh 3081 ** This routine is not necessary for the security of the system (though
57f1e87… drh 3082 ** an extra layer of security never hurts). The main purpose here is
57f1e87… drh 3083 ** to shutdown malicious attack spiders and prevent them from burning
57f1e87… drh 3084 ** lots of CPU cycles and bogging down the website. In other words, the
57f1e87… drh 3085 ** objective of this routine is to help prevent denial-of-service.
57f1e87… drh 3086 **
57f1e87… drh 3087 ** Usage Hint: Put a call to this routine as late in the webpage
57f1e87… drh 3088 ** implementation as possible, ideally just before it begins doing
57f1e87… drh 3089 ** potentially CPU-intensive computations and after all query parameters
57f1e87… drh 3090 ** have been consulted.
57f1e87… drh 3091 */
57f1e87… drh 3092 void cgi_check_for_malice(void){
57f1e87… drh 3093 struct QParam * pParam;
57f1e87… drh 3094 int i;
08df33a… drh 3095 for(i=0; i<nUsedQP; ++i){
57f1e87… drh 3096 pParam = &aParamQP[i];
08df33a… drh 3097 if( 0==pParam->isFetched
08df33a… drh 3098 && pParam->zValue!=0
08df33a… drh 3099 && pParam->zName!=0
08df33a… drh 3100 && fossil_islower(pParam->zName[0])
08df33a… drh 3101 ){
57f1e87… drh 3102 cgi_value_spider_check(pParam->zValue, pParam->zName);
57f1e87… drh 3103 }
57f1e87… drh 3104 }
dbda8d6… drh 3105 }

Keyboard Shortcuts

Open search /
Next entry (timeline) j
Previous entry (timeline) k
Open focused entry Enter
Show this help ?
Toggle theme Top nav button