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.

NodeRepository::delete()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 18
rs 9.4285
cc 2
eloc 8
nc 2
nop 1
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
            'behind_proxy' => 'required|boolean',
56
            'memory' => 'required|numeric|min:1',
57
            'memory_overallocate' => 'required|numeric|min:-1',
58
            'disk' => 'required|numeric|min:1',
59
            'disk_overallocate' => 'required|numeric|min:-1',
60
            'daemonBase' => 'required|regex:/^([\/][\d\w.\-\/]+)$/',
61
            'daemonSFTP' => 'required|numeric|between:1,65535',
62
            'daemonListen' => 'required|numeric|between:1,65535',
63
        ]);
64
65
        // Run validator, throw catchable and displayable exception if it fails.
66
        // Exception includes a JSON result of failed validation rules.
67
        if ($validator->fails()) {
68
            throw new DisplayValidationException(json_encode($validator->errors()));
69
        }
70
71
        // Verify the FQDN if using SSL
72
        if (filter_var($data['fqdn'], FILTER_VALIDATE_IP) && $data['scheme'] === 'https') {
73
            throw new DisplayException('A fully qualified domain name is required to use a secure comunication method on this node.');
74
        }
75
76
        // Verify FQDN is resolvable, or if not using SSL that the IP is valid.
77
        if (! filter_var(gethostbyname($data['fqdn']), FILTER_VALIDATE_IP)) {
78
            throw new DisplayException('The FQDN (or IP Address) provided does not resolve to a valid IP address.');
79
        }
80
81
        // Should we be nulling the overallocations?
82
        $data['memory_overallocate'] = ($data['memory_overallocate'] < 0) ? null : $data['memory_overallocate'];
83
        $data['disk_overallocate'] = ($data['disk_overallocate'] < 0) ? null : $data['disk_overallocate'];
84
85
        // Set the Secret
86
        $uuid = new UuidService;
87
        $data['daemonSecret'] = (string) $uuid->generate('nodes', 'daemonSecret');
88
89
        return Models\Node::create($data);
90
    }
91
92
    /**
93
     * Updates a node on the system.
94
     *
95
     * @param  int    $id
96
     * @param  array  $data
97
     * @return \Pterodactyl\Models\Node
98
     *
99
     * @throws \Pterodactyl\Exceptions\DisplayException
100
     * @throws \Pterodactyl\Exceptions\DisplayValidationException
101
     */
102
    public function update($id, array $data)
103
    {
104
        $node = Models\Node::findOrFail($id);
105
106
        // Validate Fields
107
        $validator = $validator = Validator::make($data, [
108
            'name' => 'regex:/^([\w .-]{1,100})$/',
109
            'location_id' => 'numeric|min:1|exists:locations,id',
110
            'public' => 'numeric|between:0,1',
111
            'fqdn' => 'string|unique:nodes,fqdn,' . $id,
112
            'scheme' => 'regex:/^(http(s)?)$/',
113
            'behind_proxy' => 'boolean',
114
            'memory' => 'numeric|min:1',
115
            'memory_overallocate' => 'numeric|min:-1',
116
            'disk' => 'numeric|min:1',
117
            'disk_overallocate' => 'numeric|min:-1',
118
            'upload_size' => 'numeric|min:0',
119
            'daemonBase' => 'sometimes|regex:/^([\/][\d\w.\-\/]+)$/',
120
            'daemonSFTP' => 'numeric|between:1,65535',
121
            'daemonListen' => 'numeric|between:1,65535',
122
            'reset_secret' => 'sometimes|nullable|accepted',
123
        ]);
124
125
        // Run validator, throw catchable and displayable exception if it fails.
126
        // Exception includes a JSON result of failed validation rules.
127
        if ($validator->fails()) {
128
            throw new DisplayValidationException(json_encode($validator->errors()));
129
        }
130
131
        // Verify the FQDN
132
        if (isset($data['fqdn'])) {
133
134
            // Verify the FQDN if using SSL
135
            if ((isset($data['scheme']) && $data['scheme'] === 'https') || (! isset($data['scheme']) && $node->scheme === 'https')) {
136
                if (filter_var($data['fqdn'], FILTER_VALIDATE_IP)) {
137
                    throw new DisplayException('A fully qualified domain name is required to use secure comunication on this node.');
138
                }
139
            }
140
141
            // Verify FQDN is resolvable, or if not using SSL that the IP is valid.
142
            if (! filter_var(gethostbyname($data['fqdn']), FILTER_VALIDATE_IP)) {
143
                throw new DisplayException('The FQDN (or IP Address) provided does not resolve to a valid IP address.');
144
            }
145
        }
146
147
        // Should we be nulling the overallocations?
148
        if (isset($data['memory_overallocate'])) {
149
            $data['memory_overallocate'] = ($data['memory_overallocate'] < 0) ? null : $data['memory_overallocate'];
150
        }
151
152
        if (isset($data['disk_overallocate'])) {
153
            $data['disk_overallocate'] = ($data['disk_overallocate'] < 0) ? null : $data['disk_overallocate'];
154
        }
155
156
        // Set the Secret
157
        if (isset($data['reset_secret']) && ! is_null($data['reset_secret'])) {
158
            $uuid = new UuidService;
159
            $data['daemonSecret'] = (string) $uuid->generate('nodes', 'daemonSecret');
160
            unset($data['reset_secret']);
161
        }
162
163
        $oldDaemonKey = $node->daemonSecret;
164
        $node->update($data);
165
        try {
166
            $node->guzzleClient(['X-Access-Token' => $oldDaemonKey])->request('PATCH', '/config', [
167
                'json' => [
168
                    'web' => [
169
                        'listen' => $node->daemonListen,
170
                        'ssl' => [
171
                            'enabled' => (! $node->behind_proxy && $node->scheme === 'https'),
172
                        ],
173
                    ],
174
                    'sftp' => [
175
                        'path' => $node->daemonBase,
176
                        'port' => $node->daemonSFTP,
177
                    ],
178
                    'remote' => [
179
                        'base' => config('app.url'),
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([
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([
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 Node
288
            $node->delete();
289
        });
290
    }
291
}
292