Use "fork_child" rather than "child_process" - on Win32, "child_process"
[obnox/wireshark/wip.git] / packet-tds.c
1 /* packet-tds.c
2  * Routines for TDS NetLib dissection
3  * Copyright 2000-2002, Brian Bruns <camber@ais.org>
4  * Copyright 2002, Steve Langasek <vorlon@netexpress.net>
5  *
6  * $Id: packet-tds.c,v 1.23 2004/01/05 01:18:53 guy Exp $
7  *
8  * Ethereal - Network traffic analyzer
9  * By Gerald Combs <gerald@ethereal.com>
10  * Copyright 1998 Gerald Combs
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25  */
26
27 /*
28  * The NETLIB protocol is a small blocking protocol designed to allow TDS
29  * to be placed within different transports (TCP, DECNet, IPX/SPX).  A
30  * NETLIB packet starts with an eight byte header containing:
31  *
32  *      a one-byte packet type field;
33  *
34  *      a one-byte status field;
35  *
36  *      a two-byte big-endian size field giving the size of the packet,
37  *      including the header;
38  *
39  *      a two-byte big-endian channel number, used when multiple sessions
40  *      are being multiplexed on a single connection;
41  *
42  *      a one-byte packet number, giving "the frame number of a multiplexed
43  *      message, modulo 256";
44  *
45  *      a one-byte window, which is the number of frames to be sent
46  *      before an acknowledgment message is received.
47  *
48  * followed by payload whose size is the value in the size field minus
49  * 8.
50  *
51  * Microsoft Network Monitor 2.x dissects the 4 byte field (and indicates
52  * that the one-byte last packet indicator also contains other bits).
53  *
54  * The TDS protocol consists of a number of protocol data units (PDUs) that
55  * appear to be assembled from NETLIB packets, in the form of zero or more
56  * NETLIB packets with the last packet indicator clear and a final NETLIB
57  * packet with the last packet indicator set.  The type of the TDS PDU is
58  * specified by the packet type field of the NETLIB header (presumably that
59  * field has the same value for all NETLIB packets that make up a TDS PDU).
60  *
61  * The "server response" PDU consists of a sequence of multiple items, each
62  * one beginning with a one byte type field at the start of the PDU.  Some
63  * items are fixed length, some are variable length with a two byte size
64  * field following the item type, and then there is TDS_ROW_TOKEN in which
65  * size is determined by analyzing the result set returned from the server.
66  * This in effect means that we are hopelessly lost if we haven't seen the
67  * result set.  Also, TDS 4/5 is byte order negotiable, which is specified
68  * in the login packet.  We can attempt to determine it later on, but not
69  * with 100% accuracy.
70  *
71  * Some preliminary documentation on the packet format can be found at
72  * http://www.freetds.org/tds.html
73  *
74  * Some more information can be found in
75  * http://download.nai.com/products/media/sniffer/support/sdos/sybase.pdf
76  *
77  * Much of this code was originally developed for the FreeTDS project.
78  * http://www.freetds.org
79  */
80
81 /*
82  * Excerpts from Brian's posting to ethereal-dev:
83  *
84  * The TDS Protocol is actually a protocol within a protocol.  On the outside
85  * there is netlib which is not so much a encapsulation as a blocking of the
86  * data, typically to 512 or 4096 bytes.  Between this are the protocol data
87  * units for TDS.  Netlib packets may be split over real packets, multiple
88  * netlib packets may appear in single real packets.  TDS PDUs may be split
89  * over netlib packets (and real packets) and most certainly can appear
90  * multiple times within a netlib packet.
91  *
92  * Because of this, I abandoned my earlier attempt at making two dissectors,
93  * one for netlib and one for TDS. Counterintuitively, a single dissector
94  * turned out to be simpler than splitting it up.
95  *
96  * Here are some of the (hefty) limitations of the current code
97  *
98  * . We currently do not handle netlib headers that cross packet boundaries.
99  *   This should be an easy fix.
100  * . I probably could have used the packet reassembly stuff, but I started
101  *   this at version 0.8.20, so c'est la vie. It wouldn't have covered the
102  *   netlib stuff anyway, so no big loss.
103  * . The older two layer version of the code dissected the PDU's, but the new
104  *   version does not yet, it only labels the names. I need an elegant way to
105  *   deal with dissecting data crossing (netlib and tcp) packet boundries.  I
106  *   think I have one, but ran out of time to do it.
107  * . It will only work on little endian platforms.  Or rather I should say,
108  *   the client that was captured must be little endian.  TDS 7.0/8.0 is
109  *   always LE; for TDS 4.2/5.0 look in the code for tvb_get_le*() functions,
110  *   there are fields in the login packet which determine byte order.
111  * . result sets that span netlib packets are not working
112  * . TDS 7 and 4.2 result sets are not working yet
113  *
114  * All that said, the code does deal gracefully with different boudary
115  * conditions and what remains are the easier bits, IMHO.
116  *
117  * XXX - "real packets" means "TCP segments", for TCP.
118  *
119  * XXX - is it *REALLY* true that you can have more than one TDS PDU (as
120  * opposed to more than one server response item) per NETLIB packet?  Or is
121  * all the data in a NETLIB packet put into a single TDS PDU?  If so, then
122  * we can reassemble NETLIB packets using the standard TCP desegmentation
123  * code, and can reassemble TDS PDUs using "fragment_add_seq_check()",
124  * and more cleanly separate the NETLIB and TDS dissectors (although the
125  * "is this NETLIB" heuristic would have to look at TDS information past
126  * the NETLIB header, in order to make the heuristic strong enough not
127  * to get too many false positives; note that the heuristic should reject
128  * any putative NETLIB packet with a length field with a value < 8).
129  *
130  * That would substantially clean the dissector up, eliminating most of
131  * the per-packet data (we might still need information to handle
132  * TDS_ROW_TOKEN), getting rid of the stuff to handle data split across
133  * TCP segment boundaries in favor of simple reassembly code, and
134  * fixing some otherwise nasty-looking crashing bugs.
135  *
136  * NOTE: we assume that all the data in a NETLIB packet *can* be put into
137  * a single TDS PTU, so that we have separate reassembly of NETLIB
138  * packets and TDS PDUs; it seems to work, and it really did clean stuff
139  * up and fix crashes.
140  */
141
142 #ifdef HAVE_CONFIG_H
143 # include "config.h"
144 #endif
145
146 #include <stdio.h>
147 #include <stdlib.h>
148 #include <string.h>
149 #include <ctype.h>
150
151 #include <glib.h>
152
153 #include <epan/packet.h>
154 #include <epan/conversation.h>
155 #include <epan/strutil.h>
156
157 #include "packet-smb-common.h"
158 #include "packet-frame.h"
159 #include "reassemble.h"
160 #include "prefs.h"
161
162 #define TDS_QUERY_PKT        1
163 #define TDS_LOGIN_PKT        2
164 #define TDS_RPC_PKT          3
165 #define TDS_RESP_PKT         4
166 #define TDS_RAW_PKT          5
167 #define TDS_CANCEL_PKT       6
168 #define TDS_BULK_DATA_PKT    7
169 #define TDS_OPEN_CHN_PKT     8
170 #define TDS_CLOSE_CHN_PKT    9
171 #define TDS_RES_ERROR_PKT   10
172 #define TDS_LOG_CHN_ACK_PKT 11
173 #define TDS_ECHO_PKT        12
174 #define TDS_LOGOUT_CHN_PKT  13
175 #define TDS_QUERY5_PKT      15  /* or "Normal tokenized request or response */
176 #define TDS_LOGIN7_PKT      16  /* or "Urgent tokenized request or response */
177 #define TDS_XXX7_PKT        18  /* seen in one capture */
178
179 #define is_valid_tds_type(x) ((x) >= TDS_QUERY_PKT && (x) <= TDS_XXX7_PKT)
180
181 /* The following constants are imported more or less directly from FreeTDS */
182
183 #define TDS5_DYN_TOKEN      231  /* 0xE7    TDS 5.0 only              */
184 #define TDS5_DYNRES_TOKEN   236  /* 0xEC    TDS 5.0 only              */
185 #define TDS5_DYN3_TOKEN     215  /* 0xD7    TDS 5.0 only              */
186 #define TDS_LANG_TOKEN       33  /* 0x21    TDS 5.0 only              */
187 #define TDS_CLOSE_TOKEN     113  /* 0x71    TDS 5.0 only? ct_close()  */
188 #define TDS_RET_STAT_TOKEN  121  /* 0x79                              */
189 #define TDS_124_TOKEN       124  /* 0x7C    TDS 4.2 only - TDS_PROCID */
190 #define TDS7_RESULT_TOKEN   129  /* 0x81    TDS 7.0 only              */
191 #define TDS_COL_NAME_TOKEN  160  /* 0xA0    TDS 4.2 only              */
192 #define TDS_COL_INFO_TOKEN  161  /* 0xA1    TDS 4.2 only - TDS_COLFMT */
193 /*#define  TDS_TABNAME   164 */
194 /*#define  TDS_COL_INFO   165 */
195 #define TDS_167_TOKEN       167  /* 0xA7                              */
196 #define TDS_168_TOKEN       168  /* 0xA8                              */
197 #define TDS_ORDER_BY_TOKEN  169  /* 0xA9    TDS_ORDER                 */
198 #define TDS_ERR_TOKEN       170  /* 0xAA                              */
199 #define TDS_MSG_TOKEN       171  /* 0xAB                              */
200 #define TDS_PARAM_TOKEN     172  /* 0xAC    RETURNVALUE?              */
201 #define TDS_LOGIN_ACK_TOKEN 173  /* 0xAD                              */
202 #define TDS_174_TOKEN       174  /* 0xAE    TDS_CONTROL               */
203 #define TDS_ROW_TOKEN       209  /* 0xD1                              */
204 #define TDS_CMP_ROW_TOKEN   211  /* 0xD3                              */
205 #define TDS_CAP_TOKEN       226  /* 0xE2                              */
206 #define TDS_ENV_CHG_TOKEN   227  /* 0xE3                              */
207 #define TDS_EED_TOKEN       229  /* 0xE5                              */
208 #define TDS_AUTH_TOKEN      237  /* 0xED                              */
209 #define TDS_RESULT_TOKEN    238  /* 0xEE                              */
210 #define TDS_DONE_TOKEN      253  /* 0xFD    TDS_DONE                  */
211 #define TDS_DONEPROC_TOKEN  254  /* 0xFE    TDS_DONEPROC              */
212 #define TDS_DONEINPROC_TOKEN 255  /* 0xFF    TDS_DONEINPROC            */
213
214 #define SYBCHAR      47   /* 0x2F */
215 #define SYBVARCHAR   39   /* 0x27 */
216 #define SYBINTN      38   /* 0x26 */
217 #define SYBINT1      48   /* 0x30 */
218 #define SYBINT2      52   /* 0x34 */
219 #define SYBINT4      56   /* 0x38 */
220 #define SYBINT8     127   /* 0x7F */
221 #define SYBFLT8      62   /* 0x3E */
222 #define SYBDATETIME  61   /* 0x3D */
223 #define SYBBIT       50   /* 0x32 */
224 #define SYBTEXT      35   /* 0x23 */
225 #define SYBNTEXT     99   /* 0x63 */
226 #define SYBIMAGE     34   /* 0x22 */
227 #define SYBMONEY4    122  /* 0x7A */
228 #define SYBMONEY     60   /* 0x3C */
229 #define SYBDATETIME4 58   /* 0x3A */
230 #define SYBREAL      59   /* 0x3B */
231 #define SYBBINARY    45   /* 0x2D */
232 #define SYBVOID      31   /* 0x1F */
233 #define SYBVARBINARY 37   /* 0x25 */
234 #define SYBNVARCHAR  103  /* 0x67 */
235 #define SYBBITN      104  /* 0x68 */
236 #define SYBNUMERIC   108  /* 0x6C */
237 #define SYBDECIMAL   106  /* 0x6A */
238 #define SYBFLTN      109  /* 0x6D */
239 #define SYBMONEYN    110  /* 0x6E */
240 #define SYBDATETIMN  111  /* 0x6F */
241 #define XSYBCHAR     167  /* 0xA7 */
242 #define XSYBVARCHAR  175  /* 0xAF */
243 #define XSYBNVARCHAR 231  /* 0xE7 */
244 #define XSYBNCHAR    239  /* 0xEF */
245 #define SYBUNIQUE    0x24
246 #define SYBVARIANT   0x62
247
248 #define is_fixed_coltype(x) (x==SYBINT1    || \
249                         x==SYBINT2      || \
250                         x==SYBINT4      || \
251                         x==SYBINT8      || \
252                         x==SYBREAL       || \
253                         x==SYBFLT8      || \
254                         x==SYBDATETIME  || \
255                         x==SYBDATETIME4 || \
256                         x==SYBBIT       || \
257                         x==SYBMONEY     || \
258                         x==SYBMONEY4    || \
259                         x==SYBUNIQUE)
260
261 /* Initialize the protocol and registered fields */
262 static int proto_tds = -1;
263 static int hf_tds_type = -1;
264 static int hf_tds_status = -1;
265 static int hf_tds_size = -1;
266 static int hf_tds_channel = -1;
267 static int hf_tds_packet_number = -1;
268 static int hf_tds_window = -1;
269 static int hf_tds_reassembled_in = -1;
270 static int hf_tds_fragments = -1;
271 static int hf_tds_fragment = -1;
272 static int hf_tds_fragment_overlap = -1;
273 static int hf_tds_fragment_overlap_conflict = -1;
274 static int hf_tds_fragment_multiple_tails = -1;
275 static int hf_tds_fragment_too_long_fragment = -1;
276 static int hf_tds_fragment_error = -1;
277
278 static int hf_tds7_login_total_size = -1;
279 static int hf_tds7_version = -1;
280 static int hf_tds7_packet_size = -1;
281 static int hf_tds7_client_version = -1;
282 static int hf_tds7_client_pid = -1;
283 static int hf_tds7_connection_id = -1;
284 static int hf_tds7_option_flags1 = -1;
285 static int hf_tds7_option_flags2 = -1;
286 static int hf_tds7_sql_type_flags = -1;
287 static int hf_tds7_reserved_flags = -1;
288 static int hf_tds7_time_zone = -1;
289 static int hf_tds7_collation = -1;
290 static int hf_tds7_message = -1;
291
292 /* Initialize the subtree pointers */
293 static gint ett_tds = -1;
294 static gint ett_tds_fragments = -1;
295 static gint ett_tds_fragment = -1;
296 static gint ett_tds_token = -1;
297 static gint ett_tds7_login = -1;
298 static gint ett_tds7_hdr = -1;
299
300 /* Desegmentation of Netlib buffers crossing TCP segment boundaries. */
301 static gboolean tds_desegment = TRUE;
302
303 static const fragment_items tds_frag_items = {
304         &ett_tds_fragment,
305         &ett_tds_fragments,
306         &hf_tds_fragments,
307         &hf_tds_fragment,
308         &hf_tds_fragment_overlap,
309         &hf_tds_fragment_overlap_conflict,
310         &hf_tds_fragment_multiple_tails,
311         &hf_tds_fragment_too_long_fragment,
312         &hf_tds_fragment_error,
313         &hf_tds_reassembled_in,
314         "fragments"
315 };
316
317 /* Tables for reassembly of fragments. */
318 static GHashTable *tds_fragment_table = NULL;
319 static GHashTable *tds_reassembled_table = NULL;
320
321 /* defragmentation of multi-buffer TDS PDUs */
322 static gboolean tds_defragment = TRUE;
323
324 static dissector_handle_t tds_tcp_handle;
325 static dissector_handle_t ntlmssp_handle;
326 static dissector_handle_t data_handle;
327
328 /* These correspond to the netlib packet type field */
329 static const value_string packet_type_names[] = {
330         {TDS_QUERY_PKT,  "Query Packet"},
331         {TDS_LOGIN_PKT,  "Login Packet"},
332         {TDS_RPC_PKT,    "Remote Procedure Call Packet"},
333         {TDS_RESP_PKT,   "Response Packet"},
334         {TDS_CANCEL_PKT, "Cancel Packet"},
335         {TDS_QUERY5_PKT, "TDS5 Query Packet"},
336         {TDS_LOGIN7_PKT, "TDS7/8 Login Packet"},
337         {0, NULL},
338 };
339
340 /* The status field */
341
342 #define is_valid_tds_status(x) ((x) <= STATUS_EVENT_NOTIFICATION)
343
344 #define STATUS_NOT_LAST_BUFFER          0x00
345 #define STATUS_LAST_BUFFER              0x01
346 #define STATUS_ATTN_REQUEST_ACK         0x02
347 #define STATUS_ATTN_REQUEST             0x03
348 #define STATUS_EVENT_NOTIFICATION       0x04
349
350 static const value_string status_names[] = {
351         {STATUS_NOT_LAST_BUFFER,    "Not last buffer"},
352         {STATUS_LAST_BUFFER,        "Last buffer in request or response"},
353         {STATUS_ATTN_REQUEST_ACK,   "Acknowledgment of last attention request"},
354         {STATUS_ATTN_REQUEST,       "Attention request"},
355         {STATUS_EVENT_NOTIFICATION, "Event notification"},
356         {0, NULL},
357 };
358
359 /* The one byte token at the start of each TDS PDU */
360 static const value_string token_names[] = {
361         {TDS5_DYN_TOKEN, "Dynamic SQL"},
362         {TDS5_DYNRES_TOKEN, "Dynamic Results"},
363         {TDS5_DYN3_TOKEN, "Dynamic (Unknown)"},
364         {TDS_LANG_TOKEN, "Language"},
365         {TDS_CLOSE_TOKEN, "Close Connection"},
366         {TDS_RET_STAT_TOKEN, "Return Status"},
367         {TDS_124_TOKEN, "Proc ID"},
368         {TDS7_RESULT_TOKEN, "Results"},
369         {TDS_COL_NAME_TOKEN, "Column Names"},
370         {TDS_COL_INFO_TOKEN, "Column Info"},
371         {TDS_167_TOKEN, "Unknown (167)"},
372         {TDS_168_TOKEN, "Unknown (168)"},
373         {TDS_ORDER_BY_TOKEN, "Order By"},
374         {TDS_ERR_TOKEN, "Error Message"},
375         {TDS_MSG_TOKEN, "Info Message"},
376         {TDS_PARAM_TOKEN, "Paramater"},
377         {TDS_LOGIN_ACK_TOKEN, "Login Acknowledgement"},
378         {TDS_174_TOKEN, "Unknown (174)"},
379         {TDS_ROW_TOKEN, "Row"},
380         {TDS_CMP_ROW_TOKEN, "Compute Row"},
381         {TDS_CAP_TOKEN, "Capabilities"},
382         {TDS_ENV_CHG_TOKEN, "Environment Change"},
383         {TDS_EED_TOKEN, "Extended Error"},
384         {TDS_AUTH_TOKEN, "Authentication"},
385         {TDS_RESULT_TOKEN, "Results"},
386         {TDS_DONE_TOKEN, "Done"},
387         {TDS_DONEPROC_TOKEN, "Done Proc"},
388         {TDS_DONEINPROC_TOKEN, "Done In Proc"},
389         {0, NULL},
390 };
391
392 static const value_string env_chg_names[] = {
393         {1, "Database"},
394         {2, "Language"},
395         {3, "Sort Order"},
396         {4, "Blocksize"},
397         {5, "Unicode Locale ID"},
398         {6, "Unicode Comparison Style"},
399         {7, "Collation Info"},
400         {0, NULL},
401 };
402
403 static const value_string login_field_names[] = {
404         {0, "Client Name"},
405         {1, "Username"},
406         {2, "Password"},
407         {3, "App Name"},
408         {4, "Server Name"},
409         {5, "Unknown1"},
410         {6, "Library Name"},
411         {7, "Locale"},
412         {8, "Unknown2"},
413         {0, NULL},
414 };
415
416
417 #define MAX_COLUMNS 256
418
419 /*
420  * This is where we store the column information to be used in decoding the
421  * TDS_ROW_TOKEN tokens.
422  */
423 struct _tds_col {
424      gchar name[256];
425      guint16 utype;
426      guint8 ctype;
427      guint csize;
428 };
429
430 struct _netlib_data {
431         guint num_cols;
432         struct _tds_col *columns[MAX_COLUMNS];
433 };
434
435 struct tds7_login_packet_hdr {
436         guint32 total_packet_size;
437         guint32 tds_version;
438         guint32 packet_size;
439         guint32 client_version;
440         guint32 client_pid;
441         guint32 connection_id;
442         guint8  option_flags1;
443         guint8  option_flags2;
444         guint8  sql_type_flags;
445         guint8  reserved_flags;
446         guint32 time_zone;
447         guint32 collation;
448 };
449
450 /* all the standard memory management stuff */
451 #define tds_column_length (sizeof(struct _tds_col))
452 #define tds_column_init_count 10
453
454 static GMemChunk *tds_column = NULL;
455
456 /* support routines */
457 static void
458 dissect_tds_ntlmssp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
459     guint offset, guint length)
460 {
461         tvbuff_t *ntlmssp_tvb;
462
463         ntlmssp_tvb = tvb_new_subset(tvb, offset, length, length);
464         call_dissector(ntlmssp_handle, ntlmssp_tvb, pinfo, tree);
465 }
466
467 static void
468 dissect_tds7_login(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
469 {
470         guint offset, i, offset2, len;
471         gboolean is_unicode = TRUE;
472         char *val;
473
474         proto_item *login_hdr;
475         proto_tree *login_tree;
476         proto_item *header_hdr;
477         proto_tree *header_tree;
478         proto_item *length_hdr;
479         proto_tree *length_tree;
480         
481         struct tds7_login_packet_hdr td7hdr;
482         gint length_remaining;
483
484
485         /* create display subtree for the protocol */
486         offset = 0;
487         login_hdr = proto_tree_add_text(tree, tvb, offset, -1, "TDS7 Login Packet");
488         login_tree = proto_item_add_subtree(login_hdr, ett_tds7_login);
489         header_hdr = proto_tree_add_text(login_tree, tvb, offset, 36, "Login Packet Header");
490         header_tree = proto_item_add_subtree(header_hdr, ett_tds7_hdr);
491         
492         td7hdr.total_packet_size = tvb_get_letohl(tvb, offset);
493         proto_tree_add_uint(header_tree, hf_tds7_login_total_size, tvb, offset, sizeof(td7hdr.total_packet_size), td7hdr.total_packet_size);
494         offset += sizeof(td7hdr.total_packet_size);
495         
496         td7hdr.tds_version = tvb_get_ntohl(tvb, offset);
497         proto_tree_add_uint(header_tree, hf_tds7_version, tvb, offset, sizeof(td7hdr.tds_version), td7hdr.tds_version);
498         offset += sizeof(td7hdr.tds_version);
499         
500         td7hdr.packet_size = tvb_get_ntohl(tvb, offset);
501         proto_tree_add_uint(header_tree, hf_tds7_packet_size, tvb, offset, sizeof(td7hdr.packet_size), td7hdr.packet_size);
502         offset += sizeof(td7hdr.packet_size);
503         
504         td7hdr.client_version = tvb_get_ntohl(tvb, offset);
505         proto_tree_add_uint(header_tree, hf_tds7_client_version, tvb, offset, sizeof(td7hdr.client_version), td7hdr.client_version);
506         offset += sizeof(td7hdr.client_version);
507         
508         td7hdr.client_pid = tvb_get_letohl(tvb, offset);
509         proto_tree_add_uint(header_tree, hf_tds7_client_pid, tvb, offset, sizeof(td7hdr.client_pid), td7hdr.client_pid);
510         offset += sizeof(td7hdr.client_pid);
511
512         td7hdr.connection_id= tvb_get_letohl(tvb, offset);
513         proto_tree_add_uint(header_tree, hf_tds7_connection_id, tvb, offset, sizeof(td7hdr.connection_id), td7hdr.connection_id);
514         offset += sizeof(td7hdr.connection_id);
515         
516         td7hdr.option_flags1 = tvb_get_guint8(tvb, offset);
517         proto_tree_add_uint(header_tree, hf_tds7_option_flags1, tvb, offset, sizeof(td7hdr.option_flags1), td7hdr.option_flags1);
518         offset += sizeof(td7hdr.option_flags1);
519         
520         td7hdr.option_flags2 = tvb_get_guint8(tvb, offset);
521         proto_tree_add_uint(header_tree, hf_tds7_option_flags2, tvb, offset, sizeof(td7hdr.option_flags2), td7hdr.option_flags2);
522         offset += sizeof(td7hdr.option_flags2);
523
524         td7hdr.sql_type_flags = tvb_get_guint8(tvb, offset);    
525         proto_tree_add_uint(header_tree, hf_tds7_sql_type_flags, tvb, offset, sizeof(td7hdr.sql_type_flags), td7hdr.sql_type_flags);
526         offset += sizeof(td7hdr.sql_type_flags);
527
528         td7hdr.reserved_flags = tvb_get_guint8(tvb, offset);
529         proto_tree_add_uint(header_tree, hf_tds7_reserved_flags, tvb, offset, sizeof(td7hdr.reserved_flags), td7hdr.reserved_flags);
530         offset += sizeof(td7hdr.reserved_flags);
531         
532         td7hdr.time_zone = tvb_get_ntohl(tvb, offset);
533         proto_tree_add_uint(header_tree, hf_tds7_time_zone, tvb, offset, sizeof(td7hdr.time_zone), td7hdr.time_zone);
534         offset += sizeof(td7hdr.time_zone);
535
536         td7hdr.collation = tvb_get_ntohl(tvb, offset);
537         proto_tree_add_uint(header_tree, hf_tds7_collation, tvb, offset, sizeof(td7hdr.collation), td7hdr.collation);
538         offset += sizeof(td7hdr.collation);
539
540         length_hdr = proto_tree_add_text(login_tree, tvb, offset, 50, "Lengths and offsets");
541         length_tree = proto_item_add_subtree(length_hdr, ett_tds7_hdr);
542
543         for (i = 0; i < 9; i++) {
544                 offset2 = tvb_get_letohs(tvb, offset + i*4);
545                 len = tvb_get_letohs(tvb, offset + i*4 + 2);
546                 proto_tree_add_text(length_tree, tvb, offset + i*4, 2,
547                     "%s offset: %u",
548                     val_to_str(i, login_field_names, "Unknown"),
549                     offset2);
550                 proto_tree_add_text(length_tree, tvb, offset + i*4 + 2, 2,
551                         "%s length: %u",
552                         val_to_str(i, login_field_names, "Unknown"),
553                         len);
554                 if (len != 0) {
555                         if (is_unicode == TRUE) {
556                                 val = tvb_fake_unicode(tvb, offset2, len,
557                                     TRUE);
558                                 len *= 2;
559                         } else
560                                 val = tvb_get_string(tvb, offset2, len);
561                         proto_tree_add_text(login_tree, tvb, offset2, len,
562                                 "%s: %s",
563                                 val_to_str(i, login_field_names, "Unknown"),
564                                 val);
565                         g_free(val);
566                 }
567         }
568
569         length_remaining = tvb_reported_length_remaining(tvb, offset2 + len);
570         if (length_remaining > 0) {
571                 dissect_tds_ntlmssp(tvb, pinfo, login_tree, offset2 + len,
572                     length_remaining);
573         }
574 }
575
576 static int get_size_by_coltype(int servertype)
577 {
578    switch(servertype)
579    {
580       case SYBINT1:        return 1;  break;
581       case SYBINT2:        return 2;  break;
582       case SYBINT4:        return 4;  break;
583       case SYBINT8:        return 8;  break;
584       case SYBREAL:        return 4;  break;
585       case SYBFLT8:        return 8;  break;
586       case SYBDATETIME:    return 8;  break;
587       case SYBDATETIME4:   return 4;  break;
588       case SYBBIT:         return 1;  break;
589       case SYBBITN:        return 1;  break;
590       case SYBMONEY:       return 8;  break;
591       case SYBMONEY4:      return 4;  break;
592       case SYBUNIQUE:      return 16; break;
593       default:             return -1; break;
594    }
595 }
596 static int tds_is_fixed_token(int token)
597 {
598      switch (token) {
599           case TDS_DONE_TOKEN:
600           case TDS_DONEPROC_TOKEN:
601           case TDS_DONEINPROC_TOKEN:
602           case TDS_RET_STAT_TOKEN:
603                return 1;
604           default:
605                return 0;
606      }
607 }
608 static int tds_get_token_size(int token)
609 {
610      switch(token) {
611           case TDS_DONE_TOKEN:
612           case TDS_DONEPROC_TOKEN:
613           case TDS_DONEINPROC_TOKEN:
614                return 8;
615           case TDS_RET_STAT_TOKEN:
616                return 4;
617           case TDS_124_TOKEN:
618                return 8;
619           default:
620                return 0;
621      }
622 }
623
624 # if 0
625 /*
626  * data_to_string should take column data and turn it into something we can
627  * display on the tree.
628  */
629 static char *data_to_string(void *data, guint col_type, guint col_size)
630 {
631    static char  result[256];
632    guint i;
633
634    switch(col_type) {
635       case SYBVARCHAR:
636          /* strncpy(result, (char *)data, col_size); */
637          for (i=0;i<col_size && i<(256-1);i++)
638                 if (!isprint(((char *)data)[i])) result[i]='.';
639                 else result[i]=((char *)data)[i];
640          result[i] = '\0';
641          break;
642       case SYBINT2:
643          sprintf(result, "%d", *(short *)data);
644          break;
645       case SYBINT4:
646          sprintf(result, "%d", *(int *)data);
647          break;
648       default:
649          sprintf(result, "Unexpected column_type %d", col_type);
650          break;
651    }
652    return result;
653 }
654 #endif
655
656 /*
657  * Since rows are special PDUs in that they are not fixed and lack a size field,
658  * the length must be computed using the column information seen in the result
659  * PDU. This function does just that.
660  */
661 static size_t
662 tds_get_row_size(tvbuff_t *tvb, struct _netlib_data *nl_data, guint offset)
663 {
664         guint cur, i, csize;
665
666         cur = offset;
667         for (i = 0; i < nl_data->num_cols; i++) {
668                 if (!is_fixed_coltype(nl_data->columns[i]->ctype)) {
669                         csize = tvb_get_guint8(tvb, cur);
670                         cur++;
671                 } else
672                         csize = get_size_by_coltype(nl_data->columns[i]->ctype);
673                 cur += csize;
674         }
675
676         return (cur - offset + 1);
677 }
678
679 /*
680  * Read the results token and store the relevant information in the
681  * _netlib_data structure for later use (see tds_get_row_size).
682  */
683 static gboolean
684 read_results_tds5(tvbuff_t *tvb, struct _netlib_data *nl_data, guint offset)
685 {
686         guint len, name_len;
687         guint cur;
688         guint i;
689
690         len = tvb_get_letohs(tvb, offset+1);
691         cur = offset + 3;
692
693         /*
694          * This would be the logical place to check for little/big endianess
695          * if we didn't see the login packet.
696          */
697         nl_data->num_cols = tvb_get_letohs(tvb, cur);
698         if (nl_data->num_cols > MAX_COLUMNS) {
699                 nl_data->num_cols = 0;
700                 return FALSE;
701         }
702
703         cur += 2;
704
705         for (i = 0; i < nl_data->num_cols; i++) {
706                 nl_data->columns[i] = g_mem_chunk_alloc(tds_column);
707                 name_len = tvb_get_guint8(tvb,cur);
708                 cur ++;
709                 cur += name_len;
710
711                 cur++; /* unknown */
712
713                 nl_data->columns[i]->utype = tvb_get_letohs(tvb, cur);
714                 cur += 2;
715
716                 cur += 2; /* unknown */
717
718                 nl_data->columns[i]->ctype = tvb_get_guint8(tvb,cur);
719                 cur++;
720
721                 if (!is_fixed_coltype(nl_data->columns[i]->ctype)) {
722                         nl_data->columns[i]->csize = tvb_get_guint8(tvb,cur);
723                         cur ++;
724                 } else {
725                         nl_data->columns[i]->csize =
726                             get_size_by_coltype(nl_data->columns[i]->ctype);
727                 }
728                 cur++; /* unknown */
729         }
730         return TRUE;
731 }
732
733 /*
734  * If the packet type from the netlib header is a login packet, then dig into
735  * the packet to see if this is a supported TDS version and verify the otherwise
736  * weak heuristics of the netlib check.
737  */
738 static gboolean
739 netlib_check_login_pkt(tvbuff_t *tvb, guint offset, packet_info *pinfo, guint8 type)
740 {
741         guint tds_major, bytes_avail;
742
743         bytes_avail = tvb_length(tvb) - offset;
744         /*
745          * we have two login packet styles, one for TDS 4.2 and 5.0
746          */
747         if (type==TDS_LOGIN_PKT) {
748                 /* Use major version number to validate TDS 4/5 login
749                  * packet */
750
751                 /* Login packet is first in stream and should not be fragmented...
752                  * if it is we are screwed */
753                 if (bytes_avail < 467) return FALSE;
754                 tds_major = tvb_get_guint8(tvb, 466);
755                 if (tds_major != 4 && tds_major != 5) {
756                         return FALSE;
757                 }
758         /*
759          * and one added by Microsoft in SQL Server 7
760          */
761         } else if (type==TDS_LOGIN7_PKT) {
762                 if (bytes_avail < 16) return FALSE;
763                 tds_major = tvb_get_guint8(tvb, 15);
764                 if (tds_major != 0x70 && tds_major != 0x80) {
765                         return FALSE;
766                 }
767         } else if (type==TDS_QUERY5_PKT) {
768                 if (bytes_avail < 9) return FALSE;
769                 /* if this is a TDS 5.0 query check the token */
770                 if (tvb_get_guint8(tvb, 8) != TDS_LANG_TOKEN) {
771                         return FALSE;
772                 }
773         /* check if it is MS SQL default port */
774         } else if (pinfo->srcport != 1433 &&
775                 pinfo->destport != 1433) {
776                 /* otherwise, we can not ensure this is netlib */
777                 /* beyond a reasonable doubt.                  */
778                         return FALSE;
779         }
780         return TRUE;
781 }
782
783 static void
784 dissect_tds_env_chg(tvbuff_t *tvb, guint offset, guint token_sz,
785     proto_tree *tree)
786 {
787         guint8 env_type;
788         guint old_len, new_len, old_len_offset;
789         char *new_val = NULL, *old_val = NULL;
790         guint32 string_offset;
791         gboolean is_unicode = FALSE;
792         guint16 collate_codepage, collate_flags;
793         guint8 collate_charset_id;
794
795         env_type = tvb_get_guint8(tvb, offset);
796         proto_tree_add_text(tree, tvb, offset, 1, "Type: %u (%s)", env_type,
797                 val_to_str(env_type, env_chg_names, "Unknown"));
798
799         new_len = tvb_get_guint8(tvb, offset+1);
800         old_len_offset = offset + new_len + 2;
801         old_len = tvb_get_guint8(tvb, old_len_offset);
802
803         /*
804          * If our lengths plus the lengths of the type and the lengths
805          * don't add up to the token size, it must be UCS2.
806          */
807         if (old_len + new_len + 3 != token_sz) {
808                 is_unicode = TRUE;
809                 old_len_offset = offset + (new_len * 2) + 2;
810                 old_len = tvb_get_guint8(tvb, old_len_offset);
811         }
812
813         proto_tree_add_text(tree, tvb, offset + 1, 1, "New Value Length: %u",
814             new_len);
815         if (new_len) {
816                 if (env_type != 7) { /* if it's not 'Collation Info - which is not textual! */
817                         string_offset = offset + 2;
818                         if (is_unicode == TRUE) {
819                                 new_val = tvb_fake_unicode(tvb, string_offset,
820                                         new_len, TRUE);
821                                 new_len *= 2;
822                         } else
823                                 new_val = tvb_get_string(tvb, string_offset, new_len);
824                         proto_tree_add_text(tree, tvb, string_offset, new_len,
825                                 "New Value: %s", new_val);
826                         g_free(new_val);
827                 }
828                 else { /* parse collation info structure. From http://www.freetds.org/tds.html#collate */
829                         offset +=2;
830                         collate_codepage = tvb_get_letohs(tvb, offset);
831                         proto_tree_add_text(tree, tvb, offset, 2, "Codepage: %u" , collate_codepage);
832                         offset += 2;
833                         collate_flags = tvb_get_letohs(tvb, offset);
834                         proto_tree_add_text(tree, tvb, offset, 2, "Flags: 0x%x", collate_flags);
835                         offset += 2;
836                         collate_charset_id = tvb_get_guint8(tvb, offset);
837                         proto_tree_add_text(tree, tvb, offset, 1, "Charset ID: %u", collate_charset_id);
838                         offset +=1;
839                 }
840         }
841
842         proto_tree_add_text(tree, tvb, old_len_offset, 1, "Old Value Length: %u",
843             old_len);
844         if (old_len) {
845                 string_offset = old_len_offset + 1;
846                 if (is_unicode == TRUE) {
847                         old_val = tvb_fake_unicode(tvb, string_offset,
848                             old_len, TRUE);
849                         old_len *= 2;
850                 } else
851                         old_val = tvb_get_string(tvb, string_offset, old_len);
852                 proto_tree_add_text(tree, tvb, string_offset, old_len,
853                     "Old Value: %s", old_val);
854                 g_free(old_val);
855          }
856 }
857
858 static void
859 dissect_tds_msg_token(tvbuff_t *tvb, guint offset, guint token_sz, proto_tree *tree)
860 {
861         guint16 msg_len;
862         guint8 srvr_len;
863         char *msg;
864         gboolean is_unicode = FALSE;
865
866         proto_tree_add_text(tree, tvb, offset, 4, "SQL Message Number: %d", tvb_get_letohl(tvb, offset));
867         offset += 4;
868         proto_tree_add_text(tree, tvb, offset, 1, "State: %u", tvb_get_guint8(tvb, offset));
869         offset +=1;
870         proto_tree_add_text(tree, tvb, offset, 1, "Level: %u", tvb_get_guint8(tvb, offset));
871         offset +=1;
872         
873         msg_len = tvb_get_letohs(tvb, offset);
874         proto_tree_add_text(tree, tvb, offset, 2, "Message length: %u characters", msg_len);
875         offset +=2;
876         
877         srvr_len = tvb_get_guint8(tvb, offset + msg_len);
878         
879         if(msg_len + srvr_len + 9U + 3U != token_sz) /* 9 is the length of message number (4), state (1), level (1), msg_len (2), srvr_len (1) fields */
880                 is_unicode = TRUE;
881
882         if(is_unicode) {
883                 msg = tvb_fake_unicode(tvb, offset, msg_len, TRUE);
884                 msg_len *= 2;
885         } else {
886                 msg = tvb_get_string(tvb, offset, msg_len);
887         }
888         proto_tree_add_string(tree, hf_tds7_message, tvb, offset, msg_len, msg);
889         g_free(msg);
890         offset += msg_len;
891
892         proto_tree_add_text(tree, tvb, offset, 1, "Server name length: %u characters", srvr_len);
893         offset +=1;
894         
895         if (is_unicode) {
896                 msg = tvb_fake_unicode(tvb, offset, srvr_len, TRUE);
897                 srvr_len *=2;
898         } else {
899                 msg = tvb_get_string(tvb, offset, srvr_len);
900         }
901         proto_tree_add_text(tree, tvb, offset, srvr_len, "Server name: %s", msg);
902         g_free(msg);
903 }
904
905 static void
906 dissect_tds_err_token(tvbuff_t *tvb, guint offset, guint token_sz, proto_tree *tree)
907 {
908         guint16 msg_len;
909         guint8 srvr_len;
910         char *msg;
911         gboolean is_unicode = FALSE;
912
913         proto_tree_add_text(tree, tvb, offset, 4, "SQL Error Number: %d", tvb_get_letohl(tvb, offset));
914         offset += 4;
915         proto_tree_add_text(tree, tvb, offset, 1, "State: %u", tvb_get_guint8(tvb, offset));
916         offset +=1;
917         proto_tree_add_text(tree, tvb, offset, 1, "Level: %u", tvb_get_guint8(tvb, offset));
918         offset +=1;
919
920         msg_len = tvb_get_letohs(tvb, offset);
921         proto_tree_add_text(tree, tvb, offset, 1, "Error length: %u characters", msg_len);
922         offset +=2;
923
924         srvr_len = tvb_get_guint8(tvb, offset + msg_len);
925         
926         if(msg_len + srvr_len + 9U + 3U != token_sz) /* 9 is the length of message number (4), state (1), level (1), msg_len (2), srvr_len (1) fields */
927                 is_unicode = TRUE;
928
929         if(is_unicode) {
930                 msg = tvb_fake_unicode(tvb, offset, msg_len, TRUE);
931                 msg_len *= 2;
932         } else {
933                 msg = tvb_get_string(tvb, offset, msg_len);
934         }
935         proto_tree_add_text(tree, tvb, offset, msg_len, "Error: %s", format_text(msg, strlen(msg)));
936         g_free(msg);
937         offset += msg_len;
938
939         proto_tree_add_text(tree, tvb, offset, 1, "Server name length: %u characters", srvr_len);
940         offset +=1;
941         
942         if (is_unicode) {
943                 msg = tvb_fake_unicode(tvb, offset, srvr_len, TRUE);
944                 srvr_len *=2;
945         } else {
946                 msg = tvb_get_string(tvb, offset, srvr_len);
947         }
948         proto_tree_add_text(tree, tvb, offset, srvr_len, "Server name: %s", msg);
949         g_free(msg);
950 }
951
952 static void
953 dissect_tds_done_token(tvbuff_t *tvb, guint offset, proto_tree *tree)
954 {
955         proto_tree_add_text(tree, tvb, offset, 2, "bit flag");
956         offset += 2;
957         proto_tree_add_text(tree, tvb, offset, 2, "unknown");
958         offset += 2;
959         proto_tree_add_text(tree, tvb, offset, 4, "row count: %u", tvb_get_letohl(tvb, offset));
960         offset += 2;
961 }
962
963 static void
964 dissect_tds_rpc(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree)
965 {
966         int offset = 0;
967         guint len;
968         const char *val;
969
970         /*
971          * RPC name.
972          * XXX - how can we determine whether this is ASCII or Unicode?
973          */
974         len = tvb_get_letohs(tvb, offset);
975         proto_tree_add_text(tree, tvb, offset, 2, "RPC Name Length: %u", len);
976         offset += 2;
977         if (len != 0) {
978                 val = tvb_fake_unicode(tvb, offset, len, TRUE);
979                 len *= 2;
980                 proto_tree_add_text(tree, tvb, offset, len, "RPC Name: %s",
981                     val);
982                 offset += len;
983         }
984         
985         proto_tree_add_text(tree, tvb, offset, -1, "Unknown data");
986 }
987
988 static void
989 dissect_tds_resp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
990 {
991         int offset = 0;
992         proto_item *token_item;
993         proto_tree *token_tree;
994         guint pos, token_sz = 0;
995         guint8 token;
996         struct _netlib_data nl_data;
997         gint length_remaining;
998
999         memset(&nl_data, '\0', sizeof nl_data);
1000
1001         /*
1002          * Until we reach the end of the packet, read tokens.
1003          */
1004         pos = offset;
1005         while (tvb_reported_length_remaining(tvb, pos) > 0) {
1006                 /* our token */
1007                 token = tvb_get_guint8(tvb, pos);
1008
1009                 if (tds_is_fixed_token(token)) {
1010                         token_sz = tds_get_token_size(token) + 1;
1011                 } else if (token == TDS_ROW_TOKEN) {
1012                         /*
1013                          * Rows are special; they have no size field and
1014                          * aren't fixed length.
1015                          */
1016                         token_sz = tds_get_row_size(tvb, &nl_data, pos + 1);
1017                 } else
1018                         token_sz = tvb_get_letohs(tvb, pos + 1) + 3;
1019
1020                 length_remaining = tvb_ensure_length_remaining(tvb, pos);
1021                 if (token_sz > (guint)length_remaining)
1022                         token_sz = (guint)length_remaining;
1023
1024                 token_item = proto_tree_add_text(tree, tvb, pos, token_sz,
1025                     "Token 0x%02x %s", token,
1026                     val_to_str(token, token_names, "Unknown Token Type"));
1027                 token_tree = proto_item_add_subtree(token_item, ett_tds_token);
1028
1029                 /*
1030                  * If it's a variable token, put the length field in here
1031                  * instead of replicating this for each token subdissector.
1032                  */
1033                 if (!tds_is_fixed_token(token) && token != TDS_ROW_TOKEN) {
1034                         proto_tree_add_text(token_tree, tvb, pos+1, 2,
1035                             "Length: %u", tvb_get_letohs(tvb, pos+1));
1036                 }
1037
1038                 switch (token) {
1039
1040                 case TDS_RESULT_TOKEN:
1041                         /*
1042                          * If it's a result token, we need to stash the
1043                          * column info.
1044                          */
1045                         read_results_tds5(tvb, &nl_data, pos);
1046                         break;
1047
1048                 case TDS_ENV_CHG_TOKEN:
1049                         dissect_tds_env_chg(tvb, pos + 3, token_sz - 3,
1050                             token_tree);
1051                         break;
1052
1053                 case TDS_AUTH_TOKEN:
1054                         dissect_tds_ntlmssp(tvb, pinfo, token_tree, pos + 3,
1055                             token_sz - 3);
1056                         break;
1057                 case TDS_MSG_TOKEN:
1058                         dissect_tds_msg_token(tvb, pos + 3, token_sz - 3, token_tree);
1059                         break;
1060                 case TDS_ERR_TOKEN:
1061                         dissect_tds_err_token(tvb, pos + 3, token_sz - 3, token_tree);
1062                         break;
1063                 case TDS_DONE_TOKEN:
1064                         dissect_tds_done_token(tvb, pos + 1, token_tree);
1065                         break;
1066                 }
1067
1068                 /* and step to the end of the token, rinse, lather, repeat */
1069                 pos += token_sz;
1070         }
1071 }
1072
1073 static void
1074 dissect_netlib_buffer(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
1075 {
1076         int offset = 0;
1077         proto_item *tds_item = NULL;
1078         proto_tree *tds_tree = NULL;
1079         guint8 type;
1080         guint8 status;
1081         guint16 size;
1082         guint16 channel;
1083         guint8 packet_number;
1084         gboolean save_fragmented;
1085         int len;
1086         fragment_data *fd_head;
1087         tvbuff_t *next_tvb;
1088
1089         if (tree) {
1090                 /* create display subtree for the protocol */
1091                 tds_item = proto_tree_add_item(tree, proto_tds, tvb, offset, -1,
1092                     FALSE);
1093
1094                 tds_tree = proto_item_add_subtree(tds_item, ett_tds);
1095         }
1096         type = tvb_get_guint8(tvb, offset);
1097         if (tree) {
1098                 proto_tree_add_uint(tds_tree, hf_tds_type, tvb, offset, 1,
1099                     type);
1100         }
1101         status = tvb_get_guint8(tvb, offset + 1);
1102         if (tree) {
1103                 proto_tree_add_uint(tds_tree, hf_tds_status, tvb, offset + 1, 1,
1104                     status);
1105         }
1106         size = tvb_get_ntohs(tvb, offset + 2);
1107         if (tree) {
1108                 proto_tree_add_uint(tds_tree, hf_tds_size, tvb, offset + 2, 2,
1109                         size);
1110         }
1111         channel = tvb_get_ntohs(tvb, offset + 4);
1112         if (tree) {
1113                 proto_tree_add_uint(tds_tree, hf_tds_channel, tvb, offset + 4, 2,
1114                         channel);
1115         }
1116         packet_number = tvb_get_guint8(tvb, offset + 6);
1117         if (tree) {
1118                 proto_tree_add_uint(tds_tree, hf_tds_packet_number, tvb, offset + 6, 1,
1119                         packet_number);
1120                 proto_tree_add_item(tds_tree, hf_tds_window, tvb, offset + 7, 1,
1121                         FALSE);
1122         }
1123         offset += 8;    /* skip Netlib header */
1124
1125         /*
1126          * Deal with fragmentation.
1127          */
1128         save_fragmented = pinfo->fragmented;
1129         if (tds_defragment &&
1130             (packet_number > 1 || status == STATUS_NOT_LAST_BUFFER)) {
1131                 if (status == STATUS_NOT_LAST_BUFFER) {
1132                         if (check_col(pinfo->cinfo, COL_INFO))
1133                                 col_append_str(pinfo->cinfo, COL_INFO,
1134                                     " (Not last buffer)");
1135                 }
1136                 len = tvb_reported_length_remaining(tvb, offset);
1137                 /*
1138                  * XXX - I've seen captures that start with a login
1139                  * packet with a sequence number of 2.
1140                  */
1141                 fd_head = fragment_add_seq_check(tvb, offset, pinfo, channel,
1142                     tds_fragment_table, tds_reassembled_table,
1143                     packet_number - 1, len, status == STATUS_NOT_LAST_BUFFER);
1144                 next_tvb = process_reassembled_data(tvb, offset, pinfo,
1145                     "Reassembled TDS", fd_head, &tds_frag_items, NULL,
1146                     tds_tree);
1147         } else {
1148                 /*
1149                  * If this isn't the last buffer, just show it as a fragment.
1150                  * (XXX - it'd be nice to dissect it if it's the first
1151                  * buffer, but we'd need to do reassembly in order to
1152                  * discover that.)
1153                  *
1154                  * If this is the last buffer, dissect it.
1155                  * (XXX - it'd be nice to show it as a fragment if it's part
1156                  * of a fragmented message, but we'd need to do reassembly
1157                  * in order to discover that.)
1158                  */
1159                 if (status == STATUS_NOT_LAST_BUFFER)
1160                         next_tvb = NULL;
1161                 else {
1162                         next_tvb = tvb_new_subset(tvb, offset, -1, -1);
1163                 }
1164         }
1165         if (next_tvb != NULL) {
1166                 switch (type) {
1167
1168                 case TDS_RPC_PKT:
1169                         dissect_tds_rpc(next_tvb, pinfo, tds_tree);
1170                         break;
1171
1172                 case TDS_RESP_PKT:
1173                         dissect_tds_resp(next_tvb, pinfo, tds_tree);
1174                         break;
1175
1176                 case TDS_LOGIN7_PKT:
1177                         dissect_tds7_login(next_tvb, pinfo, tds_tree);
1178                         break;
1179
1180                 default:
1181                         proto_tree_add_text(tds_tree, next_tvb, 0, -1,
1182                             "TDS Packet");
1183                         break;
1184                 }
1185         } else {
1186                 next_tvb = tvb_new_subset (tvb, offset, -1, -1);
1187                 call_dissector(data_handle, next_tvb, pinfo, tds_tree);
1188         }
1189 }
1190
1191 static void
1192 dissect_tds_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
1193 {
1194         volatile gboolean first_time = TRUE;
1195         volatile int offset = 0;
1196         guint length_remaining;
1197         guint8 type;
1198         guint16 plen;
1199         guint length;
1200         tvbuff_t *next_tvb;
1201         proto_item *tds_item = NULL;
1202         proto_tree *tds_tree = NULL;
1203
1204         while (tvb_reported_length_remaining(tvb, offset) != 0) {
1205                 length_remaining = tvb_ensure_length_remaining(tvb, offset);
1206
1207                 /*
1208                  * Can we do reassembly?
1209                  */
1210                 if (tds_desegment && pinfo->can_desegment) {
1211                         /*
1212                          * Yes - is the fixed-length part of the PDU
1213                          * split across segment boundaries?
1214                          */
1215                         if (length_remaining < 8) {
1216                                 /*
1217                                  * Yes.  Tell the TCP dissector where the
1218                                  * data for this message starts in the data
1219                                  * it handed us, and how many more bytes we
1220                                  * need, and return.
1221                                  */
1222                                 pinfo->desegment_offset = offset;
1223                                 pinfo->desegment_len = 8 - length_remaining;
1224                                 return;
1225                         }
1226                 }
1227
1228                 type = tvb_get_guint8(tvb, offset);
1229
1230                 /*
1231                  * Get the length of the PDU.
1232                  */
1233                 plen = tvb_get_ntohs(tvb, offset + 2);
1234                 if (plen < 8) {
1235                         /*
1236                          * The length is less than the header length.
1237                          * Put in the type, status, and length, and
1238                          * report the length as bogus.
1239                          */
1240                         if (tree) {
1241                                 /* create display subtree for the protocol */
1242                                 tds_item = proto_tree_add_item(tree, proto_tds,
1243                                     tvb, offset, -1, FALSE);
1244
1245                                 tds_tree = proto_item_add_subtree(tds_item,
1246                                     ett_tds);
1247                                 proto_tree_add_uint(tds_tree, hf_tds_type, tvb,
1248                                     offset, 1, type);
1249                                 proto_tree_add_item(tds_tree, hf_tds_status,
1250                                     tvb, offset + 1, 1, FALSE);
1251                                 proto_tree_add_uint_format(tds_tree,
1252                                     hf_tds_size, tvb, offset + 2, 2, plen,
1253                                     "Size: %u (bogus, should be >= 8)", plen);
1254                         }
1255
1256                         /*
1257                          * Give up - we can't dissect any more of this
1258                          * data.
1259                          */
1260                         break;
1261                 }
1262
1263                 /*
1264                  * Can we do reassembly?
1265                  */
1266                 if (tds_desegment && pinfo->can_desegment) {
1267                         /*
1268                          * Yes - is the PDU split across segment boundaries?
1269                          */
1270                         if (length_remaining < plen) {
1271                                 /*
1272                                  * Yes.  Tell the TCP dissector where the
1273                                  * data for this message starts in the data
1274                                  * it handed us, and how many more bytes we
1275                                  * need, and return.
1276                                  */
1277                                 pinfo->desegment_offset = offset;
1278                                 pinfo->desegment_len = plen - length_remaining;
1279                                 return;
1280                         }
1281                 }
1282
1283                 if (first_time) {
1284                         if (check_col(pinfo->cinfo, COL_PROTOCOL))
1285                                 col_set_str(pinfo->cinfo, COL_PROTOCOL, "TDS");
1286
1287                         /*
1288                          * Set the packet description based on its TDS packet
1289                          * type.
1290                          */
1291                         if (check_col(pinfo->cinfo, COL_INFO)) {
1292                                 col_add_str(pinfo->cinfo, COL_INFO,
1293                                     val_to_str(type, packet_type_names,
1294                                       "Unknown Packet Type: %u"));
1295                         }
1296                         first_time = FALSE;
1297                 }
1298
1299                 /*
1300                  * Construct a tvbuff containing the amount of the payload
1301                  * we have available.  Make its reported length the amount
1302                  * of data in the PDU.
1303                  *
1304                  * XXX - if reassembly isn't enabled. the subdissector will
1305                  * throw a BoundsError exception, rather than a
1306                  * ReportedBoundsError exception.  We really want a tvbuff
1307                  * where the length is "length", the reported length is
1308                  * "plen", and the "if the snapshot length were infinite"
1309                  * length is the minimum of the reported length of the tvbuff
1310                  * handed to us and "plen", with a new type of exception
1311                  * thrown if the offset is within the reported length but
1312                  * beyond that third length, with that exception getting the
1313                  * "Unreassembled Packet" error.
1314                  */
1315                 length = length_remaining;
1316                 if (length > plen)
1317                         length = plen;
1318                 next_tvb = tvb_new_subset(tvb, offset, length, plen);
1319
1320                 /*
1321                  * Dissect the Netlib buffer.
1322                  *
1323                  * Catch the ReportedBoundsError exception; if this
1324                  * particular Netlib buffer happens to get a
1325                  * ReportedBoundsError exception, that doesn't mean
1326                  * that we should stop dissecting PDUs within this frame
1327                  * or chunk of reassembled data.
1328                  *
1329                  * If it gets a BoundsError, we can stop, as there's nothing
1330                  * more to see, so we just re-throw it.
1331                  */
1332                 TRY {
1333                         dissect_netlib_buffer(next_tvb, pinfo, tree);
1334                 }
1335                 CATCH(BoundsError) {
1336                         RETHROW;
1337                 }
1338                 CATCH(ReportedBoundsError) {
1339                         show_reported_bounds_error(tvb, pinfo, tree);
1340                 }
1341                 ENDTRY;
1342
1343                 /*
1344                  * Step to the next Netlib buffer.
1345                  */
1346                 offset += plen;
1347         }
1348 }
1349
1350 static gboolean
1351 dissect_tds_tcp_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
1352 {
1353         int offset = 0;
1354         guint8 type;
1355         guint8 status;
1356         guint16 plen;
1357         conversation_t *conv;
1358
1359         /*
1360          * If we don't have even enough data for a Netlib header,
1361          * just say it's not TDS.
1362          */
1363         if (!tvb_bytes_exist(tvb, offset, 8))
1364                 return FALSE;
1365
1366         /*
1367          * Quickly scan all the data we have in order to see if
1368          * everything in it looks like Netlib traffic.
1369          */
1370         while (tvb_bytes_exist(tvb, offset, 1)) {
1371                 /*
1372                  * Check the type field.
1373                  */
1374                 type = tvb_get_guint8(tvb, offset);
1375                 if (!is_valid_tds_type(type))
1376                         return FALSE;
1377
1378                 /*
1379                  * Check the status field, if it's present.
1380                  */
1381                 if (!tvb_bytes_exist(tvb, offset + 1, 1))
1382                         break;
1383                 status = tvb_get_guint8(tvb, offset + 1);
1384                 if (!is_valid_tds_status(status))
1385                         return FALSE;
1386
1387                 /*
1388                  * Get the length of the PDU.
1389                  */
1390                 if (!tvb_bytes_exist(tvb, offset + 2, 2))
1391                         break;
1392                 plen = tvb_get_ntohs(tvb, offset + 2);
1393                 if (plen < 8) {
1394                         /*
1395                          * The length is less than the header length.
1396                          * That's bogus.
1397                          */
1398                         return FALSE;
1399                 }
1400
1401                 /*
1402                  * If we're at the beginning of the segment, check the
1403                  * payload if it's a login packet.
1404                  */
1405                 if (offset == 0) {
1406                         if (!netlib_check_login_pkt(tvb, offset, pinfo, type))
1407                                 return FALSE;
1408                 }
1409
1410                 /*
1411                  * Step to the next Netlib buffer.
1412                  */
1413                 offset += plen;
1414         }
1415
1416         /*
1417          * OK, it passes the test; assume the rest of this conversation
1418          * is TDS.
1419          */
1420         conv = find_conversation(&pinfo->src, &pinfo->dst, pinfo->ptype,
1421             pinfo->srcport, pinfo->destport, 0);
1422         if (conv == NULL) {
1423                 /*
1424                  * No conversation exists yet - create one.
1425                  */
1426                 conv = conversation_new(&pinfo->src, &pinfo->dst,
1427                     pinfo->ptype, pinfo->srcport, pinfo->destport, 0);
1428         }
1429         conversation_set_dissector(conv, tds_tcp_handle);
1430
1431         /*
1432          * Now dissect it as TDS.
1433          */
1434         dissect_tds_tcp(tvb, pinfo, tree);
1435         return TRUE;
1436 }
1437
1438 static void
1439 tds_init(void)
1440 {
1441         /*
1442          * Initialize the fragment and reassembly tables.
1443          */
1444         fragment_table_init(&tds_fragment_table);
1445         reassembled_table_init(&tds_reassembled_table);
1446
1447         /*
1448          * Reinitialize the chunks of data for remembering row
1449          * information.
1450          */
1451         if (tds_column)
1452                 g_mem_chunk_destroy(tds_column);
1453
1454         tds_column = g_mem_chunk_new("tds_column", tds_column_length,
1455                 tds_column_init_count * tds_column_length,
1456                 G_ALLOC_AND_FREE);
1457 }
1458
1459 /* Register the protocol with Ethereal */
1460
1461 /* this format is required because a script is used to build the C function
1462    that calls all the protocol registration.
1463 */
1464
1465 void
1466 proto_register_netlib(void)
1467 {
1468         static hf_register_info hf[] = {
1469                 { &hf_tds_type,
1470                         { "Type",           "tds.type",
1471                         FT_UINT8, BASE_HEX, VALS(packet_type_names), 0x0,
1472                         "Packet Type", HFILL }
1473                 },
1474                 { &hf_tds_status,
1475                         { "Status",         "tds.status",
1476                         FT_UINT8, BASE_DEC, VALS(status_names), 0x0,
1477                         "Frame status", HFILL }
1478                 },
1479                 { &hf_tds_size,
1480                         { "Size",           "tds.size",
1481                         FT_UINT16, BASE_DEC, NULL, 0x0,
1482                         "Packet Size", HFILL }
1483                 },
1484                 { &hf_tds_channel,
1485                         { "Channel",        "tds.channel",
1486                         FT_UINT16, BASE_DEC, NULL, 0x0,
1487                         "Channel Number", HFILL }
1488                 },
1489                 { &hf_tds_packet_number,
1490                         { "Packet Number",  "tds.packet_number",
1491                         FT_UINT8, BASE_DEC, NULL, 0x0,
1492                         "Packet Number", HFILL }
1493                 },
1494                 { &hf_tds_window,
1495                         { "Window",         "tds.window",
1496                         FT_UINT8, BASE_DEC, NULL, 0x0,
1497                         "Window", HFILL }
1498                 },
1499                 { &hf_tds_fragment_overlap,
1500                         { "Segment overlap",    "tds.fragment.overlap",
1501                         FT_BOOLEAN, BASE_NONE, NULL, 0x0,
1502                         "Fragment overlaps with other fragments", HFILL }
1503                 },
1504                 { &hf_tds_fragment_overlap_conflict,
1505                         { "Conflicting data in fragment overlap", "tds.fragment.overlap.conflict",
1506                         FT_BOOLEAN, BASE_NONE, NULL, 0x0,
1507                         "Overlapping fragments contained conflicting data", HFILL }
1508                 },
1509                 { &hf_tds_fragment_multiple_tails,
1510                         { "Multiple tail fragments found", "tds.fragment.multipletails",
1511                         FT_BOOLEAN, BASE_NONE, NULL, 0x0,
1512                         "Several tails were found when defragmenting the packet", HFILL }
1513                 },
1514                 { &hf_tds_fragment_too_long_fragment,
1515                         { "Segment too long",   "tds.fragment.toolongfragment",
1516                         FT_BOOLEAN, BASE_NONE, NULL, 0x0,
1517                         "Segment contained data past end of packet", HFILL }
1518                 },
1519                 { &hf_tds_fragment_error,
1520                         { "Defragmentation error",      "tds.fragment.error",
1521                         FT_FRAMENUM, BASE_NONE, NULL, 0x0,
1522                         "Defragmentation error due to illegal fragments", HFILL }
1523                 },
1524                 { &hf_tds_fragment,
1525                         { "TDS Fragment",       "tds.fragment",
1526                         FT_FRAMENUM, BASE_NONE, NULL, 0x0,
1527                         "TDS Fragment", HFILL }
1528                 },
1529                 { &hf_tds_fragments,
1530                         { "TDS Fragments",      "tds.fragments",
1531                         FT_NONE, BASE_NONE, NULL, 0x0,
1532                         "TDS Fragments", HFILL }
1533                 },
1534                 { &hf_tds_reassembled_in,
1535                         { "Reassembled TDS in frame", "tds.reassembled_in",
1536                         FT_FRAMENUM, BASE_NONE, NULL, 0x0,
1537                         "This TDS packet is reassembled in this frame", HFILL }
1538                 },
1539                 { &hf_tds7_login_total_size,
1540                         { "Total Packet Length", "tds7login.total_len",
1541                         FT_UINT32, BASE_DEC, NULL, 0x0,
1542                         "TDS7 Login Packet total packet length", HFILL }
1543                 },
1544                 { &hf_tds7_version,
1545                         { "TDS version", "tds7login.version",
1546                         FT_UINT32, BASE_HEX, NULL, 0x0,
1547                         "TDS version", HFILL }
1548                 },
1549                 { &hf_tds7_packet_size,
1550                         { "Packet Size", "tds7login.packet_size",
1551                         FT_UINT32, BASE_DEC, NULL, 0x0,
1552                         "Packet size", HFILL }
1553                 },
1554                 { &hf_tds7_client_version,
1555                         { "Client version", "tds7login.client_version",
1556                         FT_UINT32, BASE_DEC, NULL, 0x0,
1557                         "Client version", HFILL }
1558                 },
1559                 { &hf_tds7_client_pid,
1560                         { "Client PID", "tds7login.client_pid",
1561                         FT_UINT32, BASE_DEC, NULL, 0x0,
1562                         "Client PID", HFILL }
1563                 },
1564                 { &hf_tds7_connection_id,
1565                         { "Connection ID", "tds7login.connection_id",
1566                         FT_UINT32, BASE_DEC, NULL, 0x0,
1567                         "Connection ID", HFILL }
1568                 },
1569                 { &hf_tds7_option_flags1,
1570                         { "Option Flags 1", "tds7login.option_flags1",
1571                         FT_UINT8, BASE_HEX, NULL, 0x0,
1572                         "Option Flags 1", HFILL }
1573                 },
1574                 { &hf_tds7_option_flags2,
1575                         { "Option Flags 2", "tds7login.option_flags2",
1576                         FT_UINT8, BASE_HEX, NULL, 0x0,
1577                         "Option Flags 2", HFILL }
1578                 },
1579                 { &hf_tds7_sql_type_flags,
1580                         { "SQL Type Flags", "tds7login.sql_type_flags",
1581                         FT_UINT8, BASE_HEX, NULL, 0x0,
1582                         "SQL Type Flags", HFILL }
1583                 },
1584                 { &hf_tds7_reserved_flags,
1585                         { "Reserved Flags", "tds7login.reserved_flags",
1586                         FT_UINT8, BASE_HEX, NULL, 0x0,
1587                         "reserved flags", HFILL }
1588                 },
1589                 { &hf_tds7_time_zone,
1590                         { "Time Zone", "tds7login.time_zone",
1591                         FT_UINT32, BASE_HEX, NULL, 0x0,
1592                         "Time Zone", HFILL }
1593                 },
1594                 { &hf_tds7_collation,
1595                         { "Collation", "tds7login.collation",
1596                         FT_UINT32, BASE_HEX, NULL, 0x0,
1597                         "Collation", HFILL }
1598                 },
1599                 { &hf_tds7_message,
1600                         { "Message", "tds7.message", 
1601                         FT_STRING, BASE_NONE, NULL, 0x0, 
1602                         "", HFILL }
1603                 },
1604         };
1605         static gint *ett[] = {
1606                 &ett_tds,
1607                 &ett_tds_fragments,
1608                 &ett_tds_fragment,
1609                 &ett_tds_token,
1610                 &ett_tds7_login,
1611                 &ett_tds7_hdr,
1612         };
1613         module_t *tds_module;
1614
1615 /* Register the protocol name and description */
1616         proto_tds = proto_register_protocol("Tabular Data Stream",
1617             "TDS", "tds");
1618
1619 /* Required function calls to register the header fields and subtrees used */
1620         proto_register_field_array(proto_tds, hf, array_length(hf));
1621         proto_register_subtree_array(ett, array_length(ett));
1622
1623         tds_tcp_handle = create_dissector_handle(dissect_tds_tcp, proto_tds);
1624
1625         tds_module = prefs_register_protocol(proto_tds, NULL);
1626         prefs_register_bool_preference(tds_module, "desegment_buffers",
1627             "Desegment all TDS buffers spanning multiple TCP segments",
1628             "Whether the TDS dissector should desegment all TDS buffers spanning multiple TCP segments",
1629             &tds_desegment);
1630         prefs_register_bool_preference(tds_module, "defragment",
1631             "Defragment all TDS messages with multiple buffers",
1632             "Whether the TDS dissector should defragment all messages spanning multiple Netlib buffers",
1633             &tds_defragment);
1634
1635         register_init_routine(tds_init);
1636 }
1637
1638 /* If this dissector uses sub-dissector registration add a registration routine.
1639    This format is required because a script is used to find these routines and
1640    create the code that calls these routines.
1641 */
1642 void
1643 proto_reg_handoff_tds(void)
1644 {
1645         /* dissector_add("tcp.port", 1433, dissect_tds,
1646             proto_tds); */
1647         heur_dissector_add("tcp", dissect_tds_tcp_heur, proto_tds);
1648
1649         ntlmssp_handle = find_dissector("ntlmssp");
1650         data_handle = find_dissector("data");
1651 }