Line data Source code
1 : /* FreeTDS - Library of routines accessing Sybase and Microsoft databases
2 : * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 Brian Bruns
3 : * Copyright (C) 2005-2015 Ziglio Frediano
4 : *
5 : * This library is free software; you can redistribute it and/or
6 : * modify it under the terms of the GNU Library General Public
7 : * License as published by the Free Software Foundation; either
8 : * version 2 of the License, or (at your option) any later version.
9 : *
10 : * This library 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 GNU
13 : * Library General Public License for more details.
14 : *
15 : * You should have received a copy of the GNU Library General Public
16 : * License along with this library; if not, write to the
17 : * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 : * Boston, MA 02111-1307, USA.
19 : */
20 :
21 : #include <config.h>
22 :
23 : #include <stdarg.h>
24 : #include <stdio.h>
25 :
26 : #if HAVE_STDLIB_H
27 : #include <stdlib.h>
28 : #endif /* HAVE_STDLIB_H */
29 :
30 : #include <assert.h>
31 :
32 : #if HAVE_STRING_H
33 : #include <string.h>
34 : #endif /* HAVE_STRING_H */
35 :
36 : #if HAVE_UNISTD_H
37 : #include <unistd.h>
38 : #endif /* HAVE_UNISTD_H */
39 :
40 : #if HAVE_SYS_SOCKET_H
41 : #include <sys/socket.h>
42 : #endif /* HAVE_SYS_SOCKET_H */
43 :
44 : #ifdef _WIN32
45 : #include <process.h>
46 : #endif
47 :
48 : #include <freetds/tds.h>
49 : #include <freetds/tds/iconv.h>
50 : #include <freetds/utils/string.h>
51 : #include <freetds/bytes.h>
52 : #include <freetds/tds/tls.h>
53 : #include <freetds/tds/stream.h>
54 : #include <freetds/tds/checks.h>
55 : #include <freetds/replacements.h>
56 :
57 : static TDSRET tds_send_login(TDSSOCKET * tds, const TDSLOGIN * login);
58 : static TDSRET tds71_do_login(TDSSOCKET * tds, TDSLOGIN * login);
59 : static TDSRET tds7_send_login(TDSSOCKET * tds, const TDSLOGIN * login);
60 : static void tds7_crypt_pass(const unsigned char *clear_pass,
61 : size_t len, unsigned char *crypt_pass);
62 :
63 : void
64 804 : tds_set_version(TDSLOGIN * tds_login, TDS_TINYINT major_ver, TDS_TINYINT minor_ver)
65 : {
66 804 : tds_login->tds_version = ((TDS_USMALLINT) major_ver << 8) + minor_ver;
67 804 : }
68 :
69 : void
70 0 : tds_set_packet(TDSLOGIN * tds_login, int packet_size)
71 : {
72 0 : tds_login->block_size = packet_size;
73 0 : }
74 :
75 : void
76 0 : tds_set_port(TDSLOGIN * tds_login, int port)
77 : {
78 0 : tds_login->port = port;
79 0 : }
80 :
81 : bool
82 2768 : tds_set_passwd(TDSLOGIN * tds_login, const char *password)
83 : {
84 2768 : if (password) {
85 2768 : tds_dstr_zero(&tds_login->password);
86 2768 : return !!tds_dstr_copy(&tds_login->password, password);
87 : }
88 : return true;
89 : }
90 : void
91 1440 : tds_set_bulk(TDSLOGIN * tds_login, bool enabled)
92 : {
93 1440 : tds_login->bulk_copy = enabled ? 1 : 0;
94 1440 : }
95 :
96 : bool
97 2768 : tds_set_user(TDSLOGIN * tds_login, const char *username)
98 : {
99 2768 : return !!tds_dstr_copy(&tds_login->user_name, username);
100 : }
101 :
102 : bool
103 584 : tds_set_host(TDSLOGIN * tds_login, const char *hostname)
104 : {
105 584 : return !!tds_dstr_copy(&tds_login->client_host_name, hostname);
106 : }
107 :
108 : bool
109 1398 : tds_set_app(TDSLOGIN * tds_login, const char *application)
110 : {
111 1398 : return !!tds_dstr_copy(&tds_login->app_name, application);
112 : }
113 :
114 : /**
115 : * \brief Set the servername in a TDSLOGIN structure
116 : *
117 : * Normally copies \a server into \a tds_login. If \a server does not point to a plausible name, the environment
118 : * variables TDSQUERY and DSQUERY are used, in that order. If they don't exist, the "default default" servername
119 : * is "SYBASE" (although the utility of that choice is a bit murky).
120 : *
121 : * \param tds_login points to a TDSLOGIN structure
122 : * \param server the servername, or NULL, or a zero-length string
123 : * \todo open the log file earlier, so these messages can be seen.
124 : */
125 : bool
126 2880 : tds_set_server(TDSLOGIN * tds_login, const char *server)
127 : {
128 : #if 0
129 : /* Doing this in tds_alloc_login instead */
130 : static const char *names[] = { "TDSQUERY", "DSQUERY", "SYBASE" };
131 : int i;
132 :
133 : for (i=0; i < TDS_VECTOR_SIZE(names) && (!server || strlen(server) == 0); i++) {
134 : const char *source;
135 : if (i + 1 == TDS_VECTOR_SIZE(names)) {
136 : server = names[i];
137 : source = "compiled-in default";
138 : } else {
139 : server = getenv(names[i]);
140 : source = names[i];
141 : }
142 : if (server) {
143 : tdsdump_log(TDS_DBG_INFO1, "Setting TDSLOGIN::server_name to '%s' from %s.\n", server, source);
144 : }
145 : }
146 : #endif
147 2880 : if (server)
148 2880 : return !!tds_dstr_copy(&tds_login->server_name, server);
149 : return true;
150 : }
151 :
152 : bool
153 2798 : tds_set_library(TDSLOGIN * tds_login, const char *library)
154 : {
155 2798 : return !!tds_dstr_copy(&tds_login->library, library);
156 : }
157 :
158 : bool
159 184 : tds_set_client_charset(TDSLOGIN * tds_login, const char *charset)
160 : {
161 184 : return !!tds_dstr_copy(&tds_login->client_charset, charset);
162 : }
163 :
164 : bool
165 526 : tds_set_language(TDSLOGIN * tds_login, const char *language)
166 : {
167 526 : return !!tds_dstr_copy(&tds_login->language, language);
168 : }
169 :
170 : struct tds_save_msg
171 : {
172 : TDSMESSAGE msg;
173 : char type;
174 : };
175 :
176 : struct tds_save_env
177 : {
178 : char *oldval;
179 : char *newval;
180 : int type;
181 : };
182 :
183 : typedef struct tds_save_context
184 : {
185 : /* must be first !!! */
186 : TDSCONTEXT ctx;
187 :
188 : unsigned num_msg;
189 : struct tds_save_msg msgs[10];
190 :
191 : unsigned num_env;
192 : struct tds_save_env envs[10];
193 : } TDSSAVECONTEXT;
194 :
195 : static void
196 6 : tds_save(TDSSAVECONTEXT *ctx, char type, TDSMESSAGE *msg)
197 : {
198 : struct tds_save_msg *dest_msg;
199 :
200 6 : if (ctx->num_msg >= TDS_VECTOR_SIZE(ctx->msgs))
201 : return;
202 :
203 6 : dest_msg = &ctx->msgs[ctx->num_msg];
204 6 : dest_msg->type = type;
205 6 : dest_msg->msg = *msg;
206 : #define COPY(name) if (msg->name) dest_msg->msg.name = strdup(msg->name);
207 6 : COPY(server);
208 : /* constant messages can be used as is */
209 6 : if (msg->message_allocated)
210 4 : COPY(message);
211 6 : COPY(proc_name);
212 6 : COPY(sql_state);
213 : #undef COPY
214 6 : ++ctx->num_msg;
215 : }
216 :
217 : static int
218 4 : tds_save_msg(const TDSCONTEXT *ctx, TDSSOCKET *tds TDS_UNUSED, TDSMESSAGE *msg)
219 : {
220 4 : tds_save((TDSSAVECONTEXT *) ctx, 0, msg);
221 4 : return 0;
222 : }
223 :
224 : static int
225 2 : tds_save_err(const TDSCONTEXT *ctx, TDSSOCKET *tds TDS_UNUSED, TDSMESSAGE *msg)
226 : {
227 2 : tds_save((TDSSAVECONTEXT *) ctx, 1, msg);
228 2 : return TDS_INT_CANCEL;
229 : }
230 :
231 : static void
232 6 : tds_save_env(TDSSOCKET * tds, int type, char *oldval, char *newval)
233 : {
234 : TDSSAVECONTEXT *ctx;
235 : struct tds_save_env *env;
236 :
237 6 : if (tds_get_ctx(tds)->msg_handler != tds_save_msg)
238 : return;
239 :
240 6 : ctx = (TDSSAVECONTEXT *) tds_get_ctx(tds);
241 6 : if (ctx->num_env >= TDS_VECTOR_SIZE(ctx->envs))
242 : return;
243 :
244 6 : env = &ctx->envs[ctx->num_env];
245 6 : env->type = type;
246 6 : env->oldval = oldval ? strdup(oldval) : NULL;
247 6 : env->newval = newval ? strdup(newval) : NULL;
248 6 : ++ctx->num_env;
249 : }
250 :
251 : static void
252 : init_save_context(TDSSAVECONTEXT *ctx, const TDSCONTEXT *old_ctx)
253 : {
254 2 : memset(ctx, 0, sizeof(*ctx));
255 2 : ctx->ctx.locale = old_ctx->locale;
256 2 : ctx->ctx.msg_handler = tds_save_msg;
257 2 : ctx->ctx.err_handler = tds_save_err;
258 : }
259 :
260 : static void
261 2 : replay_save_context(TDSSOCKET *tds, TDSSAVECONTEXT *ctx)
262 : {
263 : unsigned n;
264 :
265 : /* replay all recorded messages */
266 6 : for (n = 0; n < ctx->num_msg; ++n)
267 4 : if (ctx->msgs[n].type == 0) {
268 4 : if (tds_get_ctx(tds)->msg_handler)
269 4 : tds_get_ctx(tds)->msg_handler(tds_get_ctx(tds), tds, &ctx->msgs[n].msg);
270 : } else {
271 0 : if (tds_get_ctx(tds)->err_handler)
272 0 : tds_get_ctx(tds)->err_handler(tds_get_ctx(tds), tds, &ctx->msgs[n].msg);
273 : }
274 :
275 : /* replay all recorded envs */
276 6 : for (n = 0; n < ctx->num_env; ++n)
277 6 : if (tds->env_chg_func)
278 0 : tds->env_chg_func(tds, ctx->envs[n].type, ctx->envs[n].oldval, ctx->envs[n].newval);
279 2 : }
280 :
281 : /** Check if any library error (not a server message) was saved */
282 : static bool
283 : has_saved_error(const TDSSAVECONTEXT *ctx)
284 : {
285 : unsigned n;
286 :
287 6 : for (n = 0; n < ctx->num_msg; ++n)
288 4 : if (ctx->msgs[n].type != 0)
289 : return true;
290 : return false;
291 : }
292 :
293 : static void
294 6 : reset_save_context(TDSSAVECONTEXT *ctx)
295 : {
296 : unsigned n;
297 :
298 : /* free all messages */
299 12 : for (n = 0; n < ctx->num_msg; ++n)
300 6 : tds_free_msg(&ctx->msgs[n].msg);
301 6 : ctx->num_msg = 0;
302 :
303 : /* free all envs */
304 12 : for (n = 0; n < ctx->num_env; ++n) {
305 6 : free(ctx->envs[n].oldval);
306 6 : free(ctx->envs[n].newval);
307 : }
308 6 : ctx->num_env = 0;
309 6 : }
310 :
311 : static void
312 : free_save_context(TDSSAVECONTEXT *ctx)
313 : {
314 2 : reset_save_context(ctx);
315 : }
316 :
317 : /**
318 : * Set @@spid based on column data
319 : * \tds
320 : * @param curcol column with spid data.
321 : */
322 : static TDSRET
323 778 : tds_set_spid(TDSSOCKET * tds, TDSCOLUMN *curcol)
324 : {
325 778 : switch (tds_get_conversion_type(curcol->column_type, curcol->column_size)) {
326 778 : case SYBINT2:
327 778 : tds->conn->spid = *((TDS_USMALLINT *) curcol->column_data);
328 : break;
329 0 : case SYBINT4:
330 0 : tds->conn->spid = *((TDS_UINT *) curcol->column_data);
331 : break;
332 : default:
333 : return TDS_FAIL;
334 : }
335 : return TDS_SUCCESS;
336 : }
337 :
338 : /**
339 : * Set ncharsize based on column data.
340 : * \tds
341 : * @param res_info resultset to get data from.
342 : */
343 : static TDSRET
344 : tds_set_nvc(TDSSOCKET * tds, TDSRESULTINFO *res_info)
345 : {
346 : int charsize;
347 :
348 : /* Compute the ratios, put some acceptance in order to avoid issues. */
349 : /* The "3" constant came from the query issued (NVARCHAR(3)) */
350 778 : charsize = res_info->columns[0]->on_server.column_size / 3;
351 778 : if (charsize >= 1 && charsize <= 4)
352 778 : tds->conn->ncharsize = (uint8_t) charsize;
353 : return TDS_SUCCESS;
354 : }
355 :
356 : /**
357 : * Set unicharsize based on column data.
358 : * \tds
359 : * @param res_info resultset to get data from.
360 : */
361 : static TDSRET
362 : tds_set_uvc(TDSSOCKET * tds, TDSRESULTINFO *res_info)
363 : {
364 : int charsize;
365 :
366 : /* Compute the ratios, put some acceptance in order to avoid issues. */
367 : /* The "3" constant came from the query issued (UNIVARCHAR(3)) */
368 778 : charsize = res_info->columns[0]->on_server.column_size / 3;
369 778 : if (charsize >= 1 && charsize <= 4)
370 778 : tds->conn->unicharsize = (uint8_t) charsize;
371 : return TDS_SUCCESS;
372 : }
373 :
374 : /**
375 : * Parse the results from login queries
376 : * \tds
377 : */
378 : static TDSRET
379 3952 : tds_parse_login_results(TDSSOCKET * tds, bool ignore_errors)
380 : {
381 : TDS_INT result_type;
382 : TDS_INT done_flags;
383 : TDSRET rc;
384 : TDSCOLUMN *curcol;
385 3952 : bool last_required = false;
386 :
387 3952 : CHECK_TDS_EXTRA(tds);
388 :
389 17606 : while ((rc = tds_process_tokens(tds, &result_type, &done_flags, TDS_RETURN_ROW|TDS_RETURN_DONE)) == TDS_SUCCESS) {
390 :
391 9702 : switch (result_type) {
392 2334 : case TDS_ROW_RESULT:
393 2334 : if (!tds->res_info || tds->res_info->num_cols < 1)
394 : return TDS_FAIL;
395 2334 : curcol = tds->res_info->columns[0];
396 4668 : if (tds->res_info->num_cols == 1 && strcmp(tds_dstr_cstr(&curcol->column_name), "spid") == 0)
397 778 : rc = tds_set_spid(tds, curcol);
398 4668 : if (tds->res_info->num_cols == 1 && strcmp(tds_dstr_cstr(&curcol->column_name), "nvc") == 0) {
399 778 : rc = tds_set_nvc(tds, tds->res_info);
400 : last_required = true;
401 : }
402 4668 : if (tds->res_info->num_cols == 1 && strcmp(tds_dstr_cstr(&curcol->column_name), "uvc") == 0)
403 778 : rc = tds_set_uvc(tds, tds->res_info);
404 1556 : TDS_PROPAGATE(rc);
405 : break;
406 :
407 7368 : case TDS_DONE_RESULT:
408 : case TDS_DONEPROC_RESULT:
409 : case TDS_DONEINPROC_RESULT:
410 7368 : if ((done_flags & TDS_DONE_ERROR) != 0 && !ignore_errors)
411 : return TDS_FAIL;
412 7368 : if (last_required)
413 2334 : ignore_errors = true;
414 : break;
415 : }
416 : }
417 3952 : if (rc == TDS_NO_MORE_RESULTS)
418 3952 : rc = TDS_SUCCESS;
419 :
420 : return rc;
421 : }
422 :
423 : static TDSRET
424 0 : tds_process_single(TDSSOCKET *tds, char *query, bool ignore_errors)
425 : {
426 : TDSRET erc;
427 :
428 0 : if (!query[0])
429 : return TDS_SUCCESS;
430 :
431 : /* submit and parse results */
432 0 : erc = tds_submit_query(tds, query);
433 0 : if (TDS_SUCCEED(erc))
434 0 : erc = tds_parse_login_results(tds, ignore_errors);
435 :
436 : /* prepare next query */
437 0 : query[0] = 0;
438 :
439 0 : if (TDS_FAILED(erc))
440 0 : free(query);
441 :
442 : return erc;
443 : }
444 :
445 : #define process_single(ignore_errors) do { \
446 : if (!single_query && TDS_FAILED(erc = tds_process_single(tds, str, ignore_errors))) \
447 : return erc; \
448 : } while(0)
449 :
450 : static TDSRET
451 3952 : tds_setup_connection(TDSSOCKET *tds, TDSLOGIN *login, bool set_db, bool single_query)
452 : {
453 : TDSRET erc;
454 : char *str;
455 : size_t len;
456 3952 : const char *const product_name = (tds->conn->product_name != NULL ? tds->conn->product_name : "");
457 3952 : const bool is_sql_anywhere = (strcasecmp(product_name, "SQL Anywhere") == 0);
458 3952 : const bool is_openserver = (strcasecmp(product_name, "OpenServer") == 0);
459 :
460 7904 : len = 192 + tds_quote_id(tds, NULL, tds_dstr_cstr(&login->database),-1);
461 3952 : if ((str = tds_new(char, len)) == NULL)
462 : return TDS_FAIL;
463 :
464 3952 : str[0] = 0;
465 3952 : if (login->text_size)
466 3952 : sprintf(str, "SET TEXTSIZE %d\n", login->text_size);
467 3952 : process_single(false);
468 :
469 3952 : if (tds->conn->spid == -1 && !is_openserver)
470 778 : strcat(str, "SELECT @@spid spid\n");
471 3952 : process_single(true);
472 :
473 : /* Select proper database if specified.
474 : * SQL Anywhere does not support multiple databases and USE statement
475 : * so don't send the request to avoid connection failures */
476 4730 : if (set_db && !tds_dstr_isempty(&login->database) && !is_sql_anywhere) {
477 304 : strcat(str, "USE ");
478 608 : tds_quote_id(tds, strchr(str, 0), tds_dstr_cstr(&login->database), -1);
479 304 : strcat(str, "\n");
480 : }
481 3952 : process_single(false);
482 :
483 3952 : if (IS_TDS50(tds->conn) && !is_sql_anywhere && !is_openserver) {
484 778 : strcat(str, "SELECT CONVERT(NVARCHAR(3), 'abc') nvc\n");
485 778 : if (tds->conn->product_version >= TDS_SYB_VER(12, 0, 0))
486 778 : strcat(str, "EXECUTE ('SELECT CONVERT(UNIVARCHAR(3), ''xyz'') uvc')\n");
487 : }
488 3952 : process_single(true);
489 :
490 : /* nothing to set, just return */
491 3952 : if (str[0] == 0) {
492 0 : free(str);
493 0 : return TDS_SUCCESS;
494 : }
495 :
496 3952 : erc = tds_submit_query(tds, str);
497 3952 : free(str);
498 3952 : TDS_PROPAGATE(erc);
499 :
500 3952 : return tds_parse_login_results(tds, false);
501 : }
502 :
503 : /**
504 : * Do a connection to socket
505 : * @param tds connection structure. This should be a non-connected connection.
506 : * @return TDS_FAIL or TDS_SUCCESS if a connection was made to the server's port.
507 : * @return TDSERROR enumerated type if no TCP/IP connection could be formed.
508 : * @param login info for login
509 : * @remark Possible error conditions:
510 : * - TDSESOCK: socket(2) failed: insufficient local resources
511 : * - TDSECONN: connect(2) failed: invalid hostname or port (ETIMEDOUT, ECONNREFUSED, ENETUNREACH)
512 : * - TDSEFCON: connect(2) succeeded, login packet not acknowledged.
513 : * - TDS_FAIL: connect(2) succeeded, login failed.
514 : */
515 : static TDSRET
516 3990 : tds_connect(TDSSOCKET * tds, TDSLOGIN * login, int *p_oserr)
517 : {
518 3990 : int erc = -TDSEFCON;
519 3990 : int connect_timeout = 0;
520 3990 : bool db_selected = false;
521 : struct addrinfo *addrs;
522 : int orig_port;
523 3990 : bool rerouted = false;
524 : /* save to restore during redirected connection */
525 3990 : unsigned int orig_mars = login->mars;
526 :
527 : /*
528 : * A major version of 0 means try to guess the TDS version.
529 : * We try them in an order that should work.
530 : */
531 : static const TDS_USMALLINT versions[] =
532 : { 0x704
533 : , 0x500
534 : };
535 :
536 3990 : if (!login->valid_configuration) {
537 0 : tdserror(tds_get_ctx(tds), tds, TDSECONF, 0);
538 0 : return TDS_FAIL;
539 : }
540 :
541 3990 : if (TDS_MAJOR(login) == 0) {
542 : unsigned int i;
543 : TDSSAVECONTEXT save_ctx;
544 2 : const TDSCONTEXT *old_ctx = tds_get_ctx(tds);
545 : typedef void (*env_chg_func_t) (TDSSOCKET * tds, int type, char *oldval, char *newval);
546 2 : env_chg_func_t old_env_chg = tds->env_chg_func;
547 : bool error_reported;
548 :
549 4 : init_save_context(&save_ctx, old_ctx);
550 2 : tds_set_ctx(tds, &save_ctx.ctx);
551 2 : tds->env_chg_func = tds_save_env;
552 :
553 4 : for (i = 0; i < TDS_VECTOR_SIZE(versions); ++i) {
554 4 : int orig_size = tds->conn->env.block_size;
555 4 : login->tds_version = versions[i];
556 4 : reset_save_context(&save_ctx);
557 :
558 4 : erc = tds_connect(tds, login, p_oserr);
559 4 : if (TDS_FAILED(erc)) {
560 2 : tds_close_socket(tds);
561 2 : if (tds->conn->env.block_size != orig_size)
562 2 : tds_realloc_socket(tds, orig_size);
563 : }
564 :
565 4 : if (erc != -TDSEFCON) /* TDSEFCON indicates wrong TDS version */
566 : break;
567 2 : if (login->server_is_valid)
568 : break;
569 : }
570 :
571 2 : tds->env_chg_func = old_env_chg;
572 2 : tds_set_ctx(tds, old_ctx);
573 2 : replay_save_context(tds, &save_ctx);
574 2 : error_reported = has_saved_error(&save_ctx);
575 2 : free_save_context(&save_ctx);
576 :
577 : /* do not report the same error twice */
578 2 : if (TDS_FAILED(erc) && !error_reported)
579 0 : tdserror(tds_get_ctx(tds), tds, -erc, *p_oserr);
580 :
581 : return erc;
582 : }
583 :
584 :
585 : /*
586 : * If a dump file has been specified, start logging
587 : */
588 3988 : if (login->dump_file != NULL && !tdsdump_isopen()) {
589 0 : if (login->debug_flags)
590 0 : tds_debug_flags = login->debug_flags;
591 0 : tdsdump_topen(login->dump_file);
592 : }
593 :
594 3988 : tds->login = login;
595 :
596 3988 : tds->conn->tds_version = login->tds_version;
597 :
598 : /* set up iconv if not already initialized*/
599 3988 : if (tds->conn->char_convs[client2ucs2]->to.cd == (iconv_t) -1) {
600 7972 : if (!tds_dstr_isempty(&login->client_charset)) {
601 7972 : if (TDS_FAILED(tds_iconv_open(tds->conn, tds_dstr_cstr(&login->client_charset), login->use_utf16))) {
602 : static const char server_charset[] = "UCS-2LE";
603 :
604 20 : tdserror_args(tds_get_ctx(tds), tds, TDSEICONVAVAIL, 0,
605 20 : (int) tds_dstr_len(&login->client_charset), tds_dstr_cstr(&login->client_charset),
606 : (int) (sizeof(server_charset) - 1), server_charset);
607 10 : return -TDSEICONVAVAIL;
608 : }
609 : }
610 : }
611 :
612 3978 : connect_timeout = login->connect_timeout;
613 :
614 : /* Jeff's hack - begin */
615 3978 : tds->query_timeout = connect_timeout ? connect_timeout : login->query_timeout;
616 : /* end */
617 :
618 : /* verify that ip_addr is not empty */
619 3978 : if (login->ip_addrs == NULL) {
620 0 : tdserror(tds_get_ctx(tds), tds, TDSEUHST, 0 );
621 0 : tdsdump_log(TDS_DBG_ERROR, "IP address pointer is empty\n");
622 0 : if (!tds_dstr_isempty(&login->server_name)) {
623 0 : tdsdump_log(TDS_DBG_ERROR, "Server %s not found!\n", tds_dstr_cstr(&login->server_name));
624 : } else {
625 0 : tdsdump_log(TDS_DBG_ERROR, "No server specified!\n");
626 : }
627 : return -TDSECONN;
628 : }
629 :
630 3978 : tds->conn->capabilities = login->capabilities;
631 :
632 3978 : reroute:
633 3978 : tds_ssl_deinit(tds->conn);
634 3978 : erc = TDSEINTF;
635 3978 : orig_port = login->port;
636 3978 : for (addrs = login->ip_addrs; addrs != NULL; addrs = addrs->ai_next) {
637 :
638 : /*
639 : * By some reasons ftds forms 3 linked tds_addrinfo (addrs
640 : * variable here) for one server address. The structures
641 : * differs in their ai_socktype and ai_protocol field
642 : * values. Typically the combinations are:
643 : * ai_socktype | ai_protocol
644 : * -----------------------------
645 : * 1 (SOCK_STREAM) | 6 (tcp)
646 : * 2 (SOCK_DGRAM) | 17 (udp)
647 : * 3 (SOCK_RAW) | 0 (ip)
648 : *
649 : * Later on these fields are not used and dtds always
650 : * creates a tcp socket. In case if there is a connection
651 : * problem this behavior leads to 3 tries with the provided
652 : * timeout which basically multiplies the spent time
653 : * without any good result. So it was decided to skip the
654 : * non tcp addresses.
655 : *
656 : * NOTE: on Windows exactly one tds_addrinfo structure is
657 : * formed and it has 0 in both ai_socktype and
658 : * ai_protocol fields. So skipping is conditional for
659 : * non-Windows platforms
660 : */
661 : #ifndef _WIN32
662 3978 : if (addrs->ai_socktype != SOCK_STREAM)
663 0 : continue;
664 : #endif
665 :
666 3978 : login->port = orig_port;
667 :
668 7176 : if (!IS_TDS50(tds->conn) && !tds_dstr_isempty(&login->instance_name) && !login->port)
669 4 : login->port = tds7_get_instance_port(addrs, tds_dstr_cstr(&login->instance_name));
670 :
671 3978 : if (login->port >= 1) {
672 3978 : if ((erc = tds_open_socket(tds, addrs, login->port, connect_timeout, p_oserr)) == TDSEOK)
673 : break;
674 : } else {
675 : erc = TDSECONN;
676 : }
677 : }
678 :
679 3978 : if (erc != TDSEOK) {
680 0 : if (login->port < 1)
681 0 : tdsdump_log(TDS_DBG_ERROR, "invalid port number\n");
682 :
683 0 : tdserror(tds_get_ctx(tds), tds, erc, *p_oserr);
684 0 : return -erc;
685 : }
686 :
687 : /*
688 : * Beyond this point, we're connected to the server. We know we have a valid TCP/IP address+socket pair.
689 : * Although network errors *might* happen, most problems from here on out will be TDS-level errors,
690 : * either TDS version problems or authentication problems.
691 : */
692 :
693 3978 : tds_set_state(tds, TDS_IDLE);
694 3978 : tds->conn->spid = -1;
695 :
696 : /* discard possible previous authentication */
697 3978 : if (tds->conn->authentication) {
698 0 : tds->conn->authentication->free(tds->conn, tds->conn->authentication);
699 0 : tds->conn->authentication = NULL;
700 : }
701 :
702 3978 : if (IS_TDS71_PLUS(tds->conn)) {
703 3188 : erc = tds71_do_login(tds, login);
704 3188 : db_selected = true;
705 790 : } else if (IS_TDS7_PLUS(tds->conn)) {
706 10 : erc = tds7_send_login(tds, login);
707 10 : db_selected = true;
708 : } else {
709 780 : tds->out_flag = TDS_LOGIN;
710 :
711 : /* SAP ASE 15.0+ SSL mode encrypts entire connection (like stunnel) */
712 780 : if (login->encryption_level == TDS_ENCRYPTION_STRICT)
713 0 : TDS_PROPAGATE(tds_ssl_init(tds, true));
714 :
715 780 : erc = tds_send_login(tds, login);
716 : }
717 3978 : if (TDS_FAILED(erc) || TDS_FAILED(tds_process_login_tokens(tds))) {
718 26 : tdsdump_log(TDS_DBG_ERROR, "login packet %s\n", TDS_SUCCEED(erc)? "accepted":"rejected");
719 26 : tds_close_socket(tds);
720 26 : tdserror(tds_get_ctx(tds), tds, TDSEFCON, 0); /* "TDS server connection failed" */
721 26 : return -TDSEFCON;
722 : }
723 :
724 : /* need to do rerouting */
725 3952 : if (IS_TDS71_PLUS(tds->conn)
726 6348 : && !tds_dstr_isempty(&login->routing_address) && login->routing_port) {
727 : TDSRET ret;
728 0 : char *server_name = NULL;
729 :
730 0 : tds_close_socket(tds);
731 : /* only one redirection is allowed */
732 0 : if (rerouted) {
733 0 : tdserror(tds_get_ctx(tds), tds, TDSEFCON, 0);
734 0 : return -TDSEFCON;
735 : }
736 0 : if (asprintf(&server_name, "%s,%d", tds_dstr_cstr(&login->routing_address), login->routing_port) < 0) {
737 0 : tdserror(tds_get_ctx(tds), tds, TDSEFCON, 0);
738 0 : return -TDSEMEM;
739 : }
740 0 : if (!tds_dstr_set(&login->server_name, server_name)) {
741 0 : free(server_name);
742 0 : tdserror(tds_get_ctx(tds), tds, TDSEFCON, 0);
743 0 : return -TDSEMEM;
744 : }
745 0 : login->mars = orig_mars;
746 0 : login->port = login->routing_port;
747 0 : ret = tds_lookup_host_set(tds_dstr_cstr(&login->routing_address), &login->ip_addrs);
748 0 : login->routing_port = 0;
749 0 : tds_dstr_free(&login->routing_address);
750 0 : if (TDS_FAILED(ret)) {
751 0 : tdserror(tds_get_ctx(tds), tds, TDSEFCON, 0);
752 0 : return -TDSEFCON;
753 : }
754 0 : rerouted = true;
755 0 : goto reroute;
756 : }
757 :
758 : #if ENABLE_ODBC_MARS
759 : /* initialize SID */
760 1976 : if (IS_TDS72_PLUS(tds->conn) && login->mars) {
761 : TDS72_SMP_HEADER *p;
762 :
763 219 : tds_extra_assert(tds->sid == 0);
764 219 : tds_extra_assert(tds->conn->sessions[0] == tds);
765 219 : tds_extra_assert(tds->send_packet != NULL);
766 219 : tds_extra_assert(!tds->send_packet->next);
767 :
768 219 : tds->conn->mars = 1;
769 :
770 : /* start session with a SMP SYN */
771 219 : if (TDS_FAILED(tds_append_syn(tds)))
772 : return -TDSEMEM;
773 :
774 : /* reallocate send_packet */
775 219 : if (!tds_realloc_socket(tds, tds->out_buf_max))
776 : return -TDSEMEM;
777 :
778 : /* start SMP DATA header */
779 219 : p = (TDS72_SMP_HEADER *) tds->send_packet->buf;
780 219 : p->signature = TDS72_SMP;
781 219 : p->type = TDS_SMP_DATA;
782 :
783 219 : tds_init_write_buf(tds);
784 : }
785 : #endif
786 :
787 3952 : erc = tds_setup_connection(tds, login, !db_selected, true);
788 : /* try one query at a time, some servers do not support some queries */
789 3952 : if (TDS_FAILED(erc))
790 0 : erc = tds_setup_connection(tds, login, !db_selected, false);
791 3952 : TDS_PROPAGATE(erc);
792 :
793 3952 : tds->query_timeout = login->query_timeout;
794 3952 : tds->login = NULL;
795 3952 : return TDS_SUCCESS;
796 : }
797 :
798 : TDSRET
799 3986 : tds_connect_and_login(TDSSOCKET * tds, TDSLOGIN * login)
800 : {
801 3986 : int oserr = 0;
802 :
803 3986 : TDS_PROPAGATE(tds8_adjust_login(login));
804 :
805 3986 : return tds_connect(tds, login, &oserr);
806 : }
807 :
808 : /**
809 : * Compute the service principal name (SPN) of the server, used by
810 : * Kerberos (GSSAPI), SSPI and NTLM authentication.
811 : * The "spn" configuration value is used if set.
812 : * Otherwise, for Microsoft SQL Server, "MSSQLSvc/<host>:<instance>",
813 : * or "MSSQLSvc/<host>:<port>" if no instance name is used; host is
814 : * expanded to a fully qualified domain name if possible.
815 : * For Sybase the server name is returned.
816 : * @param tds connection to the server
817 : * @return SPN (to be freed) or NULL on error
818 : */
819 : char *
820 828 : tds_get_spn(TDSSOCKET *tds)
821 : {
822 828 : TDSLOGIN *login = tds->login;
823 : const char *server_name;
824 828 : struct addrinfo *addrs = NULL;
825 828 : char *spn = NULL;
826 : int len;
827 :
828 1656 : if (!tds_dstr_isempty(&login->server_spn))
829 20 : return strdup(tds_dstr_cstr(&login->server_spn));
830 :
831 : /* TDS 5.0, Sybase */
832 818 : if (!IS_TDS7_PLUS(tds->conn))
833 20 : return strdup(tds_dstr_cstr(&login->server_name));
834 :
835 : /* try to get a fully qualified domain name */
836 1616 : server_name = tds_dstr_cstr(&login->server_host_name);
837 808 : if (strchr(server_name, '.') == NULL) {
838 : struct addrinfo hints;
839 : int res;
840 :
841 0 : memset(&hints, 0, sizeof(hints));
842 : hints.ai_family = AF_UNSPEC;
843 0 : hints.ai_socktype = SOCK_STREAM;
844 : /* do not use AI_FQDN, Windows does not allow it with AI_CANONNAME */
845 0 : hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG | AI_CANONNAME;
846 0 : res = getaddrinfo(server_name, NULL, &hints, &addrs);
847 0 : if (res) {
848 : /* some versions of Windows do not support V4MAPPED and ADDRCONFIG, try without them */
849 0 : addrs = NULL;
850 0 : hints.ai_flags = AI_CANONNAME;
851 0 : res = getaddrinfo(server_name, NULL, &hints, &addrs);
852 : }
853 0 : if (res)
854 0 : addrs = NULL;
855 0 : else if (addrs->ai_canonname && strchr(addrs->ai_canonname, '.') != NULL)
856 0 : server_name = addrs->ai_canonname;
857 : }
858 :
859 1616 : if (!tds_dstr_isempty(&login->instance_name))
860 20 : len = asprintf(&spn, "MSSQLSvc/%s:%s", server_name, tds_dstr_cstr(&login->instance_name));
861 : else
862 798 : len = asprintf(&spn, "MSSQLSvc/%s:%d", server_name, login->port);
863 808 : if (len < 0)
864 0 : spn = NULL;
865 :
866 808 : if (addrs)
867 0 : freeaddrinfo(addrs);
868 808 : return spn;
869 : }
870 :
871 : static void
872 7800 : tds_put_buf(TDSSOCKET *tds, const unsigned char *buf, size_t dsize, size_t ssize)
873 : {
874 : size_t cpsize;
875 :
876 7800 : cpsize = TDS_MIN(ssize, dsize);
877 7800 : tds_put_n(tds, buf, cpsize);
878 7800 : dsize -= cpsize;
879 7800 : tds_put_n(tds, NULL, dsize);
880 7800 : TDS_PUT_BYTE(tds, cpsize);
881 7800 : }
882 :
883 : static void
884 5460 : tds_put_login_string(TDSSOCKET * tds, const char *buf, size_t n)
885 : {
886 7800 : const size_t buf_len = buf ? strlen(buf) : 0;
887 7800 : tds_put_buf(tds, (const unsigned char *) buf, n, buf_len);
888 5460 : }
889 :
890 : #define tds_put_login_string(tds, buf, n) do { \
891 : TDS_COMPILE_CHECK(range, (n) > 0 && (n) < 256); \
892 : tds_put_login_string(tds, buf, (n)); \
893 : } while(0)
894 :
895 : static TDSRET
896 780 : tds_send_login(TDSSOCKET * tds, const TDSLOGIN * login)
897 : {
898 : static const unsigned char le1[] = { 0x03, 0x01, 0x06, 0x0a, 0x09, 0x01 };
899 : static const unsigned char le2[] = { 0x00, 13, 17 };
900 :
901 : /*
902 : * capabilities are now part of the tds structure.
903 : * unsigned char capabilities[]= {0x01,0x07,0x03,109,127,0xFF,0xFF,0xFF,0xFE,0x02,0x07,0x00,0x00,0x0A,104,0x00,0x00,0x00};
904 : */
905 : /*
906 : * This is the original capabilities packet we were working with (sqsh)
907 : * unsigned char capabilities[]= {0x01,0x07,0x03,109,127,0xFF,0xFF,0xFF,0xFE,0x02,0x07,0x00,0x00,0x0A,104,0x00,0x00,0x00};
908 : * original with 4.x messages
909 : * unsigned char capabilities[]= {0x01,0x07,0x03,109,127,0xFF,0xFF,0xFF,0xFE,0x02,0x07,0x00,0x00,0x00,120,192,0x00,0x0D};
910 : * This is isql 11.0.3
911 : * unsigned char capabilities[]= {0x01,0x07,0x00,96, 129,207, 0xFF,0xFE,62, 0x02,0x07,0x00,0x00,0x00,120,192,0x00,0x0D};
912 : * like isql but with 5.0 messages
913 : * unsigned char capabilities[]= {0x01,0x07,0x00,96, 129,207, 0xFF,0xFE,62, 0x02,0x07,0x00,0x00,0x00,120,192,0x00,0x00};
914 : */
915 :
916 : unsigned char protocol_version[4];
917 : unsigned char program_version[4];
918 780 : unsigned char sec_flags = 0;
919 780 : bool use_kerberos = false;
920 :
921 : char blockstr[16];
922 :
923 780 : TDS_TINYINT encryption_level = login->encryption_level;
924 :
925 : /* override lservname field for ASA servers */
926 1560 : const char *lservname = getenv("ASA_DATABASE")? getenv("ASA_DATABASE") : tds_dstr_cstr(&login->server_name);
927 :
928 1560 : if (strchr(tds_dstr_cstr(&login->user_name), '\\') != NULL) {
929 0 : tdsdump_log(TDS_DBG_ERROR, "NT login not supported using TDS 4.x or 5.0\n");
930 : return TDS_FAIL;
931 : }
932 1560 : if (tds_dstr_isempty(&login->user_name)) {
933 0 : if (!IS_TDS50(tds->conn)) {
934 0 : tdsdump_log(TDS_DBG_ERROR, "Kerberos login not supported using TDS 4.x\n");
935 : return TDS_FAIL;
936 : }
937 :
938 : #ifdef ENABLE_KRB5
939 : /* try kerberos */
940 0 : sec_flags = TDS5_SEC_LOG_SECSESS;
941 0 : use_kerberos = true;
942 0 : tds->conn->authentication = tds_gss_get_auth(tds);
943 0 : if (!tds->conn->authentication)
944 : return TDS_FAIL;
945 : #else
946 : tdsdump_log(TDS_DBG_ERROR, "requested GSS authentication but not compiled in\n");
947 : return TDS_FAIL;
948 : #endif
949 : }
950 780 : if (encryption_level == TDS_ENCRYPTION_DEFAULT)
951 780 : encryption_level = TDS_ENCRYPTION_OFF;
952 780 : if (!use_kerberos && encryption_level != TDS_ENCRYPTION_OFF) {
953 0 : if (!IS_TDS50(tds->conn)) {
954 0 : tdsdump_log(TDS_DBG_ERROR, "Encryption not supported using TDS 4.x\n");
955 : return TDS_FAIL;
956 : }
957 0 : tds->conn->authentication = tds5_negotiate_get_auth(tds);
958 0 : if (!tds->conn->authentication)
959 : return TDS_FAIL;
960 : }
961 :
962 780 : if (IS_TDS42(tds->conn)) {
963 0 : memcpy(protocol_version, "\004\002\000\000", 4);
964 0 : memcpy(program_version, "\004\002\000\000", 4);
965 780 : } else if (IS_TDS46(tds->conn)) {
966 0 : memcpy(protocol_version, "\004\006\000\000", 4);
967 0 : memcpy(program_version, "\004\002\000\000", 4);
968 780 : } else if (IS_TDS50(tds->conn)) {
969 780 : memcpy(protocol_version, "\005\000\000\000", 4);
970 780 : memcpy(program_version, "\005\000\000\000", 4);
971 : } else {
972 0 : tdsdump_log(TDS_DBG_SEVERE, "Unknown protocol version!\n");
973 : return TDS_FAIL;
974 : }
975 : /*
976 : * the following code is adapted from Arno Pedusaar's
977 : * (psaar@fenar.ee) MS-SQL Client. His was a much better way to
978 : * do this, (well...mine was a kludge actually) so here's mostly his
979 : */
980 :
981 1560 : tds_put_login_string(tds, tds_dstr_cstr(&login->client_host_name), TDS_MAXNAME); /* client host name */
982 1560 : tds_put_login_string(tds, tds_dstr_cstr(&login->user_name), TDS_MAXNAME); /* account name */
983 : /* account password */
984 780 : if (encryption_level != TDS_ENCRYPTION_OFF) {
985 : tds_put_login_string(tds, NULL, TDS_MAXNAME);
986 : } else {
987 1560 : tds_put_login_string(tds, tds_dstr_cstr(&login->password), TDS_MAXNAME);
988 : }
989 780 : sprintf(blockstr, "%d", (int) getpid());
990 780 : tds_put_login_string(tds, blockstr, TDS_MAXNAME); /* host process */
991 780 : tds_put_n(tds, le1, 6);
992 780 : tds_put_byte(tds, !login->bulk_copy);
993 780 : tds_put_n(tds, NULL, 2);
994 780 : if (IS_TDS42(tds->conn)) {
995 0 : tds_put_int(tds, 512);
996 : } else {
997 780 : tds_put_int(tds, 0);
998 : }
999 780 : tds_put_n(tds, NULL, 3);
1000 1560 : tds_put_login_string(tds, tds_dstr_cstr(&login->app_name), TDS_MAXNAME);
1001 780 : tds_put_login_string(tds, lservname, TDS_MAXNAME);
1002 780 : if (IS_TDS42(tds->conn)) {
1003 0 : tds_put_login_string(tds, tds_dstr_cstr(&login->password), 255);
1004 780 : } else if (encryption_level != TDS_ENCRYPTION_OFF) {
1005 0 : tds_put_n(tds, NULL, 256);
1006 : } else {
1007 1560 : size_t len = tds_dstr_len(&login->password);
1008 780 : if (len > 253)
1009 0 : len = 0;
1010 780 : tds_put_byte(tds, 0);
1011 780 : TDS_PUT_BYTE(tds, len);
1012 1560 : tds_put_n(tds, tds_dstr_cstr(&login->password), len);
1013 780 : tds_put_n(tds, NULL, 253 - len);
1014 780 : TDS_PUT_BYTE(tds, len + 2);
1015 : }
1016 :
1017 780 : tds_put_n(tds, protocol_version, 4); /* TDS version; { 0x04,0x02,0x00,0x00 } */
1018 1560 : tds_put_login_string(tds, tds_dstr_cstr(&login->library), TDS_PROGNLEN); /* client program name */
1019 780 : if (IS_TDS42(tds->conn)) {
1020 0 : tds_put_int(tds, 0);
1021 : } else {
1022 780 : tds_put_n(tds, program_version, 4); /* program version ? */
1023 : }
1024 780 : tds_put_n(tds, le2, 3);
1025 1560 : tds_put_login_string(tds, tds_dstr_cstr(&login->language), TDS_MAXNAME); /* language */
1026 780 : tds_put_byte(tds, login->suppress_language);
1027 :
1028 : /* oldsecure(2), should be zero, used by old software */
1029 780 : tds_put_n(tds, NULL, 2);
1030 : /* seclogin(1) bitmask */
1031 780 : if (sec_flags == 0 && encryption_level != TDS_ENCRYPTION_OFF)
1032 0 : sec_flags = TDS5_SEC_LOG_ENCRYPT2|TDS5_SEC_LOG_ENCRYPT3;
1033 780 : tds_put_byte(tds, sec_flags);
1034 : /* secbulk(1)
1035 : * halogin(1) type of ha login
1036 : * hasessionid(6) id of session to reconnect
1037 : * secspare(2) not used
1038 : */
1039 780 : tds_put_n(tds, NULL, 10);
1040 :
1041 : /* use empty charset to handle conversions on client */
1042 780 : tds_put_login_string(tds, "", TDS_MAXNAME); /* charset */
1043 : /* this is a flag, mean that server should use character set provided by client */
1044 : /* TODO notify charset change ?? what's correct meaning ?? -- freddy77 */
1045 780 : tds_put_byte(tds, 1);
1046 :
1047 : /* network packet size */
1048 780 : if (login->block_size < 65536u && login->block_size >= 512)
1049 0 : sprintf(blockstr, "%d", login->block_size);
1050 : else
1051 780 : strcpy(blockstr, "512");
1052 780 : tds_put_login_string(tds, blockstr, TDS_PKTLEN);
1053 :
1054 780 : if (IS_TDS42(tds->conn)) {
1055 0 : tds_put_n(tds, NULL, 8);
1056 780 : } else if (IS_TDS46(tds->conn)) {
1057 0 : tds_put_n(tds, NULL, 4);
1058 780 : } else if (IS_TDS50(tds->conn)) {
1059 : /* just padding to 8 bytes */
1060 780 : tds_put_n(tds, NULL, 4);
1061 :
1062 : /* send capabilities */
1063 780 : tds_put_byte(tds, TDS_CAPABILITY_TOKEN);
1064 780 : tds_put_smallint(tds, sizeof(tds->conn->capabilities));
1065 780 : tds_put_n(tds, &tds->conn->capabilities, sizeof(tds->conn->capabilities));
1066 : }
1067 :
1068 : #ifdef ENABLE_KRB5
1069 780 : if (use_kerberos)
1070 0 : tds5_gss_send(tds);
1071 : #endif
1072 :
1073 780 : return tds_flush_packet(tds);
1074 : }
1075 :
1076 : /**
1077 : * tds7_send_login() -- Send a TDS 7.0 login packet
1078 : * TDS 7.0 login packet is vastly different and so gets its own function
1079 : * \returns the return value is ignored by the caller. :-/
1080 : */
1081 : static TDSRET
1082 3196 : tds7_send_login(TDSSOCKET * tds, const TDSLOGIN * login)
1083 : {
1084 : static const unsigned char
1085 : client_progver[] = { 6, 0x83, 0xf2, 0xf8 },
1086 :
1087 : connection_id[] = { 0x00, 0x00, 0x00, 0x00 },
1088 : collation[] = { 0x36, 0x04, 0x00, 0x00 };
1089 :
1090 : enum {
1091 : tds70Version = 0x70000000,
1092 : tds71Version = 0x71000001,
1093 : tds72Version = 0x72090002,
1094 : tds73Version = 0x730B0003,
1095 : tds74Version = 0x74000004,
1096 : };
1097 3196 : TDS_UCHAR sql_type_flag = 0x00;
1098 3196 : TDS_INT time_zone = -120;
1099 3196 : TDS_INT tds7version = tds70Version;
1100 :
1101 3196 : unsigned int block_size = 4096;
1102 :
1103 3196 : unsigned char option_flag1 = TDS_SET_LANG_ON | TDS_USE_DB_NOTIFY | TDS_INIT_DB_FATAL;
1104 3196 : unsigned char option_flag2 = login->option_flag2;
1105 3196 : unsigned char option_flag3 = 0;
1106 :
1107 : unsigned char hwaddr[6];
1108 : size_t packet_size, current_pos;
1109 : TDSRET rc;
1110 :
1111 3196 : void *data = NULL;
1112 : TDSDYNAMICSTREAM data_stream;
1113 : TDSSTATICINSTREAM input;
1114 :
1115 6392 : const char *user_name = tds_dstr_cstr(&login->user_name);
1116 : unsigned char *pwd;
1117 :
1118 : /* FIXME: These should be TDS_SMALLINT. */
1119 3196 : size_t user_name_len = strlen(user_name);
1120 3196 : unsigned int auth_len = 0;
1121 :
1122 : static const char ext_data[] =
1123 : "\x0a\x01\x00\x00\x00\x01" /* Enable UTF-8 */
1124 : "\xff";
1125 3196 : size_t ext_len = IS_TDS74_PLUS(tds->conn) ? sizeof(ext_data) - 1 : 0;
1126 :
1127 : /* fields */
1128 : enum {
1129 : HOST_NAME,
1130 : USER_NAME,
1131 : PASSWORD,
1132 : APP_NAME,
1133 : SERVER_NAME,
1134 : EXTENSION,
1135 : LIBRARY_NAME,
1136 : LANGUAGE,
1137 : DATABASE_NAME,
1138 : DB_FILENAME,
1139 : NEW_PASSWORD,
1140 : NUM_DATA_FIELDS
1141 : };
1142 : struct {
1143 : const void *ptr;
1144 : size_t pos, len, limit;
1145 : } data_fields[NUM_DATA_FIELDS], *field;
1146 :
1147 3196 : tds->out_flag = TDS7_LOGIN;
1148 :
1149 3196 : current_pos = packet_size = IS_TDS72_PLUS(tds->conn) ? 86 + 8 : 86; /* ? */
1150 :
1151 : /* check ntlm */
1152 : #ifdef HAVE_SSPI
1153 : if (strchr(user_name, '\\') != NULL || user_name_len == 0) {
1154 : tdsdump_log(TDS_DBG_INFO2, "using SSPI authentication for '%s' account\n", user_name);
1155 : tds->conn->authentication = tds_sspi_get_auth(tds);
1156 : if (!tds->conn->authentication)
1157 : return TDS_FAIL;
1158 : auth_len = tds->conn->authentication->packet_len;
1159 : packet_size += auth_len;
1160 : #else
1161 3196 : if (strchr(user_name, '\\') != NULL) {
1162 778 : tdsdump_log(TDS_DBG_INFO2, "using NTLM authentication for '%s' account\n", user_name);
1163 778 : tds->conn->authentication = tds_ntlm_get_auth(tds);
1164 778 : if (!tds->conn->authentication)
1165 : return TDS_FAIL;
1166 778 : auth_len = tds->conn->authentication->packet_len;
1167 778 : packet_size += auth_len;
1168 2418 : } else if (user_name_len == 0) {
1169 : # ifdef ENABLE_KRB5
1170 : /* try kerberos */
1171 0 : tdsdump_log(TDS_DBG_INFO2, "using GSS authentication\n");
1172 0 : tds->conn->authentication = tds_gss_get_auth(tds);
1173 0 : if (!tds->conn->authentication)
1174 : return TDS_FAIL;
1175 0 : auth_len = tds->conn->authentication->packet_len;
1176 0 : packet_size += auth_len;
1177 : # else
1178 : tdsdump_log(TDS_DBG_ERROR, "requested GSS authentication but not compiled in\n");
1179 : return TDS_FAIL;
1180 : # endif
1181 : #endif
1182 : }
1183 :
1184 :
1185 : /* initialize ouput buffer for strings */
1186 3196 : TDS_PROPAGATE(tds_dynamic_stream_init(&data_stream, &data, 0));
1187 :
1188 : #define SET_FIELD_DSTR(field, dstr, len_limit) do { \
1189 : data_fields[field].ptr = tds_dstr_cstr(&(dstr)); \
1190 : data_fields[field].len = tds_dstr_len(&(dstr)); \
1191 : data_fields[field].limit = (len_limit) * 2; \
1192 : } while(0)
1193 :
1194 : /* setup data fields */
1195 3196 : memset(data_fields, 0, sizeof(data_fields));
1196 9588 : SET_FIELD_DSTR(HOST_NAME, login->client_host_name, 128);
1197 3196 : if (!tds->conn->authentication) {
1198 7254 : SET_FIELD_DSTR(USER_NAME, login->user_name, 128);
1199 7254 : SET_FIELD_DSTR(PASSWORD, login->password, 128);
1200 : }
1201 9588 : SET_FIELD_DSTR(APP_NAME, login->app_name, 128);
1202 9588 : SET_FIELD_DSTR(SERVER_NAME, login->server_name, 128);
1203 9588 : SET_FIELD_DSTR(LIBRARY_NAME, login->library, 128);
1204 9588 : SET_FIELD_DSTR(LANGUAGE, login->language, 128);
1205 9588 : SET_FIELD_DSTR(DATABASE_NAME, login->database, 128);
1206 9588 : SET_FIELD_DSTR(DB_FILENAME, login->db_filename, 260);
1207 3196 : if (IS_TDS72_PLUS(tds->conn) && login->use_new_password) {
1208 2 : option_flag3 |= TDS_CHANGE_PASSWORD;
1209 6 : SET_FIELD_DSTR(NEW_PASSWORD, login->new_password, 128);
1210 : }
1211 3196 : if (ext_len)
1212 784 : option_flag3 |= TDS_EXTENSION;
1213 :
1214 : /* convert data fields */
1215 38352 : for (field = data_fields; field < data_fields + TDS_VECTOR_SIZE(data_fields); ++field) {
1216 : size_t data_pos;
1217 :
1218 35156 : data_pos = data_stream.size;
1219 35156 : field->pos = current_pos + data_pos;
1220 35156 : if (field->len) {
1221 19112 : tds_staticin_stream_init(&input, field->ptr, field->len);
1222 19112 : rc = tds_convert_stream(tds, tds->conn->char_convs[client2ucs2], to_server, &input.stream, &data_stream.stream);
1223 19112 : if (TDS_FAILED(rc)) {
1224 0 : free(data);
1225 0 : return TDS_FAIL;
1226 : }
1227 16044 : } else if (ext_len && field == &data_fields[EXTENSION]) {
1228 : /* reserve 4 bytes in the stream to put the extention offset */
1229 784 : if (data_stream.stream.write(&data_stream.stream, 4) != 4) {
1230 0 : free(data);
1231 0 : return TDS_FAIL;
1232 : }
1233 784 : field->len = 4;
1234 784 : continue;
1235 : }
1236 34372 : data_stream.size = TDS_MIN(data_stream.size, data_pos + field->limit);
1237 34372 : data_stream.stream.write(&data_stream.stream, 0);
1238 34372 : field->len = data_stream.size - data_pos;
1239 : }
1240 3196 : pwd = (unsigned char *) data + data_fields[PASSWORD].pos - current_pos;
1241 6392 : tds7_crypt_pass(pwd, data_fields[PASSWORD].len, pwd);
1242 3196 : pwd = (unsigned char *) data + data_fields[NEW_PASSWORD].pos - current_pos;
1243 6392 : tds7_crypt_pass(pwd, data_fields[NEW_PASSWORD].len, pwd);
1244 3196 : packet_size += data_stream.size;
1245 3196 : if (ext_len) {
1246 784 : packet_size += ext_len;
1247 784 : pwd = (unsigned char *) data + data_fields[EXTENSION].pos - current_pos;
1248 784 : TDS_PUT_UA4LE(pwd, current_pos + data_stream.size + auth_len);
1249 : }
1250 :
1251 : #if !defined(TDS_DEBUG_LOGIN)
1252 3196 : tdsdump_log(TDS_DBG_INFO2, "quietly sending TDS 7+ login packet\n");
1253 : do { TDSDUMP_OFF_ITEM off_item;
1254 3196 : tdsdump_off(&off_item);
1255 : #endif
1256 3196 : TDS_PUT_INT(tds, packet_size);
1257 3196 : switch (login->tds_version) {
1258 : case 0x700:
1259 : tds7version = tds70Version;
1260 : break;
1261 1602 : case 0x701:
1262 1602 : tds7version = tds71Version;
1263 1602 : break;
1264 0 : case 0x702:
1265 0 : tds7version = tds72Version;
1266 0 : break;
1267 800 : case 0x703:
1268 800 : tds7version = tds73Version;
1269 800 : break;
1270 784 : case 0x800:
1271 : /* for TDS 8.0 version should be ignored and ALPN used,
1272 : * practically clients/servers usually set this to 7.4 */
1273 : case 0x704:
1274 784 : tds7version = tds74Version;
1275 784 : break;
1276 : default:
1277 0 : assert(0 && 0x700 <= login->tds_version && login->tds_version <= 0x704);
1278 : }
1279 :
1280 3196 : tds_put_int(tds, tds7version);
1281 :
1282 3196 : if (4096 <= login->block_size && login->block_size < 65536u)
1283 0 : block_size = login->block_size;
1284 :
1285 3196 : tds_put_int(tds, block_size); /* desired packet size being requested by client */
1286 :
1287 3196 : if (block_size > tds->out_buf_max)
1288 10 : tds_realloc_socket(tds, block_size);
1289 :
1290 3196 : tds_put_n(tds, client_progver, sizeof(client_progver)); /* client program version ? */
1291 :
1292 3196 : tds_put_int(tds, getpid()); /* process id of this process */
1293 :
1294 3196 : tds_put_n(tds, connection_id, sizeof(connection_id));
1295 :
1296 3196 : if (!login->bulk_copy)
1297 0 : option_flag1 |= TDS_DUMPLOAD_OFF;
1298 :
1299 3196 : tds_put_byte(tds, option_flag1);
1300 :
1301 3196 : if (tds->conn->authentication)
1302 778 : option_flag2 |= TDS_INTEGRATED_SECURITY_ON;
1303 :
1304 3196 : tds_put_byte(tds, option_flag2);
1305 :
1306 3196 : if (login->readonly_intent && IS_TDS71_PLUS(tds->conn))
1307 0 : sql_type_flag |= TDS_READONLY_INTENT;
1308 3196 : tds_put_byte(tds, sql_type_flag);
1309 :
1310 3196 : if (IS_TDS73_PLUS(tds->conn))
1311 1584 : option_flag3 |= TDS_UNKNOWN_COLLATION_HANDLING;
1312 3196 : tds_put_byte(tds, option_flag3);
1313 :
1314 3196 : tds_put_int(tds, time_zone);
1315 3196 : tds_put_n(tds, collation, sizeof(collation));
1316 :
1317 : #define PUT_STRING_FIELD_PTR(field) do { \
1318 : TDS_PUT_SMALLINT(tds, data_fields[field].pos); \
1319 : TDS_PUT_SMALLINT(tds, data_fields[field].len / 2u); \
1320 : } while(0)
1321 :
1322 : /* host name */
1323 3196 : PUT_STRING_FIELD_PTR(HOST_NAME);
1324 3196 : if (tds->conn->authentication) {
1325 778 : tds_put_int(tds, 0);
1326 778 : tds_put_int(tds, 0);
1327 : } else {
1328 : /* username */
1329 2418 : PUT_STRING_FIELD_PTR(USER_NAME);
1330 : /* password */
1331 2418 : PUT_STRING_FIELD_PTR(PASSWORD);
1332 : }
1333 : /* app name */
1334 3196 : PUT_STRING_FIELD_PTR(APP_NAME);
1335 : /* server name */
1336 3196 : PUT_STRING_FIELD_PTR(SERVER_NAME);
1337 : /* extensions */
1338 3196 : if (ext_len) {
1339 784 : TDS_PUT_SMALLINT(tds, data_fields[EXTENSION].pos);
1340 784 : tds_put_smallint(tds, 4);
1341 : } else {
1342 2412 : tds_put_int(tds, 0);
1343 : }
1344 : /* library name */
1345 3196 : PUT_STRING_FIELD_PTR(LIBRARY_NAME);
1346 : /* language - kostya@warmcat.excom.spb.su */
1347 3196 : PUT_STRING_FIELD_PTR(LANGUAGE);
1348 : /* database name */
1349 3196 : PUT_STRING_FIELD_PTR(DATABASE_NAME);
1350 :
1351 : /* MAC address */
1352 3196 : tds_getmac(tds_get_s(tds), hwaddr);
1353 3196 : tds_put_n(tds, hwaddr, 6);
1354 :
1355 : /* authentication stuff */
1356 3196 : TDS_PUT_SMALLINT(tds, current_pos + data_stream.size);
1357 3196 : TDS_PUT_SMALLINT(tds, TDS_MIN(auth_len, 0xffffu));
1358 :
1359 : /* db file */
1360 3196 : PUT_STRING_FIELD_PTR(DB_FILENAME);
1361 :
1362 3196 : if (IS_TDS72_PLUS(tds->conn)) {
1363 : /* new password */
1364 1584 : PUT_STRING_FIELD_PTR(NEW_PASSWORD);
1365 :
1366 : /* SSPI long */
1367 1584 : tds_put_int(tds, auth_len >= 0xffffu ? auth_len : 0);
1368 : }
1369 :
1370 3196 : tds_put_n(tds, data, data_stream.size);
1371 :
1372 3196 : if (tds->conn->authentication)
1373 778 : tds_put_n(tds, tds->conn->authentication->packet, auth_len);
1374 :
1375 3196 : if (ext_len)
1376 784 : tds_put_n(tds, ext_data, ext_len);
1377 :
1378 3196 : rc = tds_flush_packet(tds);
1379 :
1380 : #if !defined(TDS_DEBUG_LOGIN)
1381 3196 : tdsdump_on(&off_item);
1382 : } while(0);
1383 : #endif
1384 :
1385 3196 : free(data);
1386 3196 : return rc;
1387 : }
1388 :
1389 : /**
1390 : * tds7_crypt_pass() -- 'encrypt' TDS 7.0 style passwords.
1391 : * the calling function is responsible for ensuring crypt_pass is at least
1392 : * 'len' characters
1393 : */
1394 : static void
1395 : tds7_crypt_pass(const unsigned char *clear_pass, size_t len, unsigned char *crypt_pass)
1396 : {
1397 : size_t i;
1398 :
1399 56056 : for (i = 0; i < len; i++)
1400 52860 : crypt_pass[i] = ((clear_pass[i] << 4) | (clear_pass[i] >> 4)) ^ 0xA5;
1401 : }
1402 :
1403 : #if defined(HAVE_GNUTLS) || defined(HAVE_OPENSSL)
1404 : static inline TDS_TINYINT
1405 : tds7_get_encryption_byte(TDS_TINYINT encryption_level)
1406 : {
1407 3188 : switch (encryption_level) {
1408 : /* The observation working with Microsoft SQL Server is that
1409 : OFF did not mean off, and you would end up with encryption
1410 : turned on. Therefore when the freetds.conf says encrypt = off
1411 : we really want no encryption, and claiming lack of support
1412 : works for that. Note that the configuration default in this
1413 : subroutine always been request due to code above that
1414 : tests for TDS_ENCRYPTION_DEFAULT.
1415 : */
1416 : case TDS_ENCRYPTION_OFF:
1417 : case TDS_ENCRYPTION_STRICT:
1418 : return TDS7_ENCRYPT_NOT_SUP;
1419 1564 : case TDS_ENCRYPTION_REQUIRE:
1420 : return TDS7_ENCRYPT_ON;
1421 : }
1422 : return TDS7_ENCRYPT_OFF;
1423 : }
1424 : #endif
1425 :
1426 : static TDSRET
1427 3188 : tds71_do_login(TDSSOCKET * tds, TDSLOGIN* login)
1428 : {
1429 : int i, pkt_len;
1430 9564 : const char *instance_name = tds_dstr_isempty(&login->instance_name) ? "MSSQLServer" : tds_dstr_cstr(&login->instance_name);
1431 3188 : TDS_USMALLINT instance_name_len = strlen(instance_name) + 1;
1432 : TDS_CHAR crypt_flag;
1433 3188 : unsigned int start_pos = 21;
1434 : TDSRET ret;
1435 3188 : bool mars_replied = false;
1436 :
1437 : #define START_POS 21
1438 : #define UI16BE(n) ((n) >> 8), ((n) & 0xffu)
1439 : #define SET_UI16BE(i,n) TDS_PUT_UA2BE(&buf[i],n)
1440 3188 : TDS_UCHAR buf[] = {
1441 : /* netlib version */
1442 : 0, UI16BE(START_POS), UI16BE(6),
1443 : /* encryption */
1444 : 1, UI16BE(START_POS + 6), UI16BE(1),
1445 : /* instance */
1446 : 2, UI16BE(START_POS + 6 + 1), UI16BE(0),
1447 : /* process id */
1448 : 3, UI16BE(0), UI16BE(4),
1449 : /* MARS enables */
1450 : 4, UI16BE(0), UI16BE(1),
1451 : /* end */
1452 : 0xff
1453 : };
1454 : static const TDS_UCHAR netlib8[] = { 8, 0, 1, 0x55, 0, 0 };
1455 : static const TDS_UCHAR netlib9[] = { 9, 0, 0, 0, 0, 0 };
1456 :
1457 : TDS_UCHAR *p;
1458 :
1459 3188 : TDS_TINYINT encryption_level = login->encryption_level;
1460 :
1461 3188 : SET_UI16BE(13, instance_name_len);
1462 3188 : if (!IS_TDS72_PLUS(tds->conn)) {
1463 1602 : SET_UI16BE(16, START_POS + 6 + 1 + instance_name_len);
1464 : /* strip MARS setting */
1465 1602 : buf[20] = 0xff;
1466 : } else {
1467 1586 : start_pos += 5;
1468 : #undef START_POS
1469 : #define START_POS 26
1470 1586 : SET_UI16BE(1, START_POS);
1471 1586 : SET_UI16BE(6, START_POS + 6);
1472 1586 : SET_UI16BE(11, START_POS + 6 + 1);
1473 1586 : SET_UI16BE(16, START_POS + 6 + 1 + instance_name_len);
1474 1586 : SET_UI16BE(21, START_POS + 6 + 1 + instance_name_len + 4);
1475 : }
1476 :
1477 : assert(start_pos >= 21 && start_pos <= sizeof(buf));
1478 3188 : assert(buf[start_pos-1] == 0xff);
1479 :
1480 3188 : if (encryption_level == TDS_ENCRYPTION_DEFAULT)
1481 : encryption_level = TDS_ENCRYPTION_REQUEST;
1482 :
1483 : /* all encrypted */
1484 1584 : if (encryption_level == TDS_ENCRYPTION_STRICT)
1485 0 : TDS_PROPAGATE(tds_ssl_init(tds, true));
1486 :
1487 : /*
1488 : * fix a problem with mssql2k which doesn't like
1489 : * packet splitted during SSL handshake
1490 : */
1491 3188 : if (tds->out_buf_max < 4096)
1492 3188 : tds_realloc_socket(tds, 4096);
1493 :
1494 : /* do prelogin */
1495 3188 : tds->out_flag = TDS71_PRELOGIN;
1496 :
1497 3188 : tds_put_n(tds, buf, start_pos);
1498 : /* netlib version */
1499 3188 : tds_put_n(tds, IS_TDS72_PLUS(tds->conn) ? netlib9 : netlib8, 6);
1500 : /* encryption */
1501 : #if !defined(HAVE_GNUTLS) && !defined(HAVE_OPENSSL)
1502 : /* not supported */
1503 : tds_put_byte(tds, TDS7_ENCRYPT_NOT_SUP);
1504 : #else
1505 3188 : tds_put_byte(tds, tds7_get_encryption_byte(encryption_level));
1506 : #endif
1507 : /* instance */
1508 3188 : tds_put_n(tds, instance_name, instance_name_len);
1509 : /* pid */
1510 3188 : tds_put_int(tds, getpid());
1511 : /* MARS (1 enabled) */
1512 3188 : if (IS_TDS72_PLUS(tds->conn))
1513 : #if ENABLE_ODBC_MARS
1514 793 : tds_put_byte(tds, login->mars);
1515 1594 : login->mars = 0;
1516 : #else
1517 793 : tds_put_byte(tds, 0);
1518 : #endif
1519 3188 : TDS_PROPAGATE(tds_flush_packet(tds));
1520 :
1521 : /* now process reply from server */
1522 3188 : ret = tds_read_packet(tds);
1523 3188 : if (ret <= 0 || tds->in_flag != TDS_REPLY)
1524 : return TDS_FAIL;
1525 3186 : login->server_is_valid = 1;
1526 3186 : pkt_len = tds->in_len - tds->in_pos;
1527 :
1528 : /* the only thing we care is flag */
1529 3186 : p = tds->in_buf + tds->in_pos;
1530 : /* default 2, no certificate, no encryption */
1531 3186 : crypt_flag = TDS7_ENCRYPT_NOT_SUP;
1532 18298 : for (i = 0;; i += 5) {
1533 : TDS_UCHAR type;
1534 : int off, len;
1535 :
1536 18298 : if (i >= pkt_len)
1537 : return TDS_FAIL;
1538 18298 : type = p[i];
1539 18298 : if (type == 0xff)
1540 : break;
1541 : /* check packet */
1542 15112 : if (i+4 >= pkt_len)
1543 : return TDS_FAIL;
1544 15112 : off = TDS_GET_UA2BE(&p[i+1]);
1545 15112 : len = TDS_GET_UA2BE(&p[i+3]);
1546 15112 : if (off > pkt_len || (off+len) > pkt_len)
1547 : return TDS_FAIL;
1548 15112 : if (type == 1 && len >= 1) {
1549 3186 : crypt_flag = p[off];
1550 : }
1551 15112 : if (IS_TDS72_PLUS(tds->conn) && type == 4 && len >= 1) {
1552 1584 : mars_replied = true;
1553 : #if ENABLE_ODBC_MARS
1554 792 : login->mars = !!p[off];
1555 : #endif
1556 : }
1557 : }
1558 : /* we readed all packet */
1559 3186 : tds->in_pos += pkt_len;
1560 : /* TODO some mssql version do not set last packet, update tds according */
1561 :
1562 3186 : tdsdump_log(TDS_DBG_INFO1, "detected crypt flag %d\n", crypt_flag);
1563 :
1564 3186 : if (!mars_replied && encryption_level != TDS_ENCRYPTION_STRICT)
1565 1602 : tds->conn->tds_version = 0x701;
1566 :
1567 : /* if server does not have certificate or TLS already setup do normal login */
1568 3186 : if (crypt_flag == TDS7_ENCRYPT_NOT_SUP || encryption_level == TDS_ENCRYPTION_STRICT) {
1569 : /* unless we wanted encryption and got none, then fail */
1570 830 : if (encryption_level == TDS_ENCRYPTION_REQUIRE)
1571 : return TDS_FAIL;
1572 :
1573 830 : return tds7_send_login(tds, login);
1574 : }
1575 :
1576 : /*
1577 : * if server has a certificate it requires at least a crypted login
1578 : * (even if data is not encrypted)
1579 : */
1580 :
1581 : /* here we have to do encryption ... */
1582 :
1583 2356 : TDS_PROPAGATE(tds_ssl_init(tds, false));
1584 :
1585 : /* server just encrypt the first packet */
1586 2356 : if (crypt_flag == TDS7_ENCRYPT_OFF)
1587 792 : tds->conn->encrypt_single_packet = 1;
1588 :
1589 2356 : ret = tds7_send_login(tds, login);
1590 :
1591 : /* if flag is TDS7_ENCRYPT_OFF(0) it means that after login server continue not encrypted */
1592 2356 : if (crypt_flag == TDS7_ENCRYPT_OFF || TDS_FAILED(ret))
1593 792 : tds_ssl_deinit(tds->conn);
1594 :
1595 : return ret;
1596 : }
1597 :
|