#include #include #include #include #include #include #include #include #include #define SYSLOG_NAMES #include #include #include #include #include #define _(String) gettext((String)) #include #include #include "initlog.h" #include "process.h" static int logfacility=LOG_DAEMON; static int logpriority=LOG_NOTICE; static int reexec=0; static int quiet=0; int debug=0; regex_t **regList = NULL; static int logEntries = 0; struct logInfo *logData = NULL; void readConfiguration(char *fname) { int fd,num=0; struct stat sbuf; char *data,*line; regex_t *regexp; int lfac=-1,lpri=-1; if ((fd=open(fname,O_RDONLY))==-1) return; if (fstat(fd,&sbuf)) { close(fd); return; } data=malloc(sbuf.st_size+1); if (read(fd,data,sbuf.st_size)!=sbuf.st_size) { close(fd); return; } close(fd); data[sbuf.st_size] = '\0'; while ((line=getLine(&data))) { if (line[0]=='#') continue; if (!strncmp(line,"ignore ",7)) { regexp = malloc(sizeof(regex_t)); if (!regcomp(regexp,line+7,REG_EXTENDED|REG_NOSUB|REG_NEWLINE)) { regList = realloc(regList,(num+2) * sizeof(regex_t *)); regList[num] = regexp; regList[num+1] = NULL; num++; } } if (!strncmp(line,"facility ",9)) { lfac=atoi(line+9); if ((lfac == 0) && strcmp(line+9,"0")) { int x =0; lfac = LOG_DAEMON; for (x=0;facilitynames[x].c_name;x++) { if (!strcmp(line+9,facilitynames[x].c_name)) { lfac = facilitynames[x].c_val; break; } } } } if (!strncmp(line,"priority ",9)) { lpri = atoi(line+9); if ((lpri == 0) && strcmp(line+9,"0")) { int x=0; lpri = LOG_NOTICE; for (x=0;prioritynames[x].c_name;x++) { if (!strcmp(line+9,prioritynames[x].c_name)) { lpri = prioritynames[x].c_val; break; } } } } } if (lfac!=-1) logfacility=lfac; if (lpri!=-1) logpriority=lpri; } char *getLine(char **data) { /* Get one line from data */ /* Anything up to a carraige return (\r) or a backspace (\b) is discarded. */ /* If this really bothers you, mail me and I might make it configurable. */ /* It's here to avoid confilcts with fsck's progress bar. */ char *x, *y; if (!*data) return NULL; x=*data; while (*x && (*x != '\n')) { while (*x && (*x != '\n') && (*x != '\r') && (*x != '\b')) x++; if (*x && (*x=='\r' || *x =='\b')) { *data = x+1; x++; } } if (*x) { x++; } else { if (x-*data) { y=malloc(x-*data+1); y[x-*data] = 0; y[x-*data-1] = '\n'; memcpy(y,*data,x-*data); } else { y=NULL; } *data = NULL; return y; } y = malloc(x-*data); y[x-*data-1] = 0; memcpy(y,*data,x-*data-1); *data = x; return y; } char **toArray(char *line, int *num) { /* Converts a long string into an array of lines. */ char **lines; char *tmpline; *num = 0; lines = NULL; while ((tmpline=getLine(&line))) { if (!*num) lines = (char **) malloc(sizeof(char *)); else lines = (char **) realloc(lines, (*num+1)*sizeof(char *)); lines[*num] = tmpline; (*num)++; } return lines; } int startDaemon() { int pid; int rc; if ( (pid = fork()) == -1 ) { perror("fork"); return -1; } if ( pid ) { /* parent */ waitpid(pid,&rc,0); if (WIFEXITED(rc)) { DDEBUG("minilogd returned %d!\n",WEXITSTATUS(rc)); return WEXITSTATUS(rc); } else return -1; } else { int fd; fd=open("/dev/null",O_RDWR); dup2(fd,0); dup2(fd,1); dup2(fd,2); close(fd); /* kid */ execlp("minilogd","minilogd",NULL); perror("exec"); exit(-1); } } int trySocket() { int s; struct sockaddr_un addr; s = socket(AF_LOCAL, SOCK_DGRAM, 0); if (s<0) return 1; bzero(&addr,sizeof(addr)); addr.sun_family = AF_LOCAL; strncpy(addr.sun_path,_PATH_LOG,sizeof(addr.sun_path)-1); if (connect(s,(struct sockaddr *) &addr,sizeof(addr))<0) { if (errno == EPROTOTYPE) { DDEBUG("connect failed (EPROTOTYPE), trying stream\n"); close(s); s = socket(AF_LOCAL, SOCK_STREAM, 0); if (connect(s,(struct sockaddr *) &addr, sizeof(addr)) < 0) { DDEBUG("connect failed: %s\n",strerror(errno)); close(s); return 1; } close(s); return 0; } close(s); DDEBUG("connect failed: %s\n",strerror(errno)); return 1; } else { close(s); return 0; } } int logLine(struct logInfo *logEnt) { /* Logs a line... somewhere. */ int x; struct stat statbuf; /* Don't log empty or null lines */ if (!logEnt->line || !strcmp(logEnt->line,"\n")) return 0; if ( ((stat(_PATH_LOG,&statbuf)==-1) || trySocket()) && startDaemon() ) { DDEBUG("starting daemon failed, pooling entry %d\n",logEntries); logData=realloc(logData,(logEntries+1)*sizeof(struct logInfo)); logData[logEntries]= (*logEnt); logEntries++; } else { if (logEntries>0) { for (x=0;xline); openlog(logEnt->cmd,0,logEnt->fac); syslog(logEnt->pri,"%s",logEnt->line); closelog(); } return 0; } int logEvent(char *cmd, int eventtype,char *string) { char *eventtable [] = { _("%s babbles incoherently"), _("%s succeeded"), _("%s failed"), _("%s cancelled at user request"), _("%s failed due to a failed dependency"), /* insert more here */ NULL }; int x=0,len; struct logInfo logentry; if (cmd) { logentry.cmd = strdup(basename(cmd)); if ((logentry.cmd[0] =='K' || logentry.cmd[0] == 'S') && ( logentry.cmd[1] >= '0' && logentry.cmd[1] <= '9' ) && ( logentry.cmd[2] >= '0' && logentry.cmd[2] <= '9' ) ) logentry.cmd+=3; } else logentry.cmd = strdup(_("(none)")); if (!string) string = strdup(cmd); while (eventtable[x] && x= '0' && logentry.cmd[1] <= 0x39 ) && ( logentry.cmd[2] >= '0' && logentry.cmd[2] <= 0x39 ) ) logentry.cmd+=3; } else logentry.cmd = strdup(_("")); logentry.line = strdup(string); logentry.pri = logpriority; logentry.fac = logfacility; return logLine(&logentry); } int processArgs(int argc, char **argv, int silent) { char *cmdname=NULL; char *conffile=NULL; int cmdevent=0; char *cmd=NULL; char *logstring=NULL; char *fac=NULL,*pri=NULL; int lfac=-1, lpri=-1; poptContext context; int rc; struct poptOption optTable[] = { POPT_AUTOHELP { "conf", 0, POPT_ARG_STRING, &conffile, 0, "configuration file (default: /etc/initlog.conf)", NULL }, { "name", 'n', POPT_ARG_STRING, &cmdname, 0, "name of service being logged", NULL }, { "event", 'e', POPT_ARG_INT, &cmdevent, 0, "event being logged (see man page)", NULL }, { "cmd", 'c', POPT_ARG_STRING, &cmd, 0, "command to run, logging output", NULL }, { "debug", 'd', POPT_ARG_NONE, &debug, 0, "print lots of verbose debugging info", NULL }, { "run", 'r', POPT_ARG_STRING, &cmd, 3, "command to run, accepting input on open fd", NULL }, { "string", 's', POPT_ARG_STRING, &logstring, 0, "string to log", NULL }, { "facility", 'f', POPT_ARG_STRING, &fac, 1, "facility to log at (default: 'local7')", NULL }, { "priority", 'p', POPT_ARG_STRING, &pri, 2, "priority to log at (default: 'notice')", NULL }, { "quiet", 'q', POPT_ARG_NONE, &quiet, 0, "suppress stdout/stderr", NULL }, { 0, 0, 0, 0, 0, 0 } }; context = poptGetContext("initlog", argc, argv, optTable, 0); while ((rc = poptGetNextOpt(context)) > 0) { switch (rc) { case 1: lfac=atoi(fac); if ((lfac == 0) && strcmp(fac,"0")) { int x =0; lfac = LOG_DAEMON; for (x=0;facilitynames[x].c_name;x++) { if (!strcmp(fac,facilitynames[x].c_name)) { lfac = facilitynames[x].c_val; break; } } } break; case 2: lpri = atoi(pri); if ((lpri == 0) && strcmp(pri,"0")) { int x=0; lpri = LOG_NOTICE; for (x=0;prioritynames[x].c_name;x++) { if (!strcmp(pri,prioritynames[x].c_name)) { lpri = prioritynames[x].c_val; break; } } } break; case 3: reexec = 1; break; default: break; } } if ((rc < -1)) { if (!silent) fprintf(stderr, "%s: %s\n", poptBadOption(context, POPT_BADOPTION_NOALIAS), poptStrerror(rc)); return -1; } if ( (cmd && logstring) || (cmd && cmdname) ) { if (!silent) fprintf(stderr, _("--cmd and --run are incompatible with --string or --name\n")); return -1; } if ( cmdname && (!logstring && !cmdevent)) { if (!silent) fprintf(stderr, _("--name requires one of --event or --string\n")); return -1; } if (cmdevent && cmd) { if (!silent) fprintf(stderr, _("--cmd and --run are incompatible with --event\n")); return -1; } if (conffile) { readConfiguration(conffile); } else { readConfiguration("/etc/initlog.conf"); } if (cmd) { while (isspace(*cmd)) cmd++; } if (lpri!=-1) logpriority=lpri; if (lfac!=-1) logfacility=lfac; if (cmdevent) { logEvent(cmdname,cmdevent,logstring); } else if (logstring) { logString(cmdname,logstring); } else if ( cmd && *cmd) { return(runCommand(cmd,reexec,quiet,debug)); } else { if (!silent) fprintf(stderr,"nothing to do!\n"); return -1; } return 0; } int main(int argc, char **argv) { setlocale(LC_ALL,""); bindtextdomain("initlog","/etc/locale"); textdomain("initlog"); exit(processArgs(argc,argv,0)); } 'n221' href='#n221'>221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
<?php
/**
*
* This file is part of the phpBB Forum Software package.
*
* @copyright (c) phpBB Limited <https://www.phpbb.com>
* @license GNU General Public License, version 2 (GPL-2.0)
*
* For full copyright and license information, please see
* the docs/CREDITS.txt file.
*
*/

