16
16
17
17
18
18
#include <ctype.h>
19
+ #include <stdlib.h>
19
20
#include <string.h>
20
21
#include <sys/types.h>
22
+ #include <math.h>
21
23
22
24
#include "mongoc-host-list.h"
23
25
#include "mongoc-host-list-private.h"
@@ -203,6 +205,23 @@ mongoc_uri_parse_userpass (mongoc_uri_t *uri,
203
205
return ret ;
204
206
}
205
207
208
+ static bool
209
+ mongoc_uri_parse_port (uint16_t * port ,
210
+ const char * str )
211
+ {
212
+ unsigned long ul_port ;
213
+
214
+ ul_port = strtoul (str , NULL , 10 );
215
+
216
+ if (ul_port == 0 || ul_port > UINT16_MAX ) {
217
+ /* Parse error or port number out of range. mongod prohibits port 0. */
218
+ return false;
219
+ }
220
+
221
+ * port = (uint16_t )ul_port ;
222
+ return true;
223
+ }
224
+
206
225
207
226
static bool
208
227
mongoc_uri_parse_host6 (mongoc_uri_t * uri ,
@@ -214,11 +233,9 @@ mongoc_uri_parse_host6 (mongoc_uri_t *uri,
214
233
char * hostname ;
215
234
216
235
if ((portstr = strrchr (str , ':' )) && !strstr (portstr , "]" )) {
217
- #ifdef _MSC_VER
218
- sscanf_s (portstr , ":%hu" , & port );
219
- #else
220
- sscanf (portstr , ":%hu" , & port );
221
- #endif
236
+ if (!mongoc_uri_parse_port (& port , portstr + 1 )) {
237
+ return false;
238
+ }
222
239
}
223
240
224
241
hostname = scan_to_unichar (str + 1 , ']' , "" , & end_host );
@@ -245,15 +262,10 @@ mongoc_uri_parse_host (mongoc_uri_t *uri,
245
262
246
263
if ((hostname = scan_to_unichar (str , ':' , "?/," , & end_host ))) {
247
264
end_host ++ ;
248
- if (!isdigit ( * end_host )) {
249
- bson_free (hostname );
265
+ if (!mongoc_uri_parse_port ( & port , end_host )) {
266
+ bson_free (hostname );
250
267
return false;
251
268
}
252
- #ifdef _MSC_VER
253
- sscanf_s (end_host , "%hu" , & port );
254
- #else
255
- sscanf (end_host , "%hu" , & port );
256
- #endif
257
269
} else {
258
270
hostname = bson_strdup (str );
259
271
port = MONGOC_DEFAULT_PORT ;
0 commit comments