pinetd2 /code/classes/Daemon/PMaild/POP3_Client.class.php

Language PHP Lines 436
MD5 Hash 8cf3dd4fff834d25db5c9136fb32fe63
Repository https://github.com/blekkzor/pinetd2.git View Raw File View Project SPDX
  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
<?php

namespace Daemon\PMaild;
use pinetd\SQL;

class POP3_Client extends \pinetd\TCP\Client {
	protected $login = null;
	protected $info = null;
	protected $loggedin = false;
	protected $localNum = array(0 => null);
	protected $toDelete = array(); // list of stuff that should be deleted on QUIT, and only on QUIT
	protected $sql;
	protected $localConfig;

	function __construct($fd, $peer, $parent, $protocol) {
		parent::__construct($fd, $peer, $parent, $protocol);
		$this->setMsgEnd("\r\n");
	}

	function welcomeUser() { // nothing to do
		return true;
	}

	function sendBanner() {
		$this->sendMsg('+OK '.$this->IPC->getName().' POP3 (pmaild v2.0.0; pinetd v'.PINETD_VERSION.')');
		$this->localConfig = $this->IPC->getLocalConfig();
		return true;
	}

	function shutdown() {
		$this->sendMsg('-ERR POP3 server is shutting down, please try again later');
	}

	protected function identify($pass) { // login in $this->login
		$class = relativeclass($this, 'MTA\Auth');
		$auth = new $class($this->localConfig);
		$this->loggedin = $auth->login($this->login, $pass, 'pop3');
		if (!$this->loggedin) return false;
		$this->login = $auth->getLogin();
		$info = $auth->getInfo();
		$this->info = $info;
		// link to MySQL
		$this->sql = SQL::Factory($this->localConfig['Storage']);
		return true;
	}

	// POP3 is rather annoying, we need to have our own list of ids specific to the current session ONLY
	protected function getLocalNum($id) {
		$tnum = array_search($id, $this->localNum);
		if ($tnum !== false) return $tnum; // found
		// allocate an id
		$this->localNum[] = $id;
		// return id
		return array_search($id, $this->localNum);
	}

	protected function resolveLocalNum($tnum) {
		return $this->localNum[$tnum];
	}

	protected function mailPath($uniq) {
		$path = $this->localConfig['Mails']['Path'].'/domains';
		if ($path[0] != '/') $path = PINETD_ROOT . '/' . $path; // make it absolute
		$id = $this->info['domainid'];
		$id = str_pad($id, 10, '0', STR_PAD_LEFT);
		$path .= '/' . substr($id, -1) . '/' . substr($id, -2) . '/' . $id;
		$id = $this->info['account']->id;
		$id = str_pad($id, 4, '0', STR_PAD_LEFT);
		$path .= '/' . substr($id, -1) . '/' . substr($id, -2) . '/' . $id;
		$path.='/'.$uniq;
		return $path;
	}

	function _cmd_default() {
		$this->sendMsg('-ERR Unknown command');
	}

	function _cmd_quit() {
		if ($this->loggedin) {
			// delete messages
			foreach($this->toDelete as $id => $mail) {
				$mailid = $mail->mailid;
				$file = $this->mailPath($mail->uniqname);
				unlink($file);
				clearstatcache();
				if (file_exists($file)) continue; // could not delete?
				$mail->delete();
				$this->sql->DAO('z'.$this->info['domainid'].'_mime', 'mimeid')->delete(array('userid'=>$this->info['account']->id, 'mailid'=>$mailid));
				$this->sql->DAO('z'.$this->info['domainid'].'_mime_header', 'headerid')->delete(array('userid'=>$this->info['account']->id, 'mailid'=>$mailid));
			}

			// Extra: update mail_count and mail_quota (for this user)
			try {
				$this->sql->query('UPDATE `z'.$this->info['domainid'].'_accounts` AS a SET `mail_count` = (SELECT COUNT(1) FROM `z'.$this->info['domainid'].'_mails` AS b WHERE a.`id` = b.`userid`) WHERE a.`id` = \''.$this->sql->escape_string($this->info['account']->id).'\'');
				$this->sql->query('UPDATE `z'.$this->info['domainid'].'_accounts` AS a SET `mail_quota` = (SELECT SUM(b.`size`) FROM `z'.$this->info['domainid'].'_mails` AS b WHERE a.`id` = b.`userid`) WHERE a.`id` = \''.$this->sql->escape_string($this->info['account']->id).'\'');
			} catch(Exception $e) {
				// ignore it
			}
		}

		$this->sendMsg('+OK '.$this->IPC->getName().' closing control connexion.');
		$this->close();
	}

