xaizek / rocketgit (License: AGPLv3+) (since 2018-12-09)
Light and fast Git hosting solution suitable to serve both as a hub or as a personal code storage with its tickets, pull requests, API and much more.
<root> / inc / ldap_sync.inc.php (3c220f4a167a5f435ac5f3d7b411b9e8349cdde2) (10KiB) (mode 100644) [raw]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
<?php
require_once($INC . "/sql.inc.php");
require_once($INC . "/state.inc.php");
require_once($INC . "/prof.inc.php");
require_once($INC . "/ldap_core.inc.php");

/*
 * Get data from cache
 */
function rg_ldap_sync_get_cache($db, $v)
{
	rg_log_enter('ldap_sync_get_cache');

	$ret = array('ok' => 0);
	while (1) {
		$params = array('v' => $v);
		$sql = 'SELECT a.* FROM ldap_cache AS a, ldap_servers AS b'
			. ' WHERE a.server_id = b.id'
			. ' AND (mail = @@v@@'
			. ' OR ldap_uid = @@v@@'
			. ' OR cn = @@v@@)'
			. ' ORDER BY b.prio';
		$res = rg_sql_query_params($db, $sql, $params);
		if ($res === FALSE) {
			$ret['errmsg'] = 'cannot select from cache';
			break;
		}

		$ret['list'] = array();
		while (($row = rg_sql_fetch_array($res)))
			$ret['list'][] = $row;

		rg_sql_free_result($res);

		$ret['ok'] = 1;
		break;
	}

	rg_log_exit();
	return $ret;
}

/*
 * Updates ldap_cache table
 * TODO: should be moved to ldap.inc.php because is called from there?
 * And get rid of "_sync_" in name.
 */
function rg_ldap_sync_update_cache($db, $l)
{
	rg_log_enter('ldap_sync_update_cache');

	rg_log_ml('DEBUG: l: ' . print_r($l, TRUE));

	$ret = array('ok' => 0);
	while (1) {
		// We update uid only if != 0
		$add = '';
		if ($l['uid'] > 0)
			$add .= ', uid = @@uid@@';

		$sql = 'UPDATE ldap_cache SET'
			. ' ldap_uid = @@ldap_uid@@'
			. $add
			. ', password = @@password@@'
			. ', sn = @@sn@@'
			. ', gn = @@gn@@'
			. ', gid = @@gid@@'
			. ', mail = @@mail@@'
			. ', cn = @@cn@@'
			. ', shadow_expire = @@shadow_expire@@'
			. ' WHERE server_id = @@server_id@@'
			. ' AND uuid = @@uuid@@';
		$res = rg_sql_query_params($db, $sql, $l);
		if ($res === FALSE) {
			$ret['errmsg'] = 'error in update';
			break;
		}
		$arows = rg_sql_affected_rows($res);
		rg_sql_free_result($res);

		if ($arows > 0) {
			$ret['ok'] = 1;
			break;
		}

		$sql = 'INSERT INTO ldap_cache (uid, ldap_uid, password'
			. ', sn, gn, gid, mail, cn, shadow_expire'
			. ', server_id, uuid)'
			. ' VALUES (@@uid@@, @@ldap_uid@@, @@password@@'
			. ', @@sn@@, @@gn@@, @@gid@@, @@mail@@'
			. ', @@cn@@, @@shadow_expire@@, @@server_id@@'
			. ', @@uuid@@)';
		$ignore = array(RG_SQL_UNIQUE_VIOLATION);
		$res = rg_sql_query_params_ignore($db, $sql, $l,
			$ignore, $ignore_kicked);
		if ($res === FALSE) {
			if (!$ignore_kicked) {
				$ret['errmsg'] = 'error in update';
				break;
			}
			rg_log('Entry already in cache.');
		} else {
			rg_sql_free_result($res);
		}

		$ret['ok'] = 1;
		break;
	}

	rg_log_exit();
	return $ret;
}

/*
 * Updates ldap_servers table - for now, CSNs
 * TODO: It should be used to set also the last error message?
 * Maybe we should have a different log for this kind of problems,
 * and send it to the admin.
 */
function rg_ldap_sync_update_server($db, $server_id, $csn)
{
	rg_log_enter('ldap_sync_update_server');

	$ret = array('ok' => 0);
	while (1) {
		if (empty($csn)) {
			$ret['ok'] = 1;
			break;
		}

		$params = array(
			'server_id' => $server_id,
			'csn' => $csn
		);
		$sql = 'UPDATE ldap_servers SET'
			. ' csn = @@csn@@'
			. ' WHERE id = @@server_id@@';
		$res = rg_sql_query_params($db, $sql, $params);
		if ($res === FALSE) {
			$ret['errmsg'] = 'error in update';
			break;
		}
		rg_sql_free_result($res);

		$ret['ok'] = 1;
		break;
	}

	rg_log_exit();
	return $ret;
}

