Completed
Pull Request — v3 (#359)
by
unknown
05:29
created

Gamespy3::processDetails()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 2
crap 3
1
<?php
2
/**
3
 * This file is part of GameQ.
4
 *
5
 * GameQ is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU Lesser General Public License as published by
7
 * the Free Software Foundation; either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * GameQ is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public License
16
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
namespace GameQ\Protocols;
20
21
use GameQ\Protocol;
22
use GameQ\Buffer;
23
use GameQ\Result;
24
25
/**
26
 * GameSpy3 Protocol class
27
 *
28
 * Given the ability for non utf-8 characters to be used as hostnames, player names, etc... this
29
 * version returns all strings utf-8 encoded (utf8_encode).  To access the proper version of a
30
 * string response you must use utf8_decode() on the specific response.
31
 *
32
 * @author Austin Bischoff <[email protected]>
33
 */
34
class Gamespy3 extends Protocol
35
{
36
37
    /**
38
     * Array of packets we want to look up.
39
     * Each key should correspond to a defined method in this or a parent class
40
     *
41
     * @type array
42
     */
43
    protected $packets = [
44
        self::PACKET_CHALLENGE => "\xFE\xFD\x09\x10\x20\x30\x40",
45
        self::PACKET_ALL       => "\xFE\xFD\x00\x10\x20\x30\x40%s\xFF\xFF\xFF\x01",
46
    ];
47
48
    /**
49
     * The query protocol used to make the call
50
     *
51
     * @type string
52
     */
53
    protected $protocol = 'gamespy3';
54
55
    /**
56
     * String name of this protocol class
57
     *
58
     * @type string
59
     */
60
    protected $name = 'gamespy3';
61
62
    /**
63
     * Longer string name of this protocol class
64
     *
65
     * @type string
66
     */
67
    protected $name_long = "GameSpy3 Server";
68
69
    /**
70
     * The client join link
71
     *
72
     * @type string
73
     */
74
    protected $join_link = null;
75
76
    /**
77
     * Parse the challenge response and apply it to all the packet types
78
     *
79
     * @param \GameQ\Buffer $challenge_buffer
80
     *
81
     * @return bool
82
     * @throws \GameQ\Exception\Protocol
83
     */
84
    public function challengeParseAndApply(Buffer $challenge_buffer)
85
    {
86
        // Pull out the challenge
87
        $challenge = substr(preg_replace("/[^0-9\-]/si", "", $challenge_buffer->getBuffer()), 1);
88
89
        // By default, no challenge result (see #197) 
90
        $challenge_result = '';
91
92
        // Check for valid challenge (see #197)
93
        if ($challenge) {
94
            // Encode chellenge result
95
            $challenge_result = sprintf(
96
                "%c%c%c%c",
97
                ($challenge >> 24),
98
                ($challenge >> 16),
99
                ($challenge >> 8),
100
                ($challenge >> 0)
101
            );
102
        }
103
104
        // Apply the challenge and return
105
        return $this->challengeApply($challenge_result);
106
    }
107
108
    /**
109
     * Process the response
110
     *
111
     * @return array
112
     */
113 10
    public function processResponse()
114
    {
115
116
        // Holds the processed packets
117 10
        $processed = [];
118
119
        // Iterate over the packets
120 10
        foreach ($this->packets_response as $response) {
121
            // Make a buffer
122 10
            $buffer = new Buffer($response, Buffer::NUMBER_TYPE_BIGENDIAN);
123
124
            // Packet type = 0
125 10
            $buffer->readInt8();
126
127
            // Session Id
128 10
            $buffer->readInt32();
129
130
            // We need to burn the splitnum\0 because it is not used
131 10
            $buffer->skip(9);
132
133
            // Get the id
134 10
            $id = $buffer->readInt8();
135
136
            // Burn next byte not sure what it is used for
137 10
            $buffer->skip(1);
138
139
            // Add this packet to the processed
140 10
            $processed[$id] = $buffer->getBuffer();
141
142 10
            unset($buffer, $id);
143
        }
144
145
        // Sort packets, reset index
146 10
        ksort($processed);
147
148
        // Offload cleaning up the packets if they happen to be split
149 10
        $packets = $this->cleanPackets(array_values($processed));
150
151
        /*
152
         * Fix: when server name contains string "\u0000" - query fails. "\u0000" also separates properties from
153
         * server, so we are replacing double "\u0000" in server response.
154
         */
155 10
        $packets = preg_replace("/(\\x00){2,}gametype/", "\x00gametype", implode('', $packets));
156
157
        // Create a new buffer
158 10
        $buffer = new Buffer($packets, Buffer::NUMBER_TYPE_BIGENDIAN);
159
160
        // Create a new result
161 10
        $result = new Result();
162
163
        // Parse the server details
164 10
        $this->processDetails($buffer, $result);
165
166
        // Parse the player and team information
167 10
        $this->processPlayersAndTeams($buffer, $result);
168
169 10
        unset($buffer);
170
171 10
        return $result->fetch();
172
    }
173
174
    /*
175
     * Internal methods
176
     */
177
178
    /**
179
     * Handles cleaning up packets since the responses can be a bit "dirty"
180
     *
181
     * @param array $packets
182
     *
183
     * @return array
184
     */
185 10
    protected function cleanPackets(array $packets = [])
186
    {
187
188
        // Get the number of packets
189 10
        $packetCount = count($packets);
190
191
        // Compare last var of current packet with first var of next packet
192
        // On a partial match, remove last var from current packet,
193
        // variable header from next packet
194 10
        for ($i = 0, $x = $packetCount; $i < $x - 1; $i++) {
195
            // First packet
196 5
            $fst = substr($packets[$i], 0, -1);
197
            // Second packet
198 5
            $snd = $packets[$i + 1];
199
            // Get last variable from first packet
200 5
            $fstvar = substr($fst, strrpos($fst, "\x00") + 1);
201
            // Get first variable from last packet
202 5
            $snd = substr($snd, strpos($snd, "\x00") + 2);
203 5
            $sndvar = substr($snd, 0, strpos($snd, "\x00"));
204
            // Check if fstvar is a substring of sndvar
205
            // If so, remove it from the first string
206 5
            if (!empty($fstvar) && strpos($sndvar, $fstvar) !== false) {
207 2
                $packets[$i] = preg_replace("#(\\x00[^\\x00]+\\x00)$#", "\x00", $packets[$i]);
208
            }
209
        }
210
211
        // Now let's loop the return and remove any dupe prefixes
212 10
        for ($x = 1; $x < $packetCount; $x++) {
213 5
            $buffer = new Buffer($packets[$x], Buffer::NUMBER_TYPE_BIGENDIAN);
214
215 5
            $prefix = $buffer->readString();
216
217
            // Check to see if the return before has the same prefix present
218 5
            if ($prefix != null && strstr($packets[($x - 1)], $prefix)) {
219
                // Update the return by removing the prefix plus 2 chars
220 2
                $packets[$x] = substr(str_replace($prefix, '', $packets[$x]), 2);
221
            }
222
223 5
            unset($buffer);
224
        }
225
226 10
        unset($x, $i, $snd, $sndvar, $fst, $fstvar);
227
228
        // Return cleaned packets
229 10
        return $packets;
230
    }
231
232
    /**
233
     * Handles processing the details data into a usable format
234
     *
235
     * @param \GameQ\Buffer $buffer
236
     * @param \GameQ\Result $result
237
     */
238 10
    protected function processDetails(Buffer &$buffer, Result &$result)
239
    {
240
241
        // We go until we hit an empty key
242 10
        while ($buffer->getLength()) {
243 10
            $key = $buffer->readString();
244 10
            if (strlen($key) == 0) {
245 10
                break;
246
            }
247 10
            $result->add($key, utf8_encode($buffer->readString()));
248
        }
249 10
    }
250
251
    /**
252
     * Handles processing the player and team data into a usable format
253
     *
254
     * @param \GameQ\Buffer $buffer
255
     * @param \GameQ\Result $result
256
     */
257 10
    protected function processPlayersAndTeams(Buffer &$buffer, Result &$result)
258
    {
259
260
        /*
261
         * Explode the data into groups. First is player, next is team (item_t)
262
         * Each group should be as follows:
263
         *
264
         * [0] => item_
265
         * [1] => information for item_
266
         * ...
267
         */
268 10
        $data = explode("\x00\x00", $buffer->getBuffer());
269
270
        // By default item_group is blank, this will be set for each loop thru the data
271 10
        $item_group = '';
272
        // By default the item_type is blank, this will be set on each loop
273 10
        $item_type = '';
274
        // Loop through all of the $data for information and pull it out into the result
275 10
        for ($x = 0; $x < count($data) - 1; $x++) {
276
            // Pull out the item
277 10
            $item = $data[$x];
278
            // If this is an empty item, move on
279 10
            if ($item == '' || $item == "\x00") {
280 2
                continue;
281
            }
282
            /*
283
            * Left as reference:
284
            *
285
            * Each block of player_ and team_t have preceding junk chars
286
            *
287
            * player_ is actually \x01player_
288
            * team_t is actually \x00\x02team_t
289
            *
290
            * Probably a by-product of the change to exploding the data from the original.
291
            *
292
            * For now we just strip out these characters
293
            */
294
            // Check to see if $item has a _ at the end, this is player info
295 10
            if (substr($item, -1) == '_') {
296
                // Set the item group
297 10
                $item_group = 'players';
298
                // Set the item type, rip off any trailing stuff and bad chars
299 10
                $item_type = rtrim(str_replace("\x01", '', $item), '_');
300 9
            } elseif (substr($item, -2) == '_t') {
301
                // Check to see if $item has a _t at the end, this is team info
302
                // Set the item group
303 7
                $item_group = 'teams';
304
                // Set the item type, rip off any trailing stuff and bad chars
305 7
                $item_type = rtrim(str_replace(["\x00", "\x02"], '', $item), '_t');
306
            } else {
307
                // We can assume it is data belonging to a previously defined item
308
309
                // Make a temp buffer so we have easier access to the data
310 9
                $buf_temp = new Buffer($item, Buffer::NUMBER_TYPE_BIGENDIAN);
311
                // Get the values
312 9
                while ($buf_temp->getLength()) {
313
                    // No value so break the loop, end of string
314 9
                    if (($val = $buf_temp->readString()) === '') {
315
                        break;
316
                    }
317
                    // Add the value to the proper item in the correct group
318 9
                    $result->addSub($item_group, $item_type, utf8_encode(trim($val)));
319
                }
320
                // Unset our buffer
321 9
                unset($buf_temp);
322
            }
323
        }
324
        // Free up some memory
325 10
        unset($data, $item, $item_group, $item_type, $val);
326 10
    }
327
}
328