summaryrefslogtreecommitdiff
path: root/core/EjabberdAuth.php
blob: f3a5bfcf9bb4b774350cccc3f5695b1c16656702 (plain)
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
<?php

/**
 * Runs constantly and takes requests from an input stream
 * as specified in the ejabberd auth protocol.
 */
class EjabberdAuth {
  var $running;

  function __construct($config, EjabberdAuthBridge $bridge) {
    $this->bridge = $bridge;
    $this->bridge->parent = $this;
    if (!empty($config['log_path']) && is_dir($config['log_path']) && is_writable($config['log_path'])) {
      $this->logfile = fopen($config['log_path'] . 'activity-' . date('Y-m-d') . '.log', 'a');
    }
    else {
      $this->logfile = STDERR;
    }
    $this->log('Starting...');
    $this->running = TRUE;
  }

  function stop() {
    $this->log("Stopping...");
    $this->running = FALSE;
  }

  function run() {
    while ($this->running) {
      $data = $this->read();
      if ($data) {
        $result = $this->execute($data);
        $this->write((int)$result);
      }
    }
    $this->log("Stopped");
  }

  function read() {
    $input = fread(STDIN, 2);
    if (!$input) {
      return $this->stop();
    }

    $input = unpack('n', $input);
    $length = $input[1];
    if($length > 0) {
      $this->log("Reading $length bytes...");
      $data = fread(STDIN, $length);
      return $data;
    }
  }

  function write($data) {
    $this->log("OUT: $data");
    fwrite(STDOUT, pack("nn", 2, $data));
  }

  function log($data) {
    fwrite($this->logfile, sprintf("%s [%d] - %s\n", date('Y-m-d H:i:s'), getmypid(), $data));
  }

  function execute($data) {
    $args = explode(':', $data);
    $command = array_shift($args);
    // Only log the username for security.
    $this->log("Executing $command on {$args[0]}");

    switch ($command) {
      case 'isuser':
        list($username, $server) = $args;
        return $this->bridge->isuser($username, $server);
      case 'auth':
        list($username, $server, $password) = $args;
        return $this->bridge->auth($username, $server, $password);
      case 'setpass':
        list($username, $server, $password) = $args;
        return $this->bridge->setpass($username, $server, $password);
      case 'tryregister':
        list($username, $server, $password) = $args;
        return $this->bridge->tryregister($username, $server, $password);
      case 'removeuser':
        list($username, $server) = $args;
        return $this->bridge->removeuser($username, $server);
      case 'removeuser3':
        list($username, $server, $password) = $args;
        return $this->bridge->auth($username, $server, $password) && $this->bridge->removeuser($username, $password);
      default:
        $this->stop();
    }
  }
}