namespace phpbb\db\driver;

/**
* PostgreSQL Database Abstraction Layer
* Minimum Requirement is Version 8.3+
*/
class postgres extends \phpbb\db\driver\driver
{
	var $multi_insert = true;
	var $last_query_text = '';
	var $connect_error = '';

	/**
	* {@inheritDoc}
	*/
	function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false)
	{
		$connect_string = '';

		if ($sqluser)
		{
			$connect_string .= "user=$sqluser ";
		}

		if ($sqlpassword)
		{
			$connect_string .= "password=$sqlpassword ";
		}

		if ($sqlserver)
		{
			// $sqlserver can carry a port separated by : for compatibility reasons
			// If $sqlserver has more than one : it's probably an IPv6 address.
			// In this case we only allow passing a port via the $port variable.
			if (substr_count($sqlserver, ':') === 1)
			{
				list($sqlserver, $port) = explode(':', $sqlserver);
			}

			if ($sqlserver !== 'localhost')
			{
				$connect_string .= "host=$sqlserver ";
			}

			if ($port)
			{
				$connect_string .= "port=$port ";
			}
		}

		$schema = '';

		if ($database)
		{
			$this->dbname = $database;
			if (strpos($database, '.') !== false)
			{
				list($database, $schema) = explode('.', $database);
			}
			$connect_string .= "dbname=$database";
		}

		$this->persistency = $persistency;

		if ($this->persistency)
		{
			if (!function_exists('pg_pconnect'))
			{
				$this->connect_error = 'pg_pconnect function does not exist, is pgsql extension installed?';
				return $this->sql_error('');
			}
			$collector = new \phpbb\error_collector;
			$collector->install();
			$this->db_connect_id = (!$new_link) ? @pg_pconnect($connect_string) : @pg_pconnect($connect_string, PGSQL_CONNECT_FORCE_NEW);
		}
		else
		{
			if (!function_exists('pg_connect'))
			{
				$this->connect_error = 'pg_connect function does not exist, is pgsql extension installed?';
				return $this->sql_error('');
			}
			$collector = new \phpbb\error_collector;
			$collector->install();
			$this->db_connect_id = (!$new_link) ? @pg_connect($connect_string) : @pg_connect($connect_string, PGSQL_CONNECT_FORCE_NEW);
		}

		$collector->uninstall();

		if ($this->db_connect_id)
		{
			if ($schema !== '')
			{
				@pg_query($this->db_connect_id, 'SET search_path TO ' . $schema);
			}
			return $this->db_connect_id;
		}

		$this->connect_error = $collector->format_errors();
		return $this->sql_error('');
	}

	/**
	* {@inheritDoc}
	*/
	function sql_server_info($raw = false, $use_cache = true)
	{
		global $cache;

		if (!$use_cache || empty($cache) || ($this->sql_server_version = $cache->get('pgsql_version')) === false)
		{
			$query_id = @pg_query($this->db_connect_id, 'SELECT VERSION() AS version');
			if ($query_id)
			{
				$row = pg_fetch_assoc($query_id, null);
				pg_free_result($query_id);

				$this->sql_server_version = (!empty($row['version'])) ? trim(substr($row['version'], 10)) : 0;

				if (!empty($cache) && $use_cache)
				{
					$cache->put('pgsql_version', $this->sql_server_version);
				}
			}
		}

		return ($raw) ? $this->sql_server_version : 'PostgreSQL ' . $this->sql_server_version;
	}

	/**
	* SQL Transaction
	* @access private
	*/
	function _sql_transaction($status = 'begin')
	{
		switch ($status)
		{
			case 'begin':
				return @pg_query($this->db_connect_id, 'BEGIN');
			break;

			case 'commit':
				return @pg_query($this->db_connect_id, 'COMMIT');
			break;

			case 'rollback':
				return @pg_query($this->db_connect_id, 'ROLLBACK');
			break;
		}

		return true;
	}

	/**
	* {@inheritDoc}
	*/
	function sql_query($query = '', $cache_ttl = 0)
	{
		if ($query != '')
		{
			global $cache;

			// EXPLAIN only in extra debug mode
			if (defined('DEBUG'))
			{
				$this->sql_report('start', $query);
			}
			else if (defined('PHPBB_DISPLAY_LOAD_TIME'))
			{
				$this->curtime = microtime(true);
			}

			$this->last_query_text = $query;
			$this->query_result = ($cache && $cache_ttl) ? $cache->sql_load($query) : false;
			$this->sql_add_num_queries($this->query_result);

			if ($this->query_result === false)
			{
				if (($this->query_result = @pg_query($this->db_connect_id, $query)) === false)
				{
					$this->sql_error($query);
				}

				if (defined('DEBUG'))
				{
					$this->sql_report('stop', $query);
				}
				else if (defined('PHPBB_DISPLAY_LOAD_TIME'))
				{
					$this->sql_time += microtime(true) - $this->curtime;
				}

				if (!$this->query_result)
				{
					return false;
				}

				if ($cache && $cache_ttl)
				{
					$this->open_queries[(int) $this->query_result] = $this->query_result;
					$this->query_result = $cache->sql_save($this, $query, $this->query_result, $cache_ttl);
				}
				else if (strpos($query, 'SELECT') === 0)
				{
					$this->open_queries[(int) $this->query_result] = $this->query_result;
				}
			}
			else if (defined('DEBUG'))
			{
				$this->sql_report('fromcache', $query);
			}
		}
		else
		{
			return false;
		}

		return $this->query_result;
	}

	/**
	* Build db-specific query data
	* @access private
	*/
	function _sql_custom_build($stage, $data)
	{
		return $data;
	}

	/**
	* Build LIMIT query
	*/
	function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0)
	{
		$this->query_result = false;

		// if $total is set to 0 we do not want to limit the number of rows
		if ($total == 0)
		{
			$total = 'ALL';
		}

		$query .= "\n LIMIT $total OFFSET $offset";

		return $this->sql_query($query, $cache_ttl);
	}

	/**
	* {@inheritDoc}
	*/
	function sql_affectedrows()
	{
		return ($this->query_result) ? @pg_affected_rows($this->query_result) : false;
	}

	/**
	* {@inheritDoc}
	*/
	function sql_fetchrow($query_id = false)
	{
		global $cache;

		if ($query_id === false)
		{
			$query_id = $this->query_result;
		}

		if ($cache && $cache->sql_exists($query_id))
		{
			return $cache->sql_fetchrow($query_id);
		}

		return ($query_id) ? pg_fetch_assoc($query_id, null) : false;
	}

	/**
	* {@inheritDoc}
	*/
	function sql_rowseek($rownum, &$query_id)
	{
		global $cache;

		if ($query_id === false)
		{
			$query_id = $this->query_result;
		}

		if ($cache && $cache->sql_exists($query_id))
		{
			return $cache->sql_rowseek($rownum, $query_id);
		}

		return ($query_id) ? @pg_result_seek($query_id, $rownum) : false;
	}

	/**
	* {@inheritDoc}
	*/
	function sql_nextid()
	{
		$query_id = $this->query_result;

		if ($query_id !== false && $this->last_query_text != '')
		{
			if (preg_match("/^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)/is", $this->last_query_text, $tablename))
			{
				$query = "SELECT currval('" . $tablename[1] . "_seq') AS last_value";
				$temp_q_id = @pg_query($this->db_connect_id, $query);

				if (!$temp_q_id)
				{
					return false;
				}

				$temp_result = pg_fetch_assoc($temp_q_id, null);
				pg_free_result($query_id);

				return ($temp_result) ? $temp_result['last_value'] : false;
			}
		}

		return false;
	}

	/**
	* {@inheritDoc}
	*/
	function sql_freeresult($query_id = false)
	{
		global $cache;

		if ($query_id === false)
		{
			$query_id = $this->query_result;
		}

		if ($cache && !is_object($query_id) && $cache->sql_exists($query_id))
		{
			return $cache->sql_freeresult($query_id);
		}

		if (isset($this->open_queries[(int) $query_id]))
		{
			unset($this->open_queries[(int) $query_id]);
			return pg_free_result($query_id);
		}

		return false;
	}

	/**
	* {@inheritDoc}
	*/
	function sql_escape($msg)
	{
		return @pg_escape_string($msg);
	}

	/**
	* Build LIKE expression
	* @access private
	*/
	function _sql_like_expression($expression)
	{
		return $expression;
	}

	/**
	* Build NOT LIKE expression
	* @access private
	*/
	function _sql_not_like_expression($expression)
	{
		return $expression;
	}

	/**
	* {@inheritDoc}
	*/
	function cast_expr_to_bigint($expression)
	{
		return 'CAST(' . $expression . ' as DECIMAL(255, 0))';
	}

	/**
	* {@inheritDoc}
	*/
	function cast_expr_to_string($expression)
	{
		return 'CAST(' . $expression . ' as VARCHAR(255))';
	}

	/**
	* return sql error array
	* @access private
	*/
	function _sql_error()
	{
		// pg_last_error only works when there is an established connection.
		// Connection errors have to be tracked by us manually.
		if ($this->db_connect_id)
		{
			$message = @pg_last_error($this->db_connect_id);
		}
		else
		{
			$message = $this->connect_error;
		}

		return array(
			'message'	=> $message,
			'code'		=> ''
		);
	}

	/**
	* Close sql connection
	* @access private
	*/
	function _sql_close()
	{
		return @pg_close($this->db_connect_id);
	}

	/**
	* Build db-specific report
	* @access private
	*/
	function _sql_report($mode, $query = '')
	{
		switch ($mode)
		{
			case 'start':

				$explain_query = $query;
				if (preg_match('/UPDATE ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m))
				{
					$explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2];
				}
				else if (preg_match('/DELETE FROM ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m))
				{
					$explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2];
				}

				if (preg_match('/^SELECT/', $explain_query))
				{
					$html_table = false;

					if ($result = @pg_query($this->db_connect_id, "EXPLAIN $explain_query"))
					{
						while ($row = pg_fetch_assoc($result, null))
						{
							$html_table = $this->sql_report('add_select_row', $query, $html_table, $row);
						}
						pg_free_result($result);
					}

					if ($html_table)
					{
						$this->html_hold .= '</table>';
					}
				}

			break;

			case 'fromcache':
				$endtime = explode(' ', microtime());
				$endtime = $endtime[0] + $endtime[1];

				$result = @pg_query($this->db_connect_id, $query);
				if ($result)
				{
					while ($void = pg_fetch_assoc($result, null))
					{
						// Take the time spent on parsing rows into account
					}
					pg_free_result($result);
				}

				$splittime = explode(' ', microtime());
				$splittime = $splittime[0] + $splittime[1];

				$this->sql_report('record_fromcache', $query, $endtime, $splittime);

			break;
		}
	}
}