GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — develop ( da003e...910697 )
by Dane
02:54
created

NodeRepository::addAllocations()   C

Complexity

Conditions 15
Paths 4

Size

Total Lines 60
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 60
rs 6.305
c 0
b 0
f 0
cc 15
eloc 35
nc 4
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Pterodactyl - Panel
4
 * Copyright (c) 2015 - 2017 Dane Everitt <[email protected]>.
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in all
14
 * copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
 * SOFTWARE.
23
 */
24
25
namespace Pterodactyl\Repositories;
26
27
use DB;
28
use Validator;
29
use IPTools\Network;
30
use Pterodactyl\Models;
31
use Pterodactyl\Services\UuidService;
32
use Pterodactyl\Exceptions\DisplayException;
33
use Pterodactyl\Exceptions\DisplayValidationException;
34
35
class NodeRepository
36
{
37
    /**
38
     * Creates a new node on the system.
39
     *
40
     * @param  array  $data
41
     * @return \Pterodactyl\Models\Node
42
     *
43
     * @throws \Pterodactyl\Exceptions\DisplayException
44
     * @throws \Pterodactyl\Exceptions\DisplayValidationException
45
     */
46
    public function create(array $data)
47
    {
48
        // Validate Fields
49
        $validator = Validator::make($data, [
50
            'name' => 'required|regex:/^([\w .-]{1,100})$/',
51
            'location_id' => 'required|numeric|min:1|exists:locations,id',
52
            'public' => 'required|numeric|between:0,1',
53
            'fqdn' => 'required|string|unique:nodes,fqdn',
54
            'scheme' => 'required|regex:/^(http(s)?)$/',
55
            'memory' => 'required|numeric|min:1',
56
            'memory_overallocate' => 'required|numeric|min:-1',
57
            'disk' => 'required|numeric|min:1',
58
            'disk_overallocate' => 'required|numeric|min:-1',
59
            'daemonBase' => 'required|regex:/^([\/][\d\w.\-\/]+)$/',
60
            'daemonSFTP' => 'required|numeric|between:1,65535',
61
            'daemonListen' => 'required|numeric|between:1,65535',
62
        ]);
63
64
        // Run validator, throw catchable and displayable exception if it fails.
65
        // Exception includes a JSON result of failed validation rules.
66
        if ($validator->fails()) {
67
            throw new DisplayValidationException(json_encode($validator->errors()));
68
        }
69
70
        // Verify the FQDN if using SSL
71
        if (filter_var($data['fqdn'], FILTER_VALIDATE_IP) && $data['scheme'] === 'https') {
72
            throw new DisplayException('A fully qualified domain name is required to use a secure comunication method on this node.');
73
        }
74
75
        // Verify FQDN is resolvable, or if not using SSL that the IP is valid.
76
        if (! filter_var(gethostbyname($data['fqdn']), FILTER_VALIDATE_IP)) {
77
            throw new DisplayException('The FQDN (or IP Address) provided does not resolve to a valid IP address.');
78
        }
79
80
        // Should we be nulling the overallocations?
81
        $data['memory_overallocate'] = ($data['memory_overallocate'] < 0) ? null : $data['memory_overallocate'];
82
        $data['disk_overallocate'] = ($data['disk_overallocate'] < 0) ? null : $data['disk_overallocate'];
83
84
        // Set the Secret
85
        $uuid = new UuidService;
86
        $data['daemonSecret'] = (string) $uuid->generate('nodes', 'daemonSecret');
87
88
        return Models\Node::create($data);
89
    }
90
91
    /**
92
     * Updates a node on the system.
93
     *
94
     * @param  int    $id
95
     * @param  array  $data
96
     * @return \Pterodactyl\Models\Node
97
     *
98
     * @throws \Pterodactyl\Exceptions\DisplayException
99
     * @throws \Pterodactyl\Exceptions\DisplayValidationException
100
     */
101
    public function update($id, array $data)
102
    {
103
        $node = Models\Node::findOrFail($id);
104
105
        // Validate Fields
106
        $validator = $validator = Validator::make($data, [
107
            'name' => 'regex:/^([\w .-]{1,100})$/',
108
            'location_id' => 'numeric|min:1|exists:locations,id',
109
            'public' => 'numeric|between:0,1',
110
            'fqdn' => 'string|unique:nodes,fqdn,' . $id,
111
            'scheme' => 'regex:/^(http(s)?)$/',
112
            'memory' => 'numeric|min:1',
113
            'memory_overallocate' => 'numeric|min:-1',
114
            'disk' => 'numeric|min:1',
115
            'disk_overallocate' => 'numeric|min:-1',
116
            'upload_size' => 'numeric|min:0',
117
            'daemonBase' => 'sometimes|regex:/^([\/][\d\w.\-\/]+)$/',
118
            'daemonSFTP' => 'numeric|between:1,65535',
119
            'daemonListen' => 'numeric|between:1,65535',
120
            'reset_secret' => 'sometimes|nullable|accepted',
121
        ]);
122
123
        // Run validator, throw catchable and displayable exception if it fails.
124
        // Exception includes a JSON result of failed validation rules.
125
        if ($validator->fails()) {
126
            throw new DisplayValidationException(json_encode($validator->errors()));
127
        }
128
129
        // Verify the FQDN
130
        if (isset($data['fqdn'])) {
131
132
            // Verify the FQDN if using SSL
133
            if ((isset($data['scheme']) && $data['scheme'] === 'https') || (! isset($data['scheme']) && $node->scheme === 'https')) {
134
                if (filter_var($data['fqdn'], FILTER_VALIDATE_IP)) {
135
                    throw new DisplayException('A fully qualified domain name is required to use secure comunication on this node.');
136
                }
137
            }
138
139
            // Verify FQDN is resolvable, or if not using SSL that the IP is valid.
140
            if (! filter_var(gethostbyname($data['fqdn']), FILTER_VALIDATE_IP)) {
141
                throw new DisplayException('The FQDN (or IP Address) provided does not resolve to a valid IP address.');
142
            }
143
        }
144
145
        // Should we be nulling the overallocations?
146
        if (isset($data['memory_overallocate'])) {
147
            $data['memory_overallocate'] = ($data['memory_overallocate'] < 0) ? null : $data['memory_overallocate'];
148
        }
149
150
        if (isset($data['disk_overallocate'])) {
151
            $data['disk_overallocate'] = ($data['disk_overallocate'] < 0) ? null : $data['disk_overallocate'];
152
        }
153
154
        // Set the Secret
155
        if (isset($data['reset_secret']) && ! is_null($data['reset_secret'])) {
156
            $uuid = new UuidService;
157
            $data['daemonSecret'] = (string) $uuid->generate('nodes', 'daemonSecret');
158
            unset($data['reset_secret']);
159
        }
160
161
        $oldDaemonKey = $node->daemonSecret;
162
        $node->update($data);
163
        try {
164
            $node->guzzleClient(['X-Access-Token' => $oldDaemonKey])->request('PATCH', '/config', [
165
                'json' => [
166
                    'web' => [
167
                        'listen' => $node->daemonListen,
168
                        'ssl' => [
169
                            'enabled' => ($node->scheme === 'https'),
170
                        ],
171
                    ],
172
                    'sftp' => [
173
                        'path' => $node->daemonBase,
174
                        'port' => $node->daemonSFTP,
175
                    ],
176
                    'remote' => [
177
                        'base' => config('app.url'),
178
                        'download' => route('remote.download'),
179
                        'installed' => route('remote.install'),
180
                    ],
181
                    'uploads' => [
182
                        'size_limit' => $node->upload_size,
183
                    ],
184
                    'keys' => [
185
                        $node->daemonSecret,
186
                    ],
187
                ],
188
            ]);
189
        } catch (\Exception $ex) {
190
            throw new DisplayException('Failed to update the node configuration, however your changes have been saved to the database. You will need to manually update the configuration file for the node to apply these changes.');
191
        }
192
    }
193
194
    /**
195
     * Adds allocations to a provided node.
196
     *
197
     * @param  int    $id
198
     * @param  array  $data
199
     * @return void
200
     *
201
     * @throws \Pterodactyl\Exceptions\DisplayException
202
     * @throws \Pterodactyl\Exceptions\DisplayValidationException
203
     */
204
    public function addAllocations($id, array $data)
205
    {
206
        $node = Models\Node::findOrFail($id);
207
208
        $validator = Validator::make($data, [
209
            'allocation_ip' => 'required|string',
210
            'allocation_alias' => 'sometimes|required|string|max:255',
211
            'allocation_ports' => 'required|array',
212
        ]);
213
214
        if ($validator->fails()) {
215
            throw new DisplayValidationException(json_encode($validator->errors()));
216
        }
217
218
        $explode = explode('/', $data['allocation_ip']);
219
        if (count($explode) !== 1) {
220
            if (! ctype_digit($explode[1]) || ($explode[1] > 32 || $explode[1] < 25)) {
221
                throw new DisplayException('CIDR notation only allows masks between /32 and /25.');
222
            }
223
        }
224
225
        DB::transaction(function () use ($data, $node) {
226
            foreach (Network::parse(gethostbyname($data['allocation_ip'])) as $ip) {
227
                foreach ($data['allocation_ports'] as $port) {
228
                    // Determine if this is a valid single port, or a valid port range.
229
                    if (! ctype_digit($port) && ! preg_match('/^(\d{1,5})-(\d{1,5})$/', $port)) {
230
                        throw new DisplayException('The mapping for <code>' . $port . '</code> is invalid and cannot be processed.');
231
                    }
232
233
                    if (preg_match('/^(\d{1,5})-(\d{1,5})$/', $port, $matches)) {
234
                        $block = range($matches[1], $matches[2]);
235
236
                        if (count($block) > 1000) {
237
                            throw new DisplayException('Adding more than 1000 ports at once is not supported. Please use a smaller port range.');
238
                        }
239
240
                        foreach ($block as $unit) {
241
                            // Insert into Database
242
                            Models\Allocation::firstOrCreate([
0 ignored issues
show
Bug introduced by
The method firstOrCreate() does not exist on Pterodactyl\Models\Allocation. Did you maybe mean create()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
243
                                'node_id' => $node->id,
244
                                'ip' => $ip,
245
                                'port' => $unit,
246
                                'ip_alias' => isset($data['allocation_alias']) ? $data['allocation_alias'] : null,
247
                                'server_id' => null,
248
                            ]);
249
                        }
250
                    } else {
251
                        // Insert into Database
252
                        Models\Allocation::firstOrCreate([
0 ignored issues
show
Bug introduced by
The method firstOrCreate() does not exist on Pterodactyl\Models\Allocation. Did you maybe mean create()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
253
                            'node_id' => $node->id,
254
                            'ip' => $ip,
255
                            'port' => $port,
256
                            'ip_alias' => isset($data['allocation_alias']) ? $data['allocation_alias'] : null,
257
                            'server_id' => null,
258
                        ]);
259
                    }
260
                }
261
            }
262
        });
263
    }
264
265
    /**
266
     * Deletes a node on the system.
267
     *
268
     * @param  int  $id
269
     * @return void
270
     *
271
     * @throws \Pterodactyl\Exceptions\DisplayException
272
     */
273
    public function delete($id)
274
    {
275
        $node = Models\Node::withCount('servers')->findOrFail($id);
276
        if ($node->servers_count > 0) {
277
            throw new DisplayException('You cannot delete a node with servers currently attached to it.');
278
        }
279
280
        DB::transaction(function () use ($node) {
281
            // Unlink Database Servers
282
            Models\DatabaseHost::where('node_id', $node->id)->update(['node_id' => null]);
283
284
            // Delete Allocations
285
            Models\Allocation::where('node_id', $node->id)->delete();
286
287
            // Delete configure tokens
288
            Models\NodeConfigurationToken::where('node_id', $node->id)->delete();
289
290
            // Delete Node
291
            $node->delete();
292
        });
293
    }
294
}
295