/*
 * It applies the updates to the database.
 * Input is a ldif parsed as an array (from rg_ldap_core_ldif2array)
 */
function rg_ldap_sync_apply($db, $server_id, $data)
{
	rg_log_enter('ldap_sync_apply');

	$ret = array();
	$ret['ok'] = 0;
	while (1) {
		rg_log_ml('data: ' . print_r($data, TRUE));

		if (rg_sql_begin($db) !== TRUE) {
			$ret['errmsg'] = 'cannot start transaction';
			break;
		}
		$rollback = TRUE;

		$csn = array();
		foreach ($data as $block_id => $block) {
			if (isset($block['entryCSN'][0])) {
				rg_log('DEBUG: entryCSN is present!');
				$c = $block['entryCSN'][0];
				// Example: 20171001075924.155248Z#000000#001#000000
				$_t = explode('#', $c);
				$_s = isset($_t[2]) ? $_t[2] : '';
				if (!isset($csn[$_s]) || ($c > $csn[$_s]))
					$csn[$_s] = $c;
			} else {
				rg_log('DEBUG: entryCSN is NOT present!');
			}

			if (!isset($block['objectClass'])) {
				$ret['errmsg'] = 'missing objectClass';
				break;
			}

			// Try to detect if is a user entry
			$is_user = FALSE;
			foreach ($block['objectClass'] as $oc) {
				if (strcasecmp($oc, 'inetOrgPerson') == 0) {
					$is_user = TRUE;
					break;
				}
			}

			if (!$is_user)
				continue;

			$l = array();
			$l['uid'] = 0;
			$l['ldap_uid'] = isset($block['uid'][0]) ? $block['uid'][0] : '';
			$l['password'] = isset($block['userPassword'][0]) ? $block['userPassword'][0] : '';
			$l['sn'] = isset($block['sn'][0]) ? $block['sn'][0] : '';
			$l['gn'] = isset($block['givenName'][0]) ? $block['givenName'][0] : '';
			$l['gid'] = isset($block['gidNumber'][0]) ? $block['gidNumber'][0] : 0;
			$l['mail'] = isset($block['mail'][0]) ? $block['mail'][0] : '';
			$l['cn'] = isset($block['cn'][0]) ? $block['cn'][0] : '';
			$l['shadow_expire'] = isset($block['shadowExpire'][0]) ? $block['shadowExpire'][0] : '99999';
			$l['server_id'] = $server_id;
			$l['uuid'] = isset($block['entryUUID'][0]) ? $block['entryUUID'][0] : '';
			// Verifications
			if (empty($l['ldap_uid'])) {
				rg_log('DEBUG: ldap_uid is not present!');
				continue;
			}
			if (empty($l['uuid'])) {
				rg_log('DEBUG: entryUUID is not present!');
				continue;
			}

			rg_log_ml('DEBUG: l:' . print_r($l, TRUE));

			$r = rg_ldap_sync_update_cache($db, $l);
			if ($r['ok'] !== 1) {
				$r['errmsg'] = $r['errmsg'];
				break;
			}

			/*
			TODO foreach ($block['memberOf'] as $m)
				$pairs_groups[] = array($uuid, $m);
			*/
		}
		if (isset($ret['errmsg']))
			break;

		rg_log_ml('DEBUG: csn: ' . print_r($csn, TRUE));
		$r = rg_ldap_sync_update_server($db, $server_id,
			implode(';', $csn));
		if ($r['ok'] !== 1) {
			$ret['errmsg'] = $r['errmsg'];
			break;
		}

		if (rg_sql_commit($db) !== TRUE) {
			$ret['errmsg'] = 'cannot commit';
			break;
		}

		$ret['ok'] = 1;
		$rollback = FALSE;
		break;
	}

	if ($rollback)
		rg_sql_rollback($db);

	rg_log_exit();
	return $ret;
}

/*
 * Function called to process raw ldif blocks -> database
 */
function rg_ldap_sync_data($db, $server_id, $s)
{
	rg_log_enter('ldap_sync_data');
	rg_log('DEBUG: s=' . $s);

	$ret = array();
	$ret['ok'] = 0;
	while (1) {
		$a = rg_ldap_core_ldif2array($s);
		if ($a['ok'] != 1) {
			$ret['errmsg'] = $a['errmsg'];
			break;
		}

		// Update database
		if (!empty($a['data'])) {
			$r = rg_ldap_sync_apply($db, $server_id, $a['data']);
			if ($r['ok'] != 1) {
				$ret['errmsg'] = $r['errmsg'];
				break;
			}
		}

		$ret['ok'] = 1;
		$ret['used'] = $a['used'];
		break;
	}

	rg_log_exit();
	return $ret;
}

