1 | <?php |
||
2 | |||
3 | /* |
||
4 | * SPDX-License-Identifier: AGPL-3.0-only |
||
5 | * SPDX-FileCopyrightText: Copyright 2007-2016 Zarafa Deutschland GmbH |
||
6 | * SPDX-FileCopyrightText: Copyright 2020-2024 grommunio GmbH |
||
7 | * |
||
8 | * This is the entry point through which all requests are processed. |
||
9 | */ |
||
10 | |||
11 | ob_start(null, 1048576); |
||
12 | |||
13 | // ignore user abortions because this can lead to weird errors |
||
14 | ignore_user_abort(true); |
||
15 | |||
16 | require_once 'vendor/autoload.php'; |
||
17 | |||
18 | if (!defined('GSYNC_CONFIG')) { |
||
19 | define('GSYNC_CONFIG', 'config.php'); |
||
20 | } |
||
21 | |||
22 | include_once GSYNC_CONFIG; |
||
23 | |||
24 | // Attempt to set maximum execution time |
||
25 | ini_set('max_execution_time', SCRIPT_TIMEOUT); |
||
26 | set_time_limit(SCRIPT_TIMEOUT); |
||
27 | |||
28 | try { |
||
29 | // check config & initialize the basics |
||
30 | GSync::CheckConfig(); |
||
31 | Request::Initialize(); |
||
32 | SLog::Initialize(); |
||
33 | |||
34 | SLog::Write(LOGLEVEL_DEBUG, "-------- Start"); |
||
35 | SLog::Write( |
||
36 | LOGLEVEL_DEBUG, |
||
37 | sprintf( |
||
38 | "cmd='%s' devType='%s' devId='%s' getUser='%s' from='%s' version='%s' method='%s'", |
||
39 | Request::GetCommand(), |
||
40 | Request::GetDeviceType(), |
||
41 | Request::GetDeviceID(), |
||
42 | Request::GetGETUser(), |
||
43 | Request::GetRemoteAddr(), |
||
44 | @constant('GROMMUNIOSYNC_VERSION'), |
||
45 | Request::GetMethod() |
||
46 | ) |
||
47 | ); |
||
48 | |||
49 | // always request the authorization header |
||
50 | if (!Request::HasAuthenticationInfo() || !Request::GetGETUser()) { |
||
51 | throw new AuthenticationRequiredException("Access denied. Please send authorisation information"); |
||
52 | } |
||
53 | |||
54 | GSync::CheckAdvancedConfig(); |
||
55 | |||
56 | // Process request headers and look for AS headers |
||
57 | Request::ProcessHeaders(); |
||
58 | |||
59 | // Stop here if this is an OPTIONS request |
||
60 | if (Request::IsMethodOPTIONS()) { |
||
61 | RequestProcessor::Authenticate(); |
||
62 | |||
63 | throw new NoPostRequestException("Options request", NoPostRequestException::OPTIONS_REQUEST); |
||
64 | } |
||
65 | |||
66 | // Check required GET parameters |
||
67 | if (Request::IsMethodPOST() && (Request::GetCommandCode() === false || !Request::GetDeviceID() || !Request::GetDeviceType())) { |
||
68 | throw new FatalException("Requested the grommunio-sync URL without the required GET parameters"); |
||
69 | } |
||
70 | |||
71 | // Load the backend |
||
72 | $backend = GSync::GetBackend(); |
||
73 | |||
74 | // check the provisioning information |
||
75 | if ( |
||
76 | PROVISIONING === true && |
||
77 | Request::IsMethodPOST() && |
||
78 | GSync::CommandNeedsProvisioning(Request::GetCommandCode()) && |
||
79 | ( |
||
80 | (Request::WasPolicyKeySent() && Request::GetPolicyKey() == 0) || |
||
81 | GSync::GetProvisioningManager()->ProvisioningRequired(Request::GetPolicyKey()) |
||
82 | ) && ( |
||
83 | LOOSE_PROVISIONING === false || |
||
84 | (LOOSE_PROVISIONING === true && Request::WasPolicyKeySent()) |
||
85 | )) { |
||
86 | // TODO for AS 14 send a wbxml response |
||
87 | throw new ProvisioningRequiredException(); |
||
88 | } |
||
89 | |||
90 | // most commands require an authenticated user |
||
91 | if (GSync::CommandNeedsAuthentication(Request::GetCommandCode())) { |
||
92 | RequestProcessor::Authenticate(); |
||
93 | } |
||
94 | |||
95 | // Do the actual processing of the request |
||
96 | if (Request::IsMethodGET()) { |
||
97 | throw new NoPostRequestException("This is the grommunio-sync location and can only be accessed by Microsoft ActiveSync-capable devices", NoPostRequestException::GET_REQUEST); |
||
98 | } |
||
99 | |||
100 | // Do the actual request |
||
101 | header(GSync::GetServerHeader()); |
||
102 | |||
103 | if (RequestProcessor::isUserAuthenticated()) { |
||
104 | header("X-Grommunio-Sync-Version: " . @constant('GROMMUNIOSYNC_VERSION')); |
||
105 | |||
106 | // announce the supported AS versions (if not already sent to device) |
||
107 | if (GSync::GetDeviceManager()->AnnounceASVersion()) { |
||
108 | $versions = GSync::GetSupportedProtocolVersions(true); |
||
109 | SLog::Write(LOGLEVEL_INFO, sprintf("Announcing latest AS version to device: %s", $versions)); |
||
110 | header("X-MS-RP: " . $versions); |
||
111 | } |
||
112 | } |
||
113 | |||
114 | RequestProcessor::Initialize(); |
||
115 | RequestProcessor::HandleRequest(); |
||
116 | |||
117 | // eventually the RequestProcessor wants to send other headers to the mobile |
||
118 | foreach (RequestProcessor::GetSpecialHeaders() as $header) { |
||
119 | SLog::Write(LOGLEVEL_DEBUG, sprintf("Special header: %s", $header)); |
||
120 | header($header); |
||
121 | } |
||
122 | |||
123 | // stream the data |
||
124 | $len = ob_get_length(); |
||
125 | $data = ob_get_contents(); |
||
126 | ob_end_clean(); |
||
127 | |||
128 | // log amount of data transferred |
||
129 | // TODO check $len when streaming more data (e.g. Attachments), as the data will be send chunked |
||
130 | if (GSync::GetDeviceManager(false)) { |
||
131 | GSync::GetDeviceManager()->SentData($len); |
||
132 | } |
||
133 | |||
134 | // Unfortunately, even though grommunio-sync can stream the data to the client |
||
135 | // with a chunked encoding, using chunked encoding breaks the progress bar |
||
136 | // on the PDA. So the data is de-chunk here, written a content-length header and |
||
137 | // data send as a 'normal' packet. If the output packet exceeds 1MB (see ob_start) |
||
138 | // then it will be sent as a chunked packet anyway because PHP will have to flush |
||
139 | // the buffer. |
||
140 | if (!headers_sent()) { |
||
141 | header("Content-Length: {$len}"); |
||
142 | } |
||
143 | |||
144 | // send vnd.ms-sync.wbxml content type header if there is no content |
||
145 | // otherwise text/html content type is added which might break some devices |
||
146 | if (!headers_sent() && $len == 0) { |
||
147 | header("Content-Type: application/vnd.ms-sync.wbxml"); |
||
148 | } |
||
149 | |||
150 | echo $data; |
||
151 | |||
152 | // destruct backend after all data is on the stream |
||
153 | $backend->Logoff(); |
||
154 | } |
||
155 | catch (NoPostRequestException $nopostex) { |
||
156 | if ($nopostex->getCode() == NoPostRequestException::OPTIONS_REQUEST) { |
||
157 | header(GSync::GetServerHeader()); |
||
158 | header(GSync::GetSupportedProtocolVersions()); |
||
159 | header(GSync::GetSupportedCommands()); |
||
160 | header("X-AspNet-Version: 4.0.30319"); |
||
161 | SLog::Write(LOGLEVEL_INFO, $nopostex->getMessage()); |
||
162 | } |
||
163 | elseif ($nopostex->getCode() == NoPostRequestException::GET_REQUEST) { |
||
164 | if (Request::GetUserAgent()) { |
||
165 | SLog::Write(LOGLEVEL_INFO, sprintf("User-agent: '%s'", Request::GetUserAgent())); |
||
166 | } |
||
167 | if (!headers_sent() && $nopostex->showLegalNotice()) { |
||
168 | GSync::PrintGrommunioSyncLegal('GET not supported', $nopostex->getMessage()); |
||
169 | } |
||
170 | } |
||
171 | } |
||
172 | catch (Exception $ex) { |
||
173 | // Extract any previous exception message for logging purpose. |
||
174 | $exclass = $ex::class; |
||
175 | $exception_message = $ex->getMessage(); |
||
176 | if ($ex->getPrevious()) { |
||
177 | do { |
||
178 | $current_exception = $ex->getPrevious(); |
||
179 | $exception_message .= ' -> ' . $current_exception->getMessage(); |
||
180 | } |
||
181 | while ($current_exception->getPrevious()); |
||
182 | } |
||
183 | |||
184 | if (Request::GetUserAgent()) { |
||
185 | SLog::Write(LOGLEVEL_INFO, sprintf("User-agent: '%s'", Request::GetUserAgent())); |
||
186 | } |
||
187 | |||
188 | SLog::Write(LOGLEVEL_FATAL, sprintf('Exception: (%s) - %s', $exclass, $exception_message)); |
||
189 | |||
190 | if (!headers_sent()) { |
||
191 | if ($ex instanceof GSyncException) { |
||
192 | header('HTTP/1.1 ' . $ex->getHTTPCodeString()); |
||
193 | foreach ($ex->getHTTPHeaders() as $h) { |
||
194 | header($h); |
||
195 | } |
||
196 | } |
||
197 | // something really unexpected happened! |
||
198 | else { |
||
199 | header('HTTP/1.1 500 Internal Server Error'); |
||
200 | } |
||
201 | } |
||
202 | |||
203 | if ($ex instanceof AuthenticationRequiredException) { |
||
204 | // Only print GSync legal message for GET requests because |
||
205 | // some devices send unauthorized OPTIONS requests |
||
206 | // and don't expect anything in the response body |
||
207 | if (Request::IsMethodGET()) { |
||
208 | GSync::PrintGrommunioSyncLegal($exclass, sprintf('<pre>%s</pre>', $ex->getMessage())); |
||
209 | } |
||
210 | |||
211 | // log the failed login attempt e.g. for fail2ban |
||
212 | if (defined('LOGAUTHFAIL') && LOGAUTHFAIL !== false) { |
||
0 ignored issues
–
show
introduced
by
![]() |
|||
213 | SLog::Write(LOGLEVEL_WARN, sprintf("IP: %s failed to authenticate user '%s'", Request::GetRemoteAddr(), Request::GetAuthUser() ?: Request::GetGETUser())); |
||
214 | } |
||
215 | } |
||
216 | |||
217 | // This could be a WBXML problem.. try to get the complete request |
||
218 | elseif ($ex instanceof WBXMLException) { |
||
219 | SLog::Write(LOGLEVEL_FATAL, "Request could not be processed correctly due to a WBXMLException. Please report this including the 'WBXML debug data' logged. Be aware that the debug data could contain confidential information."); |
||
220 | } |
||
221 | |||
222 | // Try to output some kind of error information. This is only possible if |
||
223 | // the output had not started yet. If it has started already, we can't show the user the error, and |
||
224 | // the device will give its own (useless) error message. |
||
225 | elseif (!($ex instanceof GSyncException) || $ex->showLegalNotice()) { |
||
226 | $cmdinfo = (Request::GetCommand()) ? sprintf(" processing command <i>%s</i>", Request::GetCommand()) : ""; |
||
227 | $extrace = $ex->getTrace(); |
||
228 | $trace = (!empty($extrace)) ? "\n\nTrace:\n" . print_r($extrace, 1) : ""; |
||
229 | GSync::PrintGrommunioSyncLegal($exclass . $cmdinfo, sprintf('<pre>%s</pre>', $ex->getMessage() . $trace)); |
||
230 | } |
||
231 | |||
232 | // Announce exception to process loop detection |
||
233 | if (GSync::GetDeviceManager(false)) { |
||
234 | GSync::GetDeviceManager()->AnnounceProcessException($ex); |
||
235 | } |
||
236 | |||
237 | // Announce exception if the TopCollector if available |
||
238 | GSync::GetTopCollector()->AnnounceInformation($ex::class, true); |
||
239 | } |
||
240 | |||
241 | // save device data if the DeviceManager is available |
||
242 | if (GSync::GetDeviceManager(false)) { |
||
243 | GSync::GetDeviceManager()->Save(); |
||
244 | } |
||
245 | |||
246 | // end gracefully |
||
247 | SLog::Write( |
||
248 | LOGLEVEL_INFO, |
||
249 | sprintf( |
||
250 | "cmd='%s' memory='%s/%s' time='%ss' devType='%s' devId='%s' getUser='%s' from='%s' idle='%ss' version='%s' method='%s' httpcode='%s'", |
||
251 | Request::GetCommand(), |
||
252 | Utils::FormatBytes(memory_get_peak_usage(false)), |
||
253 | Utils::FormatBytes(memory_get_peak_usage(true)), |
||
254 | number_format(microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"], 2), |
||
255 | Request::GetDeviceType(), |
||
256 | Request::GetDeviceID(), |
||
257 | Request::GetGETUser(), |
||
258 | Request::GetRemoteAddr(), |
||
259 | RequestProcessor::GetWaitTime(), |
||
260 | @constant('GROMMUNIOSYNC_VERSION'), |
||
261 | Request::GetMethod(), |
||
262 | http_response_code() |
||
263 | ) |
||
264 | ); |
||
265 | |||
266 | SLog::Write(LOGLEVEL_DEBUG, "-------- End"); |
||
267 |