Hoa central
Resolve.php
Go to the documentation of this file.
1 <?php
2 
37 namespace Hoa\Dns\Bin;
38 
39 use Hoa\Console;
40 use Hoa\Core;
41 use Hoa\Dns;
42 use Hoa\Socket;
43 
53 {
59  protected $options = [
60  ['listen', Console\GetOption::REQUIRED_ARGUMENT, 'l'],
61  ['help', Console\GetOption::NO_ARGUMENT, 'h'],
62  ['help', Console\GetOption::NO_ARGUMENT, '?']
63  ];
64 
65 
66 
72  public function main()
73  {
74  $listen = '127.0.0.1:57005';
75 
76  while (false !== $c = $this->getOption($v)) {
77  switch ($c) {
78  case 'l':
79  $listen = $v;
80 
81  break;
82 
83  case '__ambiguous':
84  $this->resolveOptionAmbiguity($v);
85 
86  break;
87 
88  case 'h':
89  case '?':
90  default:
91  return $this->usage();
92  }
93  }
94 
95  $redirections = [];
96  $inputs = $this->parser->getInputs();
97 
98  if (empty($inputs)) {
99  $this->usage();
100 
101  return;
102  }
103 
104  for ($i = 0, $max = count($inputs); $i < $max; $i += 3) {
105  $from = str_replace('#', '\#', $inputs[$i]);
106 
107  if (false === @preg_match('#^' . $from . '$#', '', $_)) {
108  echo 'Expression ', $from, ' does not compile correctly.', "\n";
109 
110  return 1;
111  }
112 
113  if ('to' !== $inputs[$i + 1]) {
114  continue;
115  }
116 
117  $to = $inputs[$i + 2];
118  $redirections[$from] = $to;
119  }
120 
121  $dns = new Dns\Resolver(new Socket\Server('udp://' . $listen));
122  $dns->on('query', function (Core\Event\Bucket $bucket) use (&$redirections) {
123 
124  $data = $bucket->getData();
125  echo
126  'Resolving domain ', $data['domain'],
127  ' of type ', $data['type'], ' to ';
128 
129  foreach ($redirections as $from => $to) {
130  if (0 !== preg_match('#^' . $from . '$#', $data['domain'], $_)) {
131  echo $to, ".\n";
132 
133  return $to;
134  }
135  }
136 
137  echo '127.0.0.1 (default).', "\n";
138 
139  return '127.0.0.1';
140  });
141 
142  echo 'Server is up, on udp://' . $listen . '!', "\n\n";
143  $dns->run();
144 
145  return;
146  }
147 
153  public function usage()
154  {
155  echo
156  'Usage : dns:resolve <options> [<regex> to <ip>]+', "\n",
157  'Options :', "\n",
158  $this->makeUsageOptionsList([
159  'l' => 'Socket URI to listen (default: 127.0.0.1:57005).',
160  'help' => 'This help.'
161  ]), "\n",
162  'Example: `… dns:resolve \'foo.*\' to 1.2.3.4 \\', "\n",
163  ' \'bar.*\' to 5.6.7.8`.', "\n";
164 
165  return;
166  }
167 }
168 
169 __halt_compiler();
170 Quick DNS resolver.
makeUsageOptionsList(Array $definitions=[])
Definition: Kit.php:149
getOption(&$optionValue, $short=null)
Definition: Kit.php:104
resolveOptionAmbiguity(Array $solutions)
Definition: Kit.php:190