/*
 * 'input' callback for rg_ldap_sync_* functions
 */
function rg_ldap_sync_cb_input($index, &$info, $stream)
{
	rg_log_enter('ldap_sync_cb_input: index=' . $index
		. ' stream=' . $stream);

	while (1) {
		//rg_log_ml('info: ' . print_r($info, TRUE));

		$c = &$info['custom'];

		switch ($stream) {
		case 1:
			//rg_log('Got data: ' . $info['in_buf']);
			$r = rg_ldap_sync_data($c['db'], $c['server_id'],
				$info['in_buf']);
			if ($r['ok'] != 1) {
				rg_log('Error: ' . $r['errmsg']);
				$info['done'] = TRUE;
				break;
			}

			$info['in_buf'] = substr($info['in_buf'], $r['used']);
			break;

		case 2:
			// TODO: should we do something with this?
			// Maybe store it in the synchronization log?
			// Send it do admin?
			rg_log_ml('error received: ' . $info['err_buf']);
			$info['err_buf'] = '';
			break;
		}

		break;
	}

	rg_log_exit();
}

/*
 * 'error' calback for rg_ldap_sync_* functions
 */
function rg_ldap_sync_cb_error($index, &$info, $msg)
{
	rg_log('ldap_sync_cb_error: ' . $msg);
	$info['done'] = TRUE;
}

/*
 * Sync function using SyncRepl protocol (ro way)
 */
function rg_ldap_sync_ro($db, $data)
{
	// TODO: move this in the higher level part
	// Load the list of servers in decreasing priority order (increasing numeric)
	// because we want the best one to overwrite the lower priority ones.

	// Hm! Have a problem: sync_rp with multiple servers!

	$ret = array();
	$ret['ok'] = 0;
	while (1) {
		// Store password
		$r = rg_id(16);
		// TODO: choose a better name; choose a better dir
		$pass_file = '/tmp/' . $r;
		$f = @fopen($pass_file, 'w');
		if ($f === FALSE) {
			$ret['errmsg'] = 'cannot create pass file';
			break;
		}
		if (@chmod($pass_file, 0600) !== TRUE) {
			fclose($f);
			$ret['errmsg'] = 'cannot chmod pass';
			break;
		}

		$r = @fwrite($f, $data['bind_pass']);
		if ($r === FALSE) {
			fclose($f);
			$ret['errmsg'] = 'cannot write pass';
			break;
		}

		fclose($f);

		$cmd = 'ldapsearch -d-1 -LLL -v -b ' . escapeshellarg($data['base'])
			. ' -x -H ldap://' . escapeshellarg($data['addr'])
			. ':' . escapeshellarg($data['port'])
			. ' -D ' . escapeshellarg($data['bind_user'])
			. ' -y ' . escapeshellarg($pass_file)
			. ' -s sub -P 3';
		if (isset($data['rid']) && isset($data['csn'])) {
			$cmd .= ' -E ' . escapeshellarg('sync=ro/'
				. 'rid=' . $data['rid']
				. ',sid=001'
				. ',csn=' . $data['csn']);
		} else {
			$cmd .= ' -E sync=ro/rid=001,sid=001,csn=aaa';
		}

		if (isset($data['fields'])) {
			$fields = '';
			$add = '';
			foreach($data['fields'] as $f) {
				$fields .= $add . $f;
				$add = ',';
			}
		} else {
			$fields = '*';
		}

		$cmd .= ' "(|'
			. '(objectClass=groupOfNames)'
			. '(objectClass=groupOfUniqueNames)'
			. '(structuralObjectClass=inetOrgPerson)'
			. ')"';
		$cmd .= ' ' . escapeshellarg($fields) . ' +';
		$a = array(
			'cmds' => array(
				'cmd1' => array(
					'cmd' => $cmd,
					'cb_input' => 'rg_ldap_sync_cb_input',
					'cb_error' => 'rg_ldap_sync_cb_error',
					'custom' => array(
						'db' => $db,
						'server_id' => $data['server_id']
					)
				)
			)
		);
		$r = rg_exec2($a);
		@unlink($pass_file);
		if ($r['ok'] != 1) {
			$ret['errmsg'] = $r['errmsg'];
			break;
		}

		$ret['ok'] = 1;
		break;
	}

	return $ret;
}

?>
Hints

Before first commit, do not forget to setup your git environment:
git config --global user.name "your_name_here"
git config --global user.email "your@email_here"

Clone this repository using HTTP(S):
git clone https://code.reversed.top/user/xaizek/rocketgit

Clone this repository using ssh (do not forget to upload a key first):
git clone ssh://rocketgit@code.reversed.top/user/xaizek/rocketgit

You are allowed to anonymously push to this repository.
This means that your pushed commits will automatically be transformed into a pull request:
... clone the repository ...
... make some changes and some commits ...
git push origin master