	function _cmd_stls() {
		if (!$this->IPC->hasTLS()) {
			$this->sendMsg('-ERR SSL not available');
			return;
		}
		if ($this->protocol != 'tcp') {
			$this->sendMsg('-ERR STLS only available in PLAIN mode. An encryption mode is already enabled');
			return;
		}
		$this->sendMsg('+OK Begin TLS negotiation');
		// TODO: this call will lock, need a way to avoid from doing it without Fork
		if (!stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_SERVER)) {
			$this->sendMsg('-ERR TLS negociation failed!');
			$this->close();
		}
		$this->protocol = 'tls';
	}

	function _cmd_auth($argv) {
		if ($this->loggedin) {
			$this->sendMsg('-ERR You do not need to AUTH two times');
			return;
		}
		if (($this->IPC->requireSsl()) && ($this->protocol == 'tcp')) return $this->sendMsg('-ERR Need SSL before logging in');
		if (!$argv[1]) {
			$this->sendMsg('+OK list of SASL extensions follows');
			$this->sendMsg('PLAIN');
			$this->sendMsg('.');
			return;
		}
		if ($argv[1] != 'PLAIN') {
			$this->sendMsg('-ERR Unknown AUTH method');
			return;
		}
		if (!$argv[2]) { // AUTH PLAIN <response>, or given on different line...
			$this->sendMsg('+ go ahead');
			$argv[2] = $this->readLine(); // TODO: not fork-compliant
		}
		$response = base64_decode($argv[2]);
		if ($response[0] != "\0") {
			$this->sendMsg('-ERR syntax error');
			return;
		}
		$response = explode("\0", $response);
		$this->login = $response[1];
		if ($this->identify($response[2])) {
			$this->sendMsg('+OK Authorization granted');
		} else {
			sleep(4);
			$this->sendMsg('-ERR Authorization denied');
		}
	}

	function _cmd_user($argv) {
		if ($this->loggedin) {
			$this->sendMsg('-ERR already logged in');
			return;
		}
		if (($this->IPC->requireSsl()) && ($this->protocol == 'tcp')) return $this->sendMsg('-ERR Need SSL before logging in');
		if (count($argv) < 2) {
			$this->sendMsg('-ERR Syntax: USER <login>');
			return;
		}
		$this->login = $argv[1];
		$this->sendMsg('+OK Provide PASSword now, please');
	}

	function _cmd_pass($argv) {
		if ($this->loggedin) {
			$this->sendMsg('-ERR Already logged in');
			return;
		}
		if (($this->IPC->requireSsl()) && ($this->protocol == 'tcp')) return $this->sendMsg('-ERR Need SSL before logging in');
		if (count($argv) < 2) {
			$this->sendMsg('-ERR Syntax: PASS <password>');
			return;
		}
		if ($this->identify($argv[1])) {
			$this->sendMsg('+OK Authorization granted');
		} else {
			sleep(4);
			$this->sendMsg('-ERR Authorization denied');
		}
	}

	function _cmd_noop() {
		if (!$this->loggedin) return $this->sendMsg('-ERR need to login first');
		$this->sendMsg('+OK'); // nothing :D
	}

	function _cmd_rset() {
		if (!$this->loggedin) return $this->sendMsg('-ERR need to login first');
		$this->toDelete = array();
		$this->sendMsg('+OK');
	}

	function _cmd_stat() {
		if (!$this->loggedin) return $this->sendMsg('-ERR need to login first');
		$this->sendMsg('+OK '.$this->info['account']->mail_count.' '.$this->info['account']->mail_quota);
	}

	function _cmd_list($argv) {
		if (!$this->loggedin) return $this->sendMsg('-ERR need to login first');
		$cond = array('userid' => $this->info['account']->id);
		$onlyone = false;
		if ($argv[1]) {
			$id = $argv[1];
			if (isset($this->toDelete[$id])) {
				$this->sendMsg('-ERR Message was deleted, you can still restore it using RSET');
				return;
			}
			$tid = $this->resolveLocalNum($id);
			if (is_null($tid)) {
				$this->sendMsg('-ERR Unknown message');
				return;
			}
			$cond['mailid'] = $tid;
			$onlyone = true;
		} else {
			$this->sendMsg('+OK'); // list...
		}
		$DAO_mails = $this->sql->DAO('z'.$this->info['domainid'].'_mails', 'mailid');
		$list = $DAO_mails->loadByField($cond);
		foreach($list as $mail) {
			$flags = array_flip(explode(',', $mail->flags));
			if (isset($flags['deleted'])) continue;
			$num = $this->getLocalNum($mail->mailid);
			if (isset($this->toDelete[$num])) continue;
			$file = $this->mailPath($mail->uniqname);
			if (!file_exists($file)) {
				$mail->delete();
				continue;
			}
			$s = filesize($file);
			if ($onlyone) {
				$this->sendMsg('+OK '.$num.' '.$s);
				return;
			}
			$this->sendMsg($num.' '.$s);
		}
		$this->sendMsg('.');
	}

	function _cmd_uidl($argv) {
		if (!$this->loggedin) return $this->sendMsg('-ERR need to login first');
		$cond = array('userid' => $this->info['account']->id);
		$onlyone = false;
		if ($argv[1]) {
			$id = $argv[1];
			if (isset($this->toDelete[$id])) {
				$this->sendMsg('-ERR Message was deleted, you can still restore it using RSET');
				return;
			}
			$tid = $this->resolveLocalNum($id);
			if (is_null($tid)) {
				$this->sendMsg('-ERR Unknown message');
				return;
			}
			$cond['mailid'] = $tid;
			$onlyone = true;
		} else {
			$this->sendMsg('+OK'); // list...
		}
		$DAO_mails = $this->sql->DAO('z'.$this->info['domainid'].'_mails', 'mailid');
		$list = $DAO_mails->loadByField($cond);
		foreach($list as $mail) {
			$flags = array_flip(explode(',', $mail->flags));
			if (isset($flags['deleted'])) continue;
			$num = $this->getLocalNum($mail->mailid);
			if (isset($this->toDelete[$num])) continue;
			$s = $mail->uniqname;
			if ($onlyone) {
				$this->sendMsg('+OK '.$num.' '.$s);
				return;
			}
			$this->sendMsg($num.' '.$s);
		}
		$this->sendMsg('.');
	}

	function _cmd_retr($argv) {
		$id = (int)$argv[1];
		if (isset($this->toDelete[$id])) {
			$this->sendMsg('-ERR Message was deleted');
			return;
		}
		$tid = $this->resolveLocalNum($id);
		if (is_null($tid)) {
			$this->sendMsg('-ERR Message not found');
			return;
		}
		$DAO_mails = $this->sql->DAO('z'.$this->info['domainid'].'_mails', 'mailid');
		$mail = $DAO_mails->loadByField(array('userid' => $this->info['account']->id, 'mailid' => $tid));
		if (!$mail) {
			$this->sendMsg('-ERR Message not found');
			return;
		}
		$mail = $mail[0];
		$flags = array_flip(explode(',', $mail->flags));
		if (isset($flags['deleted'])) {
			$this->sendMsg('-ERR Message not found');
			return;
		}
		$file = $this->mailPath($mail->uniqname);
		$fd = fopen($file, 'r');
		if (!$fd) { // something is wrong with filesystem
			$this->sendMsg('+OK');
			$this->sendMsg('.');
			return;
		}
		$this->sendMsg('+OK');
		while(!feof($fd)) {
			$lin = fgets($fd);
			if ($lin[0] == '.') fputs($this->fd, '.');
			fputs($this->fd, $lin);
		}
		fclose($fd);
		$this->sendMsg('.');
		// mark the message as "read"
		$flags = array_flip(explode(',', $mail->flags));
		if (isset($flags['recent'])) {
			unset($flags['recent']);
			$mail->flags = implode(',', array_flip($flags));
			$mail->commit();
		}
	}

	function _cmd_top($argv) {
		// return headers plus n lines of mail
		$id = (int)$argv[1];
		$count = (int)$argv[2];
		if (isset($this->toDelete[$id])) {
			$this->sendMsg('-ERR Message was deleted');
			return;
		}
		$tid = $this->resolveLocalNum($id);
		if (is_null($tid)) {
			$this->sendMsg('-ERR Message not found');
			return;
		}
		$DAO_mails = $this->sql->DAO('z'.$this->info['domainid'].'_mails', 'mailid');
		$mail = $DAO_mails->loadByField(array('userid' => $this->info['account']->id, 'mailid' => $tid));
		if (!$mail) {
			$this->sendMsg('-ERR Message not found');
			return;
		}
		$mail = $mail[0];
		$flags = array_flip(explode(',', $mail->flags));
		if (isset($flags['deleted'])) {
			$this->sendMsg('-ERR Message not found');
			return;
		}
		$file = $this->mailPath($mail->uniqname);
		$fd = fopen($file, 'r');
		if (!$fd) { // something is wrong with filesystem
			$this->sendMsg('+OK');
			$this->sendMsg('.');
			return;
		}
		$this->sendMsg('+OK');
		$h = true;
		while(!feof($fd)) {
			$lin = fgets($fd);
			if ($h) {
				if (rtrim($lin) === '') $h = false;
			} else {
				if($count--<=0) break;
			}
			if ($lin[0] == '.') fputs($this->fd, '.');
			fputs($this->fd, $lin);
		}
		fclose($fd);
		$this->sendMsg('.');
		// mark the message as "read"
		$flags = array_flip(explode(',', $mail->flags));
		if (isset($flags['recent'])) {
			unset($flags['recent']);
			$mail->flags = implode(',', array_flip($flags));
			$mail->commit();
		}
	}

	function _cmd_dele($argv) {
		$id = (int)$argv[1];
		if (isset($this->toDelete[$id])) {
			$this->sendMsg('-ERR Message was deleted');
			return;
		}
		$tid = $this->resolveLocalNum($id);
		if (is_null($tid)) {
			$this->sendMsg('-ERR Message not found');
			return;
		}
		$DAO_mails = $this->sql->DAO('z'.$this->info['domainid'].'_mails', 'mailid');
		$mail = $DAO_mails->loadByField(array('userid' => $this->info['account']->id, 'mailid' => $tid));
		if (!$mail) {
			$this->sendMsg('-ERR Message not found');
			return;
		}
		$mail = $mail[0];
		$flags = array_flip(explode(',', $mail->flags));
		if (isset($flags['deleted'])) {
			$this->sendMsg('-ERR Message not found');
			return;
		}
		$this->toDelete[$id] = $mail;
		$this->sendMsg('+OK Nessage marked for deletion');
	}

	function _cmd_capa($argv) {
		$capa = array(
			'TOP',
//			'RESP-CODES',
			'PIPELINING',
			'UIDL',
			'IMPLEMENTATION pMaild 2.0',
//			'AUTH-RESP-CODE',
		);
		if ($this->protocol != 'tcp') {
			$capa[] = 'USER';
			$capa[] = 'SASL PLAIN'; // SASL CRAM-MD5 DIGEST-MD5 PLAIN
		} else {
			$capa[] = 'STLS';
		}
		$this->sendMsg('+OK');
		foreach($capa as $cap) $this->sendMsg($cap);
		$this->sendMsg('.');
	}
}
Back to Top