[CIFS] fix memory leak in cifs session info struct on reconnect
[linux-2.6] / fs / cifs / connect.c
1 /*
2  *   fs/cifs/connect.c
3  *
4  *   Copyright (C) International Business Machines  Corp., 2002,2006
5  *   Author(s): Steve French (sfrench@us.ibm.com)
6  *
7  *   This library is free software; you can redistribute it and/or modify
8  *   it under the terms of the GNU Lesser General Public License as published
9  *   by the Free Software Foundation; either version 2.1 of the License, or
10  *   (at your option) any later version.
11  *
12  *   This library is distributed in the hope that it will be useful,
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
15  *   the GNU Lesser General Public License for more details.
16  *
17  *   You should have received a copy of the GNU Lesser General Public License
18  *   along with this library; if not, write to the Free Software
19  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
20  */
21 #include <linux/fs.h>
22 #include <linux/net.h>
23 #include <linux/string.h>
24 #include <linux/list.h>
25 #include <linux/wait.h>
26 #include <linux/ipv6.h>
27 #include <linux/pagemap.h>
28 #include <linux/ctype.h>
29 #include <linux/utsname.h>
30 #include <linux/mempool.h>
31 #include <linux/delay.h>
32 #include <linux/completion.h>
33 #include <linux/pagevec.h>
34 #include <asm/uaccess.h>
35 #include <asm/processor.h>
36 #include "cifspdu.h"
37 #include "cifsglob.h"
38 #include "cifsproto.h"
39 #include "cifs_unicode.h"
40 #include "cifs_debug.h"
41 #include "cifs_fs_sb.h"
42 #include "ntlmssp.h"
43 #include "nterr.h"
44 #include "rfc1002pdu.h"
45 #include "cn_cifs.h"
46
47 #define CIFS_PORT 445
48 #define RFC1001_PORT 139
49
50 static DECLARE_COMPLETION(cifsd_complete);
51
52 extern void SMBencrypt(unsigned char *passwd, unsigned char *c8,
53                        unsigned char *p24);
54 extern void SMBNTencrypt(unsigned char *passwd, unsigned char *c8,
55                          unsigned char *p24);
56
57 extern mempool_t *cifs_req_poolp;
58
59 struct smb_vol {
60         char *username;
61         char *password;
62         char *domainname;
63         char *UNC;
64         char *UNCip;
65         char *in6_addr;  /* ipv6 address as human readable form of in6_addr */
66         char *iocharset;  /* local code page for mapping to and from Unicode */
67         char source_rfc1001_name[16]; /* netbios name of client */
68         char target_rfc1001_name[16]; /* netbios name of server for Win9x/ME */
69         uid_t linux_uid;
70         gid_t linux_gid;
71         mode_t file_mode;
72         mode_t dir_mode;
73         unsigned rw:1;
74         unsigned retry:1;
75         unsigned intr:1;
76         unsigned setuids:1;
77         unsigned noperm:1;
78         unsigned no_psx_acl:1; /* set if posix acl support should be disabled */
79         unsigned cifs_acl:1;
80         unsigned no_xattr:1;   /* set if xattr (EA) support should be disabled*/
81         unsigned server_ino:1; /* use inode numbers from server ie UniqueId */
82         unsigned direct_io:1;
83         unsigned remap:1;   /* set to remap seven reserved chars in filenames */
84         unsigned posix_paths:1;   /* unset to not ask for posix pathnames. */
85         unsigned sfu_emul:1;
86         unsigned krb5:1;
87         unsigned ntlm:1;
88         unsigned ntlmv2:1;
89         unsigned nullauth:1; /* attempt to authenticate with null user */
90         unsigned sign:1;
91         unsigned seal:1;     /* encrypt */
92         unsigned nocase;     /* request case insensitive filenames */
93         unsigned nobrl;      /* disable sending byte range locks to srv */
94         unsigned int rsize;
95         unsigned int wsize;
96         unsigned int sockopt;
97         unsigned short int port;
98 };
99
100 static int ipv4_connect(struct sockaddr_in *psin_server, 
101                         struct socket **csocket,
102                         char * netb_name,
103                         char * server_netb_name);
104 static int ipv6_connect(struct sockaddr_in6 *psin_server, 
105                         struct socket **csocket);
106
107
108         /* 
109          * cifs tcp session reconnection
110          * 
111          * mark tcp session as reconnecting so temporarily locked
112          * mark all smb sessions as reconnecting for tcp session
113          * reconnect tcp session
114          * wake up waiters on reconnection? - (not needed currently)
115          */
116
117 int
118 cifs_reconnect(struct TCP_Server_Info *server)
119 {
120         int rc = 0;
121         struct list_head *tmp;
122         struct cifsSesInfo *ses;
123         struct cifsTconInfo *tcon;
124         struct mid_q_entry * mid_entry;
125         
126         spin_lock(&GlobalMid_Lock);
127         if(server->tcpStatus == CifsExiting) {
128                 /* the demux thread will exit normally 
129                 next time through the loop */
130                 spin_unlock(&GlobalMid_Lock);
131                 return rc;
132         } else
133                 server->tcpStatus = CifsNeedReconnect;
134         spin_unlock(&GlobalMid_Lock);
135         server->maxBuf = 0;
136
137         cFYI(1, ("Reconnecting tcp session"));
138
139         /* before reconnecting the tcp session, mark the smb session (uid)
140                 and the tid bad so they are not used until reconnected */
141         read_lock(&GlobalSMBSeslock);
142         list_for_each(tmp, &GlobalSMBSessionList) {
143                 ses = list_entry(tmp, struct cifsSesInfo, cifsSessionList);
144                 if (ses->server) {
145                         if (ses->server == server) {
146                                 ses->status = CifsNeedReconnect;
147                                 ses->ipc_tid = 0;
148                         }
149                 }
150                 /* else tcp and smb sessions need reconnection */
151         }
152         list_for_each(tmp, &GlobalTreeConnectionList) {
153                 tcon = list_entry(tmp, struct cifsTconInfo, cifsConnectionList);
154                 if((tcon) && (tcon->ses) && (tcon->ses->server == server)) {
155                         tcon->tidStatus = CifsNeedReconnect;
156                 }
157         }
158         read_unlock(&GlobalSMBSeslock);
159         /* do not want to be sending data on a socket we are freeing */
160         down(&server->tcpSem); 
161         if(server->ssocket) {
162                 cFYI(1,("State: 0x%x Flags: 0x%lx", server->ssocket->state,
163                         server->ssocket->flags));
164                 server->ssocket->ops->shutdown(server->ssocket,SEND_SHUTDOWN);
165                 cFYI(1,("Post shutdown state: 0x%x Flags: 0x%lx", server->ssocket->state,
166                         server->ssocket->flags));
167                 sock_release(server->ssocket);
168                 server->ssocket = NULL;
169         }
170
171         spin_lock(&GlobalMid_Lock);
172         list_for_each(tmp, &server->pending_mid_q) {
173                 mid_entry = list_entry(tmp, struct
174                                         mid_q_entry,
175                                         qhead);
176                 if(mid_entry) {
177                         if(mid_entry->midState == MID_REQUEST_SUBMITTED) {
178                                 /* Mark other intransit requests as needing
179                                    retry so we do not immediately mark the
180                                    session bad again (ie after we reconnect
181                                    below) as they timeout too */
182                                 mid_entry->midState = MID_RETRY_NEEDED;
183                         }
184                 }
185         }
186         spin_unlock(&GlobalMid_Lock);
187         up(&server->tcpSem); 
188
189         while ((server->tcpStatus != CifsExiting) && (server->tcpStatus != CifsGood))
190         {
191                 if(server->protocolType == IPV6) {
192                         rc = ipv6_connect(&server->addr.sockAddr6,&server->ssocket);
193                 } else {
194                         rc = ipv4_connect(&server->addr.sockAddr, 
195                                         &server->ssocket,
196                                         server->workstation_RFC1001_name,
197                                         server->server_RFC1001_name);
198                 }
199                 if(rc) {
200                         cFYI(1,("reconnect error %d",rc));
201                         msleep(3000);
202                 } else {
203                         atomic_inc(&tcpSesReconnectCount);
204                         spin_lock(&GlobalMid_Lock);
205                         if(server->tcpStatus != CifsExiting)
206                                 server->tcpStatus = CifsGood;
207                         server->sequence_number = 0;
208                         spin_unlock(&GlobalMid_Lock);                   
209         /*              atomic_set(&server->inFlight,0);*/
210                         wake_up(&server->response_q);
211                 }
212         }
213         return rc;
214 }
215
216 /* 
217         return codes:
218                 0       not a transact2, or all data present
219                 >0      transact2 with that much data missing
220                 -EINVAL = invalid transact2
221
222  */
223 static int check2ndT2(struct smb_hdr * pSMB, unsigned int maxBufSize)
224 {
225         struct smb_t2_rsp * pSMBt;
226         int total_data_size;
227         int data_in_this_rsp;
228         int remaining;
229
230         if(pSMB->Command != SMB_COM_TRANSACTION2)
231                 return 0;
232
233         /* check for plausible wct, bcc and t2 data and parm sizes */
234         /* check for parm and data offset going beyond end of smb */
235         if(pSMB->WordCount != 10) { /* coalesce_t2 depends on this */
236                 cFYI(1,("invalid transact2 word count"));
237                 return -EINVAL;
238         }
239
240         pSMBt = (struct smb_t2_rsp *)pSMB;
241
242         total_data_size = le16_to_cpu(pSMBt->t2_rsp.TotalDataCount);
243         data_in_this_rsp = le16_to_cpu(pSMBt->t2_rsp.DataCount);
244
245         remaining = total_data_size - data_in_this_rsp;
246
247         if(remaining == 0)
248                 return 0;
249         else if(remaining < 0) {
250                 cFYI(1,("total data %d smaller than data in frame %d",
251                         total_data_size, data_in_this_rsp));
252                 return -EINVAL;
253         } else {
254                 cFYI(1,("missing %d bytes from transact2, check next response",
255                         remaining));
256                 if(total_data_size > maxBufSize) {
257                         cERROR(1,("TotalDataSize %d is over maximum buffer %d",
258                                 total_data_size,maxBufSize));
259                         return -EINVAL; 
260                 }
261                 return remaining;
262         }
263 }
264
265 static int coalesce_t2(struct smb_hdr * psecond, struct smb_hdr *pTargetSMB)
266 {
267         struct smb_t2_rsp *pSMB2 = (struct smb_t2_rsp *)psecond;
268         struct smb_t2_rsp *pSMBt  = (struct smb_t2_rsp *)pTargetSMB;
269         int total_data_size;
270         int total_in_buf;
271         int remaining;
272         int total_in_buf2;
273         char * data_area_of_target;
274         char * data_area_of_buf2;
275         __u16 byte_count;
276
277         total_data_size = le16_to_cpu(pSMBt->t2_rsp.TotalDataCount);
278
279         if(total_data_size != le16_to_cpu(pSMB2->t2_rsp.TotalDataCount)) {
280                 cFYI(1,("total data sizes of primary and secondary t2 differ"));
281         }
282
283         total_in_buf = le16_to_cpu(pSMBt->t2_rsp.DataCount);
284
285         remaining = total_data_size - total_in_buf;
286         
287         if(remaining < 0)
288                 return -EINVAL;
289
290         if(remaining == 0) /* nothing to do, ignore */
291                 return 0;
292         
293         total_in_buf2 = le16_to_cpu(pSMB2->t2_rsp.DataCount);
294         if(remaining < total_in_buf2) {
295                 cFYI(1,("transact2 2nd response contains too much data"));
296         }
297
298         /* find end of first SMB data area */
299         data_area_of_target = (char *)&pSMBt->hdr.Protocol + 
300                                 le16_to_cpu(pSMBt->t2_rsp.DataOffset);
301         /* validate target area */
302
303         data_area_of_buf2 = (char *) &pSMB2->hdr.Protocol +
304                                         le16_to_cpu(pSMB2->t2_rsp.DataOffset);
305
306         data_area_of_target += total_in_buf;
307
308         /* copy second buffer into end of first buffer */
309         memcpy(data_area_of_target,data_area_of_buf2,total_in_buf2);
310         total_in_buf += total_in_buf2;
311         pSMBt->t2_rsp.DataCount = cpu_to_le16(total_in_buf);
312         byte_count = le16_to_cpu(BCC_LE(pTargetSMB));
313         byte_count += total_in_buf2;
314         BCC_LE(pTargetSMB) = cpu_to_le16(byte_count);
315
316         byte_count = pTargetSMB->smb_buf_length;
317         byte_count += total_in_buf2;
318
319         /* BB also add check that we are not beyond maximum buffer size */
320                 
321         pTargetSMB->smb_buf_length = byte_count;
322
323         if(remaining == total_in_buf2) {
324                 cFYI(1,("found the last secondary response"));
325                 return 0; /* we are done */
326         } else /* more responses to go */
327                 return 1;
328
329 }
330
331 static int
332 cifs_demultiplex_thread(struct TCP_Server_Info *server)
333 {
334         int length;
335         unsigned int pdu_length, total_read;
336         struct smb_hdr *smb_buffer = NULL;
337         struct smb_hdr *bigbuf = NULL;
338         struct smb_hdr *smallbuf = NULL;
339         struct msghdr smb_msg;
340         struct kvec iov;
341         struct socket *csocket = server->ssocket;
342         struct list_head *tmp;
343         struct cifsSesInfo *ses;
344         struct task_struct *task_to_wake = NULL;
345         struct mid_q_entry *mid_entry;
346         char temp;
347         int isLargeBuf = FALSE;
348         int isMultiRsp;
349         int reconnect;
350
351         daemonize("cifsd");
352         allow_signal(SIGKILL);
353         current->flags |= PF_MEMALLOC;
354         server->tsk = current;  /* save process info to wake at shutdown */
355         cFYI(1, ("Demultiplex PID: %d", current->pid));
356         write_lock(&GlobalSMBSeslock); 
357         atomic_inc(&tcpSesAllocCount);
358         length = tcpSesAllocCount.counter;
359         write_unlock(&GlobalSMBSeslock);
360         complete(&cifsd_complete);
361         if(length  > 1) {
362                 mempool_resize(cifs_req_poolp,
363                         length + cifs_min_rcv,
364                         GFP_KERNEL);
365         }
366
367         while (server->tcpStatus != CifsExiting) {
368                 if (try_to_freeze())
369                         continue;
370                 if (bigbuf == NULL) {
371                         bigbuf = cifs_buf_get();
372                         if(bigbuf == NULL) {
373                                 cERROR(1,("No memory for large SMB response"));
374                                 msleep(3000);
375                                 /* retry will check if exiting */
376                                 continue;
377                         }
378                 } else if(isLargeBuf) {
379                         /* we are reusing a dirtry large buf, clear its start */
380                         memset(bigbuf, 0, sizeof (struct smb_hdr));
381                 }
382
383                 if (smallbuf == NULL) {
384                         smallbuf = cifs_small_buf_get();
385                         if(smallbuf == NULL) {
386                                 cERROR(1,("No memory for SMB response"));
387                                 msleep(1000);
388                                 /* retry will check if exiting */
389                                 continue;
390                         }
391                         /* beginning of smb buffer is cleared in our buf_get */
392                 } else /* if existing small buf clear beginning */
393                         memset(smallbuf, 0, sizeof (struct smb_hdr));
394
395                 isLargeBuf = FALSE;
396                 isMultiRsp = FALSE;
397                 smb_buffer = smallbuf;
398                 iov.iov_base = smb_buffer;
399                 iov.iov_len = 4;
400                 smb_msg.msg_control = NULL;
401                 smb_msg.msg_controllen = 0;
402                 length =
403                     kernel_recvmsg(csocket, &smb_msg,
404                                  &iov, 1, 4, 0 /* BB see socket.h flags */);
405
406                 if(server->tcpStatus == CifsExiting) {
407                         break;
408                 } else if (server->tcpStatus == CifsNeedReconnect) {
409                         cFYI(1,("Reconnect after server stopped responding"));
410                         cifs_reconnect(server);
411                         cFYI(1,("call to reconnect done"));
412                         csocket = server->ssocket;
413                         continue;
414                 } else if ((length == -ERESTARTSYS) || (length == -EAGAIN)) {
415                         msleep(1); /* minimum sleep to prevent looping
416                                 allowing socket to clear and app threads to set
417                                 tcpStatus CifsNeedReconnect if server hung */
418                         continue;
419                 } else if (length <= 0) {
420                         if(server->tcpStatus == CifsNew) {
421                                 cFYI(1,("tcp session abend after SMBnegprot"));
422                                 /* some servers kill the TCP session rather than
423                                    returning an SMB negprot error, in which
424                                    case reconnecting here is not going to help,
425                                    and so simply return error to mount */
426                                 break;
427                         }
428                         if(length == -EINTR) { 
429                                 cFYI(1,("cifsd thread killed"));
430                                 break;
431                         }
432                         cFYI(1,("Reconnect after unexpected peek error %d",
433                                 length));
434                         cifs_reconnect(server);
435                         csocket = server->ssocket;
436                         wake_up(&server->response_q);
437                         continue;
438                 } else if (length < 4) {
439                         cFYI(1,
440                             ("Frame under four bytes received (%d bytes long)",
441                               length));
442                         cifs_reconnect(server);
443                         csocket = server->ssocket;
444                         wake_up(&server->response_q);
445                         continue;
446                 }
447
448                 /* The right amount was read from socket - 4 bytes */
449                 /* so we can now interpret the length field */
450
451                 /* the first byte big endian of the length field,
452                 is actually not part of the length but the type
453                 with the most common, zero, as regular data */
454                 temp = *((char *) smb_buffer);
455
456                 /* Note that FC 1001 length is big endian on the wire, 
457                 but we convert it here so it is always manipulated
458                 as host byte order */
459                 pdu_length = ntohl(smb_buffer->smb_buf_length);
460                 smb_buffer->smb_buf_length = pdu_length;
461
462                 cFYI(1,("rfc1002 length 0x%x)", pdu_length+4));
463
464                 if (temp == (char) RFC1002_SESSION_KEEP_ALIVE) {
465                         continue; 
466                 } else if (temp == (char)RFC1002_POSITIVE_SESSION_RESPONSE) {
467                         cFYI(1,("Good RFC 1002 session rsp"));
468                         continue;
469                 } else if (temp == (char)RFC1002_NEGATIVE_SESSION_RESPONSE) {
470                         /* we get this from Windows 98 instead of 
471                            an error on SMB negprot response */
472                         cFYI(1,("Negative RFC1002 Session Response Error 0x%x)",
473                                 pdu_length));
474                         if(server->tcpStatus == CifsNew) {
475                                 /* if nack on negprot (rather than 
476                                 ret of smb negprot error) reconnecting
477                                 not going to help, ret error to mount */
478                                 break;
479                         } else {
480                                 /* give server a second to
481                                 clean up before reconnect attempt */
482                                 msleep(1000);
483                                 /* always try 445 first on reconnect
484                                 since we get NACK on some if we ever
485                                 connected to port 139 (the NACK is 
486                                 since we do not begin with RFC1001
487                                 session initialize frame) */
488                                 server->addr.sockAddr.sin_port = 
489                                         htons(CIFS_PORT);
490                                 cifs_reconnect(server);
491                                 csocket = server->ssocket;
492                                 wake_up(&server->response_q);
493                                 continue;
494                         }
495                 } else if (temp != (char) 0) {
496                         cERROR(1,("Unknown RFC 1002 frame"));
497                         cifs_dump_mem(" Received Data: ", (char *)smb_buffer,
498                                       length);
499                         cifs_reconnect(server);
500                         csocket = server->ssocket;
501                         continue;
502                 }
503
504                 /* else we have an SMB response */
505                 if((pdu_length > CIFSMaxBufSize + MAX_CIFS_HDR_SIZE - 4) ||
506                             (pdu_length < sizeof (struct smb_hdr) - 1 - 4)) {
507                         cERROR(1, ("Invalid size SMB length %d pdu_length %d",
508                                         length, pdu_length+4));
509                         cifs_reconnect(server);
510                         csocket = server->ssocket;
511                         wake_up(&server->response_q);
512                         continue;
513                 } 
514
515                 /* else length ok */
516                 reconnect = 0;
517
518                 if(pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
519                         isLargeBuf = TRUE;
520                         memcpy(bigbuf, smallbuf, 4);
521                         smb_buffer = bigbuf;
522                 }
523                 length = 0;
524                 iov.iov_base = 4 + (char *)smb_buffer;
525                 iov.iov_len = pdu_length;
526                 for (total_read = 0; total_read < pdu_length; 
527                      total_read += length) {
528                         length = kernel_recvmsg(csocket, &smb_msg, &iov, 1,
529                                                 pdu_length - total_read, 0);
530                         if((server->tcpStatus == CifsExiting) ||
531                             (length == -EINTR)) {
532                                 /* then will exit */
533                                 reconnect = 2;
534                                 break;
535                         } else if (server->tcpStatus == CifsNeedReconnect) {
536                                 cifs_reconnect(server);
537                                 csocket = server->ssocket;
538                                 /* Reconnect wakes up rspns q */
539                                 /* Now we will reread sock */
540                                 reconnect = 1;
541                                 break;
542                         } else if ((length == -ERESTARTSYS) || 
543                                    (length == -EAGAIN)) {
544                                 msleep(1); /* minimum sleep to prevent looping,
545                                               allowing socket to clear and app 
546                                               threads to set tcpStatus
547                                               CifsNeedReconnect if server hung*/
548                                 continue;
549                         } else if (length <= 0) {
550                                 cERROR(1,("Received no data, expecting %d",
551                                               pdu_length - total_read));
552                                 cifs_reconnect(server);
553                                 csocket = server->ssocket;
554                                 reconnect = 1;
555                                 break;
556                         }
557                 }
558                 if(reconnect == 2)
559                         break;
560                 else if(reconnect == 1)
561                         continue;
562
563                 length += 4; /* account for rfc1002 hdr */
564         
565
566                 dump_smb(smb_buffer, length);
567                 if (checkSMB(smb_buffer, smb_buffer->Mid, total_read+4)) {
568                         cifs_dump_mem("Bad SMB: ", smb_buffer, 48);
569                         continue;
570                 }
571
572
573                 task_to_wake = NULL;
574                 spin_lock(&GlobalMid_Lock);
575                 list_for_each(tmp, &server->pending_mid_q) {
576                         mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
577
578                         if ((mid_entry->mid == smb_buffer->Mid) && 
579                             (mid_entry->midState == MID_REQUEST_SUBMITTED) &&
580                             (mid_entry->command == smb_buffer->Command)) {
581                                 if(check2ndT2(smb_buffer,server->maxBuf) > 0) {
582                                         /* We have a multipart transact2 resp */
583                                         isMultiRsp = TRUE;
584                                         if(mid_entry->resp_buf) {
585                                                 /* merge response - fix up 1st*/
586                                                 if(coalesce_t2(smb_buffer, 
587                                                         mid_entry->resp_buf)) {
588                                                         break;
589                                                 } else {
590                                                         /* all parts received */
591                                                         goto multi_t2_fnd; 
592                                                 }
593                                         } else {
594                                                 if(!isLargeBuf) {
595                                                         cERROR(1,("1st trans2 resp needs bigbuf"));
596                                         /* BB maybe we can fix this up,  switch
597                                            to already allocated large buffer? */
598                                                 } else {
599                                                         /* Have first buffer */
600                                                         mid_entry->resp_buf =
601                                                                  smb_buffer;
602                                                         mid_entry->largeBuf = 1;
603                                                         bigbuf = NULL;
604                                                 }
605                                         }
606                                         break;
607                                 } 
608                                 mid_entry->resp_buf = smb_buffer;
609                                 if(isLargeBuf)
610                                         mid_entry->largeBuf = 1;
611                                 else
612                                         mid_entry->largeBuf = 0;
613 multi_t2_fnd:
614                                 task_to_wake = mid_entry->tsk;
615                                 mid_entry->midState = MID_RESPONSE_RECEIVED;
616 #ifdef CONFIG_CIFS_STATS2
617                                 mid_entry->when_received = jiffies;
618 #endif
619                                 break;
620                         }
621                 }
622                 spin_unlock(&GlobalMid_Lock);
623                 if (task_to_wake) {
624                         /* Was previous buf put in mpx struct for multi-rsp? */
625                         if(!isMultiRsp) {
626                                 /* smb buffer will be freed by user thread */
627                                 if(isLargeBuf) {
628                                         bigbuf = NULL;
629                                 } else
630                                         smallbuf = NULL;
631                         }
632                         wake_up_process(task_to_wake);
633                 } else if ((is_valid_oplock_break(smb_buffer, server) == FALSE)
634                     && (isMultiRsp == FALSE)) {                          
635                         cERROR(1, ("No task to wake, unknown frame rcvd!"));
636                         cifs_dump_mem("Received Data is: ",(char *)smb_buffer,
637                                       sizeof(struct smb_hdr));
638                 }
639         } /* end while !EXITING */
640
641         spin_lock(&GlobalMid_Lock);
642         server->tcpStatus = CifsExiting;
643         server->tsk = NULL;
644         /* check if we have blocked requests that need to free */
645         /* Note that cifs_max_pending is normally 50, but
646         can be set at module install time to as little as two */
647         if(atomic_read(&server->inFlight) >= cifs_max_pending)
648                 atomic_set(&server->inFlight, cifs_max_pending - 1);
649         /* We do not want to set the max_pending too low or we
650         could end up with the counter going negative */
651         spin_unlock(&GlobalMid_Lock);
652         /* Although there should not be any requests blocked on 
653         this queue it can not hurt to be paranoid and try to wake up requests
654         that may haven been blocked when more than 50 at time were on the wire
655         to the same server - they now will see the session is in exit state
656         and get out of SendReceive.  */
657         wake_up_all(&server->request_q);
658         /* give those requests time to exit */
659         msleep(125);
660         
661         if(server->ssocket) {
662                 sock_release(csocket);
663                 server->ssocket = NULL;
664         }
665         /* buffer usuallly freed in free_mid - need to free it here on exit */
666         if (bigbuf != NULL)
667                 cifs_buf_release(bigbuf);
668         if (smallbuf != NULL)
669                 cifs_small_buf_release(smallbuf);
670
671         read_lock(&GlobalSMBSeslock);
672         if (list_empty(&server->pending_mid_q)) {
673                 /* loop through server session structures attached to this and
674                     mark them dead */
675                 list_for_each(tmp, &GlobalSMBSessionList) {
676                         ses =
677                             list_entry(tmp, struct cifsSesInfo,
678                                        cifsSessionList);
679                         if (ses->server == server) {
680                                 ses->status = CifsExiting;
681                                 ses->server = NULL;
682                         }
683                 }
684                 read_unlock(&GlobalSMBSeslock);
685         } else {
686                 /* although we can not zero the server struct pointer yet,
687                 since there are active requests which may depnd on them,
688                 mark the corresponding SMB sessions as exiting too */
689                 list_for_each(tmp, &GlobalSMBSessionList) {
690                         ses = list_entry(tmp, struct cifsSesInfo,
691                                          cifsSessionList);
692                         if (ses->server == server) {
693                                 ses->status = CifsExiting;
694                         }
695                 }
696
697                 spin_lock(&GlobalMid_Lock);
698                 list_for_each(tmp, &server->pending_mid_q) {
699                 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
700                         if (mid_entry->midState == MID_REQUEST_SUBMITTED) {
701                                 cFYI(1,
702                                   ("Clearing Mid 0x%x - waking up ",mid_entry->mid));
703                                 task_to_wake = mid_entry->tsk;
704                                 if(task_to_wake) {
705                                         wake_up_process(task_to_wake);
706                                 }
707                         }
708                 }
709                 spin_unlock(&GlobalMid_Lock);
710                 read_unlock(&GlobalSMBSeslock);
711                 /* 1/8th of sec is more than enough time for them to exit */
712                 msleep(125);
713         }
714
715         if (!list_empty(&server->pending_mid_q)) {
716                 /* mpx threads have not exited yet give them 
717                 at least the smb send timeout time for long ops */
718                 /* due to delays on oplock break requests, we need
719                 to wait at least 45 seconds before giving up
720                 on a request getting a response and going ahead
721                 and killing cifsd */
722                 cFYI(1, ("Wait for exit from demultiplex thread"));
723                 msleep(46000);
724                 /* if threads still have not exited they are probably never
725                 coming home not much else we can do but free the memory */
726         }
727
728         write_lock(&GlobalSMBSeslock);
729         atomic_dec(&tcpSesAllocCount);
730         length = tcpSesAllocCount.counter;
731
732         /* last chance to mark ses pointers invalid
733         if there are any pointing to this (e.g
734         if a crazy root user tried to kill cifsd 
735         kernel thread explicitly this might happen) */
736         list_for_each(tmp, &GlobalSMBSessionList) {
737                 ses = list_entry(tmp, struct cifsSesInfo,
738                                 cifsSessionList);
739                 if (ses->server == server) {
740                         ses->server = NULL;
741                 }
742         }
743         write_unlock(&GlobalSMBSeslock);
744
745         kfree(server);
746         if(length  > 0) {
747                 mempool_resize(cifs_req_poolp,
748                         length + cifs_min_rcv,
749                         GFP_KERNEL);
750         }
751         
752         complete_and_exit(&cifsd_complete, 0);
753         return 0;
754 }
755
756 static int
757 cifs_parse_mount_options(char *options, const char *devname,struct smb_vol *vol)
758 {
759         char *value;
760         char *data;
761         unsigned int  temp_len, i, j;
762         char separator[2];
763
764         separator[0] = ',';
765         separator[1] = 0; 
766
767         memset(vol->source_rfc1001_name,0x20,15);
768         for(i=0;i < strnlen(system_utsname.nodename,15);i++) {
769                 /* does not have to be a perfect mapping since the field is
770                 informational, only used for servers that do not support
771                 port 445 and it can be overridden at mount time */
772                 vol->source_rfc1001_name[i] = 
773                         toupper(system_utsname.nodename[i]);
774         }
775         vol->source_rfc1001_name[15] = 0;
776         /* null target name indicates to use *SMBSERVR default called name
777            if we end up sending RFC1001 session initialize */
778         vol->target_rfc1001_name[0] = 0;
779         vol->linux_uid = current->uid;  /* current->euid instead? */
780         vol->linux_gid = current->gid;
781         vol->dir_mode = S_IRWXUGO;
782         /* 2767 perms indicate mandatory locking support */
783         vol->file_mode = S_IALLUGO & ~(S_ISUID | S_IXGRP);
784
785         /* vol->retry default is 0 (i.e. "soft" limited retry not hard retry) */
786         vol->rw = TRUE;
787         vol->ntlm = TRUE;
788         /* default is always to request posix paths. */
789         vol->posix_paths = 1;
790
791         if (!options)
792                 return 1;
793
794         if(strncmp(options,"sep=",4) == 0) {
795                 if(options[4] != 0) {
796                         separator[0] = options[4];
797                         options += 5;
798                 } else {
799                         cFYI(1,("Null separator not allowed"));
800                 }
801         }
802                 
803         while ((data = strsep(&options, separator)) != NULL) {
804                 if (!*data)
805                         continue;
806                 if ((value = strchr(data, '=')) != NULL)
807                         *value++ = '\0';
808
809                 if (strnicmp(data, "user_xattr",10) == 0) {/*parse before user*/
810                         vol->no_xattr = 0;
811                 } else if (strnicmp(data, "nouser_xattr",12) == 0) {
812                         vol->no_xattr = 1;
813                 } else if (strnicmp(data, "user", 4) == 0) {
814                         if (!value || !*value) {
815                                 printk(KERN_WARNING
816                                        "CIFS: invalid or missing username\n");
817                                 return 1;       /* needs_arg; */
818                         }
819                         if (strnlen(value, 200) < 200) {
820                                 vol->username = value;
821                         } else {
822                                 printk(KERN_WARNING "CIFS: username too long\n");
823                                 return 1;
824                         }
825                 } else if (strnicmp(data, "pass", 4) == 0) {
826                         if (!value) {
827                                 vol->password = NULL;
828                                 continue;
829                         } else if(value[0] == 0) {
830                                 /* check if string begins with double comma
831                                    since that would mean the password really
832                                    does start with a comma, and would not
833                                    indicate an empty string */
834                                 if(value[1] != separator[0]) {
835                                         vol->password = NULL;
836                                         continue;
837                                 }
838                         }
839                         temp_len = strlen(value);
840                         /* removed password length check, NTLM passwords
841                                 can be arbitrarily long */
842
843                         /* if comma in password, the string will be 
844                         prematurely null terminated.  Commas in password are
845                         specified across the cifs mount interface by a double
846                         comma ie ,, and a comma used as in other cases ie ','
847                         as a parameter delimiter/separator is single and due
848                         to the strsep above is temporarily zeroed. */
849
850                         /* NB: password legally can have multiple commas and
851                         the only illegal character in a password is null */
852
853                         if ((value[temp_len] == 0) && 
854                             (value[temp_len+1] == separator[0])) {
855                                 /* reinsert comma */
856                                 value[temp_len] = separator[0];
857                                 temp_len+=2;  /* move after the second comma */
858                                 while(value[temp_len] != 0)  {
859                                         if (value[temp_len] == separator[0]) {
860                                                 if (value[temp_len+1] == 
861                                                      separator[0]) {
862                                                 /* skip second comma */
863                                                         temp_len++;
864                                                 } else { 
865                                                 /* single comma indicating start
866                                                          of next parm */
867                                                         break;
868                                                 }
869                                         }
870                                         temp_len++;
871                                 }
872                                 if(value[temp_len] == 0) {
873                                         options = NULL;
874                                 } else {
875                                         value[temp_len] = 0;
876                                         /* point option to start of next parm */
877                                         options = value + temp_len + 1;
878                                 }
879                                 /* go from value to value + temp_len condensing 
880                                 double commas to singles. Note that this ends up
881                                 allocating a few bytes too many, which is ok */
882                                 vol->password = kzalloc(temp_len, GFP_KERNEL);
883                                 if(vol->password == NULL) {
884                                         printk("CIFS: no memory for pass\n");
885                                         return 1;
886                                 }
887                                 for(i=0,j=0;i<temp_len;i++,j++) {
888                                         vol->password[j] = value[i];
889                                         if(value[i] == separator[0]
890                                                 && value[i+1] == separator[0]) {
891                                                 /* skip second comma */
892                                                 i++;
893                                         }
894                                 }
895                                 vol->password[j] = 0;
896                         } else {
897                                 vol->password = kzalloc(temp_len+1, GFP_KERNEL);
898                                 if(vol->password == NULL) {
899                                         printk("CIFS: no memory for pass\n");
900                                         return 1;
901                                 }
902                                 strcpy(vol->password, value);
903                         }
904                 } else if (strnicmp(data, "ip", 2) == 0) {
905                         if (!value || !*value) {
906                                 vol->UNCip = NULL;
907                         } else if (strnlen(value, 35) < 35) {
908                                 vol->UNCip = value;
909                         } else {
910                                 printk(KERN_WARNING "CIFS: ip address too long\n");
911                                 return 1;
912                         }
913                 } else if (strnicmp(data, "sec", 3) == 0) { 
914                         if (!value || !*value) {
915                                 cERROR(1,("no security value specified"));
916                                 continue;
917                         } else if (strnicmp(value, "krb5i", 5) == 0) {
918                                 vol->sign = 1;
919                                 vol->krb5 = 1;
920                         } else if (strnicmp(value, "krb5p", 5) == 0) {
921                                 /* vol->seal = 1; 
922                                    vol->krb5 = 1; */
923                                 cERROR(1,("Krb5 cifs privacy not supported"));
924                                 return 1;
925                         } else if (strnicmp(value, "krb5", 4) == 0) {
926                                 vol->krb5 = 1;
927                         } else if (strnicmp(value, "ntlmv2i", 7) == 0) {
928                                 vol->ntlmv2 = 1;
929                                 vol->sign = 1;
930                         } else if (strnicmp(value, "ntlmv2", 6) == 0) {
931                                 vol->ntlmv2 = 1;
932                         } else if (strnicmp(value, "ntlmi", 5) == 0) {
933                                 vol->ntlm = 1;
934                                 vol->sign = 1;
935                         } else if (strnicmp(value, "ntlm", 4) == 0) {
936                                 /* ntlm is default so can be turned off too */
937                                 vol->ntlm = 1;
938                         } else if (strnicmp(value, "nontlm", 6) == 0) {
939                                 vol->ntlm = 0;
940                         } else if (strnicmp(value, "none", 4) == 0) {
941                                 vol->nullauth = 1; 
942                         } else {
943                                 cERROR(1,("bad security option: %s", value));
944                                 return 1;
945                         }
946                 } else if ((strnicmp(data, "unc", 3) == 0)
947                            || (strnicmp(data, "target", 6) == 0)
948                            || (strnicmp(data, "path", 4) == 0)) {
949                         if (!value || !*value) {
950                                 printk(KERN_WARNING
951                                        "CIFS: invalid path to network resource\n");
952                                 return 1;       /* needs_arg; */
953                         }
954                         if ((temp_len = strnlen(value, 300)) < 300) {
955                                 vol->UNC = kmalloc(temp_len+1,GFP_KERNEL);
956                                 if(vol->UNC == NULL)
957                                         return 1;
958                                 strcpy(vol->UNC,value);
959                                 if (strncmp(vol->UNC, "//", 2) == 0) {
960                                         vol->UNC[0] = '\\';
961                                         vol->UNC[1] = '\\';
962                                 } else if (strncmp(vol->UNC, "\\\\", 2) != 0) {                    
963                                         printk(KERN_WARNING
964                                                "CIFS: UNC Path does not begin with // or \\\\ \n");
965                                         return 1;
966                                 }
967                         } else {
968                                 printk(KERN_WARNING "CIFS: UNC name too long\n");
969                                 return 1;
970                         }
971                 } else if ((strnicmp(data, "domain", 3) == 0)
972                            || (strnicmp(data, "workgroup", 5) == 0)) {
973                         if (!value || !*value) {
974                                 printk(KERN_WARNING "CIFS: invalid domain name\n");
975                                 return 1;       /* needs_arg; */
976                         }
977                         /* BB are there cases in which a comma can be valid in
978                         a domain name and need special handling? */
979                         if (strnlen(value, 65) < 65) {
980                                 vol->domainname = value;
981                                 cFYI(1, ("Domain name set"));
982                         } else {
983                                 printk(KERN_WARNING "CIFS: domain name too long\n");
984                                 return 1;
985                         }
986                 } else if (strnicmp(data, "iocharset", 9) == 0) {
987                         if (!value || !*value) {
988                                 printk(KERN_WARNING "CIFS: invalid iocharset specified\n");
989                                 return 1;       /* needs_arg; */
990                         }
991                         if (strnlen(value, 65) < 65) {
992                                 if(strnicmp(value,"default",7))
993                                         vol->iocharset = value;
994                                 /* if iocharset not set load_nls_default used by caller */
995                                 cFYI(1, ("iocharset set to %s",value));
996                         } else {
997                                 printk(KERN_WARNING "CIFS: iocharset name too long.\n");
998                                 return 1;
999                         }
1000                 } else if (strnicmp(data, "uid", 3) == 0) {
1001                         if (value && *value) {
1002                                 vol->linux_uid =
1003                                         simple_strtoul(value, &value, 0);
1004                         }
1005                 } else if (strnicmp(data, "gid", 3) == 0) {
1006                         if (value && *value) {
1007                                 vol->linux_gid =
1008                                         simple_strtoul(value, &value, 0);
1009                         }
1010                 } else if (strnicmp(data, "file_mode", 4) == 0) {
1011                         if (value && *value) {
1012                                 vol->file_mode =
1013                                         simple_strtoul(value, &value, 0);
1014                         }
1015                 } else if (strnicmp(data, "dir_mode", 4) == 0) {
1016                         if (value && *value) {
1017                                 vol->dir_mode =
1018                                         simple_strtoul(value, &value, 0);
1019                         }
1020                 } else if (strnicmp(data, "dirmode", 4) == 0) {
1021                         if (value && *value) {
1022                                 vol->dir_mode =
1023                                         simple_strtoul(value, &value, 0);
1024                         }
1025                 } else if (strnicmp(data, "port", 4) == 0) {
1026                         if (value && *value) {
1027                                 vol->port =
1028                                         simple_strtoul(value, &value, 0);
1029                         }
1030                 } else if (strnicmp(data, "rsize", 5) == 0) {
1031                         if (value && *value) {
1032                                 vol->rsize =
1033                                         simple_strtoul(value, &value, 0);
1034                         }
1035                 } else if (strnicmp(data, "wsize", 5) == 0) {
1036                         if (value && *value) {
1037                                 vol->wsize =
1038                                         simple_strtoul(value, &value, 0);
1039                         }
1040                 } else if (strnicmp(data, "sockopt", 5) == 0) {
1041                         if (value && *value) {
1042                                 vol->sockopt =
1043                                         simple_strtoul(value, &value, 0);
1044                         }
1045                 } else if (strnicmp(data, "netbiosname", 4) == 0) {
1046                         if (!value || !*value || (*value == ' ')) {
1047                                 cFYI(1,("invalid (empty) netbiosname specified"));
1048                         } else {
1049                                 memset(vol->source_rfc1001_name,0x20,15);
1050                                 for(i=0;i<15;i++) {
1051                                 /* BB are there cases in which a comma can be 
1052                                 valid in this workstation netbios name (and need
1053                                 special handling)? */
1054
1055                                 /* We do not uppercase netbiosname for user */
1056                                         if (value[i]==0)
1057                                                 break;
1058                                         else 
1059                                                 vol->source_rfc1001_name[i] = value[i];
1060                                 }
1061                                 /* The string has 16th byte zero still from
1062                                 set at top of the function  */
1063                                 if((i==15) && (value[i] != 0))
1064                                         printk(KERN_WARNING "CIFS: netbiosname longer than 15 truncated.\n");
1065                         }
1066                 } else if (strnicmp(data, "servern", 7) == 0) {
1067                         /* servernetbiosname specified override *SMBSERVER */
1068                         if (!value || !*value || (*value == ' ')) {
1069                                 cFYI(1,("empty server netbiosname specified"));
1070                         } else {
1071                                 /* last byte, type, is 0x20 for servr type */
1072                                 memset(vol->target_rfc1001_name,0x20,16);
1073
1074                                 for(i=0;i<15;i++) {
1075                                 /* BB are there cases in which a comma can be
1076                                    valid in this workstation netbios name (and need
1077                                    special handling)? */
1078
1079                                 /* user or mount helper must uppercase netbiosname */
1080                                         if (value[i]==0)
1081                                                 break;
1082                                         else
1083                                                 vol->target_rfc1001_name[i] = value[i];
1084                                 }
1085                                 /* The string has 16th byte zero still from
1086                                    set at top of the function  */
1087                                 if((i==15) && (value[i] != 0))
1088                                         printk(KERN_WARNING "CIFS: server netbiosname longer than 15 truncated.\n");
1089                         }
1090                 } else if (strnicmp(data, "credentials", 4) == 0) {
1091                         /* ignore */
1092                 } else if (strnicmp(data, "version", 3) == 0) {
1093                         /* ignore */
1094                 } else if (strnicmp(data, "guest",5) == 0) {
1095                         /* ignore */
1096                 } else if (strnicmp(data, "rw", 2) == 0) {
1097                         vol->rw = TRUE;
1098                 } else if ((strnicmp(data, "suid", 4) == 0) ||
1099                                    (strnicmp(data, "nosuid", 6) == 0) ||
1100                                    (strnicmp(data, "exec", 4) == 0) ||
1101                                    (strnicmp(data, "noexec", 6) == 0) ||
1102                                    (strnicmp(data, "nodev", 5) == 0) ||
1103                                    (strnicmp(data, "noauto", 6) == 0) ||
1104                                    (strnicmp(data, "dev", 3) == 0)) {
1105                         /*  The mount tool or mount.cifs helper (if present)
1106                                 uses these opts to set flags, and the flags are read
1107                                 by the kernel vfs layer before we get here (ie
1108                                 before read super) so there is no point trying to
1109                                 parse these options again and set anything and it
1110                                 is ok to just ignore them */
1111                         continue;
1112                 } else if (strnicmp(data, "ro", 2) == 0) {
1113                         vol->rw = FALSE;
1114                 } else if (strnicmp(data, "hard", 4) == 0) {
1115                         vol->retry = 1;
1116                 } else if (strnicmp(data, "soft", 4) == 0) {
1117                         vol->retry = 0;
1118                 } else if (strnicmp(data, "perm", 4) == 0) {
1119                         vol->noperm = 0;
1120                 } else if (strnicmp(data, "noperm", 6) == 0) {
1121                         vol->noperm = 1;
1122                 } else if (strnicmp(data, "mapchars", 8) == 0) {
1123                         vol->remap = 1;
1124                 } else if (strnicmp(data, "nomapchars", 10) == 0) {
1125                         vol->remap = 0;
1126                 } else if (strnicmp(data, "sfu", 3) == 0) {
1127                         vol->sfu_emul = 1;
1128                 } else if (strnicmp(data, "nosfu", 5) == 0) {
1129                         vol->sfu_emul = 0;
1130                 } else if (strnicmp(data, "posixpaths", 10) == 0) {
1131                         vol->posix_paths = 1;
1132                 } else if (strnicmp(data, "noposixpaths", 12) == 0) {
1133                         vol->posix_paths = 0;
1134                 } else if ((strnicmp(data, "nocase", 6) == 0) ||
1135                            (strnicmp(data, "ignorecase", 10)  == 0)) {
1136                         vol->nocase = 1;
1137                 } else if (strnicmp(data, "brl", 3) == 0) {
1138                         vol->nobrl =  0;
1139                 } else if ((strnicmp(data, "nobrl", 5) == 0) || 
1140                            (strnicmp(data, "nolock", 6) == 0)) {
1141                         vol->nobrl =  1;
1142                         /* turn off mandatory locking in mode
1143                         if remote locking is turned off since the
1144                         local vfs will do advisory */
1145                         if(vol->file_mode == (S_IALLUGO & ~(S_ISUID | S_IXGRP)))
1146                                 vol->file_mode = S_IALLUGO;
1147                 } else if (strnicmp(data, "setuids", 7) == 0) {
1148                         vol->setuids = 1;
1149                 } else if (strnicmp(data, "nosetuids", 9) == 0) {
1150                         vol->setuids = 0;
1151                 } else if (strnicmp(data, "nohard", 6) == 0) {
1152                         vol->retry = 0;
1153                 } else if (strnicmp(data, "nosoft", 6) == 0) {
1154                         vol->retry = 1;
1155                 } else if (strnicmp(data, "nointr", 6) == 0) {
1156                         vol->intr = 0;
1157                 } else if (strnicmp(data, "intr", 4) == 0) {
1158                         vol->intr = 1;
1159                 } else if (strnicmp(data, "serverino",7) == 0) {
1160                         vol->server_ino = 1;
1161                 } else if (strnicmp(data, "noserverino",9) == 0) {
1162                         vol->server_ino = 0;
1163                 } else if (strnicmp(data, "cifsacl",7) == 0) {
1164                         vol->cifs_acl = 1;
1165                 } else if (strnicmp(data, "nocifsacl", 9) == 0) {
1166                         vol->cifs_acl = 0;
1167                 } else if (strnicmp(data, "acl",3) == 0) {
1168                         vol->no_psx_acl = 0;
1169                 } else if (strnicmp(data, "noacl",5) == 0) {
1170                         vol->no_psx_acl = 1;
1171                 } else if (strnicmp(data, "direct",6) == 0) {
1172                         vol->direct_io = 1;
1173                 } else if (strnicmp(data, "forcedirectio",13) == 0) {
1174                         vol->direct_io = 1;
1175                 } else if (strnicmp(data, "in6_addr",8) == 0) {
1176                         if (!value || !*value) {
1177                                 vol->in6_addr = NULL;
1178                         } else if (strnlen(value, 49) == 48) {
1179                                 vol->in6_addr = value;
1180                         } else {
1181                                 printk(KERN_WARNING "CIFS: ip v6 address not 48 characters long\n");
1182                                 return 1;
1183                         }
1184                 } else if (strnicmp(data, "noac", 4) == 0) {
1185                         printk(KERN_WARNING "CIFS: Mount option noac not supported. Instead set /proc/fs/cifs/LookupCacheEnabled to 0\n");
1186                 } else
1187                         printk(KERN_WARNING "CIFS: Unknown mount option %s\n",data);
1188         }
1189         if (vol->UNC == NULL) {
1190                 if(devname == NULL) {
1191                         printk(KERN_WARNING "CIFS: Missing UNC name for mount target\n");
1192                         return 1;
1193                 }
1194                 if ((temp_len = strnlen(devname, 300)) < 300) {
1195                         vol->UNC = kmalloc(temp_len+1,GFP_KERNEL);
1196                         if(vol->UNC == NULL)
1197                                 return 1;
1198                         strcpy(vol->UNC,devname);
1199                         if (strncmp(vol->UNC, "//", 2) == 0) {
1200                                 vol->UNC[0] = '\\';
1201                                 vol->UNC[1] = '\\';
1202                         } else if (strncmp(vol->UNC, "\\\\", 2) != 0) {
1203                                 printk(KERN_WARNING "CIFS: UNC Path does not begin with // or \\\\ \n");
1204                                 return 1;
1205                         }
1206                 } else {
1207                         printk(KERN_WARNING "CIFS: UNC name too long\n");
1208                         return 1;
1209                 }
1210         }
1211         if(vol->UNCip == NULL)
1212                 vol->UNCip = &vol->UNC[2];
1213
1214         return 0;
1215 }
1216
1217 static struct cifsSesInfo *
1218 cifs_find_tcp_session(struct in_addr * target_ip_addr, 
1219                 struct in6_addr *target_ip6_addr,
1220                  char *userName, struct TCP_Server_Info **psrvTcp)
1221 {
1222         struct list_head *tmp;
1223         struct cifsSesInfo *ses;
1224         *psrvTcp = NULL;
1225         read_lock(&GlobalSMBSeslock);
1226
1227         list_for_each(tmp, &GlobalSMBSessionList) {
1228                 ses = list_entry(tmp, struct cifsSesInfo, cifsSessionList);
1229                 if (ses->server) {
1230                         if((target_ip_addr && 
1231                                 (ses->server->addr.sockAddr.sin_addr.s_addr
1232                                   == target_ip_addr->s_addr)) || (target_ip6_addr
1233                                 && memcmp(&ses->server->addr.sockAddr6.sin6_addr,
1234                                         target_ip6_addr,sizeof(*target_ip6_addr)))){
1235                                 /* BB lock server and tcp session and increment use count here?? */
1236                                 *psrvTcp = ses->server; /* found a match on the TCP session */
1237                                 /* BB check if reconnection needed */
1238                                 if (strncmp
1239                                     (ses->userName, userName,
1240                                      MAX_USERNAME_SIZE) == 0){
1241                                         read_unlock(&GlobalSMBSeslock);
1242                                         return ses;     /* found exact match on both tcp and SMB sessions */
1243                                 }
1244                         }
1245                 }
1246                 /* else tcp and smb sessions need reconnection */
1247         }
1248         read_unlock(&GlobalSMBSeslock);
1249         return NULL;
1250 }
1251
1252 static struct cifsTconInfo *
1253 find_unc(__be32 new_target_ip_addr, char *uncName, char *userName)
1254 {
1255         struct list_head *tmp;
1256         struct cifsTconInfo *tcon;
1257
1258         read_lock(&GlobalSMBSeslock);
1259         list_for_each(tmp, &GlobalTreeConnectionList) {
1260                 cFYI(1, ("Next tcon - "));
1261                 tcon = list_entry(tmp, struct cifsTconInfo, cifsConnectionList);
1262                 if (tcon->ses) {
1263                         if (tcon->ses->server) {
1264                                 cFYI(1,
1265                                      (" old ip addr: %x == new ip %x ?",
1266                                       tcon->ses->server->addr.sockAddr.sin_addr.
1267                                       s_addr, new_target_ip_addr));
1268                                 if (tcon->ses->server->addr.sockAddr.sin_addr.
1269                                     s_addr == new_target_ip_addr) {
1270         /* BB lock tcon and server and tcp session and increment use count here? */
1271                                         /* found a match on the TCP session */
1272                                         /* BB check if reconnection needed */
1273                                         cFYI(1,("Matched ip, old UNC: %s == new: %s ?",
1274                                               tcon->treeName, uncName));
1275                                         if (strncmp
1276                                             (tcon->treeName, uncName,
1277                                              MAX_TREE_SIZE) == 0) {
1278                                                 cFYI(1,
1279                                                      ("Matched UNC, old user: %s == new: %s ?",
1280                                                       tcon->treeName, uncName));
1281                                                 if (strncmp
1282                                                     (tcon->ses->userName,
1283                                                      userName,
1284                                                      MAX_USERNAME_SIZE) == 0) {
1285                                                         read_unlock(&GlobalSMBSeslock);
1286                                                         return tcon;/* also matched user (smb session)*/
1287                                                 }
1288                                         }
1289                                 }
1290                         }
1291                 }
1292         }
1293         read_unlock(&GlobalSMBSeslock);
1294         return NULL;
1295 }
1296
1297 int
1298 connect_to_dfs_path(int xid, struct cifsSesInfo *pSesInfo,
1299                     const char *old_path, const struct nls_table *nls_codepage,
1300                     int remap)
1301 {
1302         unsigned char *referrals = NULL;
1303         unsigned int num_referrals;
1304         int rc = 0;
1305
1306         rc = get_dfs_path(xid, pSesInfo,old_path, nls_codepage, 
1307                         &num_referrals, &referrals, remap);
1308
1309         /* BB Add in code to: if valid refrl, if not ip address contact
1310                 the helper that resolves tcp names, mount to it, try to 
1311                 tcon to it unmount it if fail */
1312
1313         kfree(referrals);
1314
1315         return rc;
1316 }
1317
1318 int
1319 get_dfs_path(int xid, struct cifsSesInfo *pSesInfo,
1320                         const char *old_path, const struct nls_table *nls_codepage, 
1321                         unsigned int *pnum_referrals, 
1322                         unsigned char ** preferrals, int remap)
1323 {
1324         char *temp_unc;
1325         int rc = 0;
1326
1327         *pnum_referrals = 0;
1328
1329         if (pSesInfo->ipc_tid == 0) {
1330                 temp_unc = kmalloc(2 /* for slashes */ +
1331                         strnlen(pSesInfo->serverName,SERVER_NAME_LEN_WITH_NULL * 2)
1332                                  + 1 + 4 /* slash IPC$ */  + 2,
1333                                 GFP_KERNEL);
1334                 if (temp_unc == NULL)
1335                         return -ENOMEM;
1336                 temp_unc[0] = '\\';
1337                 temp_unc[1] = '\\';
1338                 strcpy(temp_unc + 2, pSesInfo->serverName);
1339                 strcpy(temp_unc + 2 + strlen(pSesInfo->serverName), "\\IPC$");
1340                 rc = CIFSTCon(xid, pSesInfo, temp_unc, NULL, nls_codepage);
1341                 cFYI(1,
1342                      ("CIFS Tcon rc = %d ipc_tid = %d", rc,pSesInfo->ipc_tid));
1343                 kfree(temp_unc);
1344         }
1345         if (rc == 0)
1346                 rc = CIFSGetDFSRefer(xid, pSesInfo, old_path, preferrals,
1347                                      pnum_referrals, nls_codepage, remap);
1348
1349         return rc;
1350 }
1351
1352 /* See RFC1001 section 14 on representation of Netbios names */
1353 static void rfc1002mangle(char * target,char * source, unsigned int length)
1354 {
1355         unsigned int i,j;
1356
1357         for(i=0,j=0;i<(length);i++) {
1358                 /* mask a nibble at a time and encode */
1359                 target[j] = 'A' + (0x0F & (source[i] >> 4));
1360                 target[j+1] = 'A' + (0x0F & source[i]);
1361                 j+=2;
1362         }
1363
1364 }
1365
1366
1367 static int
1368 ipv4_connect(struct sockaddr_in *psin_server, struct socket **csocket, 
1369              char * netbios_name, char * target_name)
1370 {
1371         int rc = 0;
1372         int connected = 0;
1373         __be16 orig_port = 0;
1374
1375         if(*csocket == NULL) {
1376                 rc = sock_create_kern(PF_INET, SOCK_STREAM, IPPROTO_TCP, csocket);
1377                 if (rc < 0) {
1378                         cERROR(1, ("Error %d creating socket",rc));
1379                         *csocket = NULL;
1380                         return rc;
1381                 } else {
1382                 /* BB other socket options to set KEEPALIVE, NODELAY? */
1383                         cFYI(1,("Socket created"));
1384                         (*csocket)->sk->sk_allocation = GFP_NOFS; 
1385                 }
1386         }
1387
1388         psin_server->sin_family = AF_INET;
1389         if(psin_server->sin_port) { /* user overrode default port */
1390                 rc = (*csocket)->ops->connect(*csocket,
1391                                 (struct sockaddr *) psin_server,
1392                                 sizeof (struct sockaddr_in),0);
1393                 if (rc >= 0)
1394                         connected = 1;
1395         } 
1396
1397         if(!connected) {
1398                 /* save original port so we can retry user specified port  
1399                         later if fall back ports fail this time  */
1400                 orig_port = psin_server->sin_port;
1401
1402                 /* do not retry on the same port we just failed on */
1403                 if(psin_server->sin_port != htons(CIFS_PORT)) {
1404                         psin_server->sin_port = htons(CIFS_PORT);
1405
1406                         rc = (*csocket)->ops->connect(*csocket,
1407                                         (struct sockaddr *) psin_server,
1408                                         sizeof (struct sockaddr_in),0);
1409                         if (rc >= 0)
1410                                 connected = 1;
1411                 }
1412         }
1413         if (!connected) {
1414                 psin_server->sin_port = htons(RFC1001_PORT);
1415                 rc = (*csocket)->ops->connect(*csocket, (struct sockaddr *)
1416                                               psin_server, sizeof (struct sockaddr_in),0);
1417                 if (rc >= 0) 
1418                         connected = 1;
1419         }
1420
1421         /* give up here - unless we want to retry on different
1422                 protocol families some day */
1423         if (!connected) {
1424                 if(orig_port)
1425                         psin_server->sin_port = orig_port;
1426                 cFYI(1,("Error %d connecting to server via ipv4",rc));
1427                 sock_release(*csocket);
1428                 *csocket = NULL;
1429                 return rc;
1430         }
1431         /* Eventually check for other socket options to change from 
1432                 the default. sock_setsockopt not used because it expects 
1433                 user space buffer */
1434          cFYI(1,("sndbuf %d rcvbuf %d rcvtimeo 0x%lx",(*csocket)->sk->sk_sndbuf,
1435                  (*csocket)->sk->sk_rcvbuf, (*csocket)->sk->sk_rcvtimeo));
1436         (*csocket)->sk->sk_rcvtimeo = 7 * HZ;
1437         /* make the bufsizes depend on wsize/rsize and max requests */
1438         if((*csocket)->sk->sk_sndbuf < (200 * 1024))
1439                 (*csocket)->sk->sk_sndbuf = 200 * 1024;
1440         if((*csocket)->sk->sk_rcvbuf < (140 * 1024))
1441                 (*csocket)->sk->sk_rcvbuf = 140 * 1024;
1442
1443         /* send RFC1001 sessinit */
1444         if(psin_server->sin_port == htons(RFC1001_PORT)) {
1445                 /* some servers require RFC1001 sessinit before sending
1446                 negprot - BB check reconnection in case where second 
1447                 sessinit is sent but no second negprot */
1448                 struct rfc1002_session_packet * ses_init_buf;
1449                 struct smb_hdr * smb_buf;
1450                 ses_init_buf = kzalloc(sizeof(struct rfc1002_session_packet), GFP_KERNEL);
1451                 if(ses_init_buf) {
1452                         ses_init_buf->trailer.session_req.called_len = 32;
1453                         if(target_name && (target_name[0] != 0)) {
1454                                 rfc1002mangle(ses_init_buf->trailer.session_req.called_name,
1455                                         target_name, 16);
1456                         } else {
1457                                 rfc1002mangle(ses_init_buf->trailer.session_req.called_name,
1458                                         DEFAULT_CIFS_CALLED_NAME,16);
1459                         }
1460
1461                         ses_init_buf->trailer.session_req.calling_len = 32;
1462                         /* calling name ends in null (byte 16) from old smb
1463                         convention. */
1464                         if(netbios_name && (netbios_name[0] !=0)) {
1465                                 rfc1002mangle(ses_init_buf->trailer.session_req.calling_name,
1466                                         netbios_name,16);
1467                         } else {
1468                                 rfc1002mangle(ses_init_buf->trailer.session_req.calling_name,
1469                                         "LINUX_CIFS_CLNT",16);
1470                         }
1471                         ses_init_buf->trailer.session_req.scope1 = 0;
1472                         ses_init_buf->trailer.session_req.scope2 = 0;
1473                         smb_buf = (struct smb_hdr *)ses_init_buf;
1474                         /* sizeof RFC1002_SESSION_REQUEST with no scope */
1475                         smb_buf->smb_buf_length = 0x81000044;
1476                         rc = smb_send(*csocket, smb_buf, 0x44,
1477                                 (struct sockaddr *)psin_server);
1478                         kfree(ses_init_buf);
1479                         msleep(1); /* RFC1001 layer in at least one server 
1480                                       requires very short break before negprot
1481                                       presumably because not expecting negprot
1482                                       to follow so fast.  This is a simple
1483                                       solution that works without 
1484                                       complicating the code and causes no
1485                                       significant slowing down on mount
1486                                       for everyone else */
1487                 }
1488                 /* else the negprot may still work without this 
1489                 even though malloc failed */
1490                 
1491         }
1492                 
1493         return rc;
1494 }
1495
1496 static int
1497 ipv6_connect(struct sockaddr_in6 *psin_server, struct socket **csocket)
1498 {
1499         int rc = 0;
1500         int connected = 0;
1501         __be16 orig_port = 0;
1502
1503         if(*csocket == NULL) {
1504                 rc = sock_create_kern(PF_INET6, SOCK_STREAM, IPPROTO_TCP, csocket);
1505                 if (rc < 0) {
1506                         cERROR(1, ("Error %d creating ipv6 socket",rc));
1507                         *csocket = NULL;
1508                         return rc;
1509                 } else {
1510                 /* BB other socket options to set KEEPALIVE, NODELAY? */
1511                          cFYI(1,("ipv6 Socket created"));
1512                         (*csocket)->sk->sk_allocation = GFP_NOFS;
1513                 }
1514         }
1515
1516         psin_server->sin6_family = AF_INET6;
1517
1518         if(psin_server->sin6_port) { /* user overrode default port */
1519                 rc = (*csocket)->ops->connect(*csocket,
1520                                 (struct sockaddr *) psin_server,
1521                                 sizeof (struct sockaddr_in6),0);
1522                 if (rc >= 0)
1523                         connected = 1;
1524         } 
1525
1526         if(!connected) {
1527                 /* save original port so we can retry user specified port  
1528                         later if fall back ports fail this time  */
1529
1530                 orig_port = psin_server->sin6_port;
1531                 /* do not retry on the same port we just failed on */
1532                 if(psin_server->sin6_port != htons(CIFS_PORT)) {
1533                         psin_server->sin6_port = htons(CIFS_PORT);
1534
1535                         rc = (*csocket)->ops->connect(*csocket,
1536                                         (struct sockaddr *) psin_server,
1537                                         sizeof (struct sockaddr_in6),0);
1538                         if (rc >= 0)
1539                                 connected = 1;
1540                 }
1541         }
1542         if (!connected) {
1543                 psin_server->sin6_port = htons(RFC1001_PORT);
1544                 rc = (*csocket)->ops->connect(*csocket, (struct sockaddr *)
1545                                          psin_server, sizeof (struct sockaddr_in6),0);
1546                 if (rc >= 0) 
1547                         connected = 1;
1548         }
1549
1550         /* give up here - unless we want to retry on different
1551                 protocol families some day */
1552         if (!connected) {
1553                 if(orig_port)
1554                         psin_server->sin6_port = orig_port;
1555                 cFYI(1,("Error %d connecting to server via ipv6",rc));
1556                 sock_release(*csocket);
1557                 *csocket = NULL;
1558                 return rc;
1559         }
1560         /* Eventually check for other socket options to change from 
1561                 the default. sock_setsockopt not used because it expects 
1562                 user space buffer */
1563         (*csocket)->sk->sk_rcvtimeo = 7 * HZ;
1564                 
1565         return rc;
1566 }
1567
1568 int
1569 cifs_mount(struct super_block *sb, struct cifs_sb_info *cifs_sb,
1570            char *mount_data, const char *devname)
1571 {
1572         int rc = 0;
1573         int xid;
1574         int address_type = AF_INET;
1575         struct socket *csocket = NULL;
1576         struct sockaddr_in sin_server;
1577         struct sockaddr_in6 sin_server6;
1578         struct smb_vol volume_info;
1579         struct cifsSesInfo *pSesInfo = NULL;
1580         struct cifsSesInfo *existingCifsSes = NULL;
1581         struct cifsTconInfo *tcon = NULL;
1582         struct TCP_Server_Info *srvTcp = NULL;
1583
1584         xid = GetXid();
1585
1586 /* cFYI(1, ("Entering cifs_mount. Xid: %d with: %s", xid, mount_data)); */
1587         
1588         memset(&volume_info,0,sizeof(struct smb_vol));
1589         if (cifs_parse_mount_options(mount_data, devname, &volume_info)) {
1590                 kfree(volume_info.UNC);
1591                 kfree(volume_info.password);
1592                 FreeXid(xid);
1593                 return -EINVAL;
1594         }
1595
1596         if (volume_info.username) {
1597                 /* BB fixme parse for domain name here */
1598                 cFYI(1, ("Username: %s ", volume_info.username));
1599
1600         } else {
1601                 cifserror("No username specified");
1602         /* In userspace mount helper we can get user name from alternate
1603            locations such as env variables and files on disk */
1604                 kfree(volume_info.UNC);
1605                 kfree(volume_info.password);
1606                 FreeXid(xid);
1607                 return -EINVAL;
1608         }
1609
1610         if (volume_info.UNCip && volume_info.UNC) {
1611                 rc = cifs_inet_pton(AF_INET, volume_info.UNCip,&sin_server.sin_addr.s_addr);
1612
1613                 if(rc <= 0) {
1614                         /* not ipv4 address, try ipv6 */
1615                         rc = cifs_inet_pton(AF_INET6,volume_info.UNCip,&sin_server6.sin6_addr.in6_u); 
1616                         if(rc > 0)
1617                                 address_type = AF_INET6;
1618                 } else {
1619                         address_type = AF_INET;
1620                 }
1621        
1622                 if(rc <= 0) {
1623                         /* we failed translating address */
1624                         kfree(volume_info.UNC);
1625                         kfree(volume_info.password);
1626                         FreeXid(xid);
1627                         return -EINVAL;
1628                 }
1629
1630                 cFYI(1, ("UNC: %s ip: %s", volume_info.UNC, volume_info.UNCip));
1631                 /* success */
1632                 rc = 0;
1633         } else if (volume_info.UNCip){
1634                 /* BB using ip addr as server name connect to the DFS root below */
1635                 cERROR(1,("Connecting to DFS root not implemented yet"));
1636                 kfree(volume_info.UNC);
1637                 kfree(volume_info.password);
1638                 FreeXid(xid);
1639                 return -EINVAL;
1640         } else /* which servers DFS root would we conect to */ {
1641                 cERROR(1,
1642                        ("CIFS mount error: No UNC path (e.g. -o unc=//192.168.1.100/public) specified"));
1643                 kfree(volume_info.UNC);
1644                 kfree(volume_info.password);
1645                 FreeXid(xid);
1646                 return -EINVAL;
1647         }
1648
1649         /* this is needed for ASCII cp to Unicode converts */
1650         if(volume_info.iocharset == NULL) {
1651                 cifs_sb->local_nls = load_nls_default();
1652         /* load_nls_default can not return null */
1653         } else {
1654                 cifs_sb->local_nls = load_nls(volume_info.iocharset);
1655                 if(cifs_sb->local_nls == NULL) {
1656                         cERROR(1,("CIFS mount error: iocharset %s not found",volume_info.iocharset));
1657                         kfree(volume_info.UNC);
1658                         kfree(volume_info.password);
1659                         FreeXid(xid);
1660                         return -ELIBACC;
1661                 }
1662         }
1663
1664         if(address_type == AF_INET)
1665                 existingCifsSes = cifs_find_tcp_session(&sin_server.sin_addr,
1666                         NULL /* no ipv6 addr */,
1667                         volume_info.username, &srvTcp);
1668         else if(address_type == AF_INET6)
1669                 existingCifsSes = cifs_find_tcp_session(NULL /* no ipv4 addr */,
1670                         &sin_server6.sin6_addr,
1671                         volume_info.username, &srvTcp);
1672         else {
1673                 kfree(volume_info.UNC);
1674                 kfree(volume_info.password);
1675                 FreeXid(xid);
1676                 return -EINVAL;
1677         }
1678
1679
1680         if (srvTcp) {
1681                 cFYI(1, ("Existing tcp session with server found"));                
1682         } else {        /* create socket */
1683                 if(volume_info.port)
1684                         sin_server.sin_port = htons(volume_info.port);
1685                 else
1686                         sin_server.sin_port = 0;
1687                 rc = ipv4_connect(&sin_server,&csocket,
1688                                   volume_info.source_rfc1001_name,
1689                                   volume_info.target_rfc1001_name);
1690                 if (rc < 0) {
1691                         cERROR(1,
1692                                ("Error connecting to IPv4 socket. Aborting operation"));
1693                         if(csocket != NULL)
1694                                 sock_release(csocket);
1695                         kfree(volume_info.UNC);
1696                         kfree(volume_info.password);
1697                         FreeXid(xid);
1698                         return rc;
1699                 }
1700
1701                 srvTcp = kmalloc(sizeof (struct TCP_Server_Info), GFP_KERNEL);
1702                 if (srvTcp == NULL) {
1703                         rc = -ENOMEM;
1704                         sock_release(csocket);
1705                         kfree(volume_info.UNC);
1706                         kfree(volume_info.password);
1707                         FreeXid(xid);
1708                         return rc;
1709                 } else {
1710                         memset(srvTcp, 0, sizeof (struct TCP_Server_Info));
1711                         memcpy(&srvTcp->addr.sockAddr, &sin_server, sizeof (struct sockaddr_in));
1712                         atomic_set(&srvTcp->inFlight,0);
1713                         /* BB Add code for ipv6 case too */
1714                         srvTcp->ssocket = csocket;
1715                         srvTcp->protocolType = IPV4;
1716                         init_waitqueue_head(&srvTcp->response_q);
1717                         init_waitqueue_head(&srvTcp->request_q);
1718                         INIT_LIST_HEAD(&srvTcp->pending_mid_q);
1719                         /* at this point we are the only ones with the pointer
1720                         to the struct since the kernel thread not created yet
1721                         so no need to spinlock this init of tcpStatus */
1722                         srvTcp->tcpStatus = CifsNew;
1723                         init_MUTEX(&srvTcp->tcpSem);
1724                         rc = (int)kernel_thread((void *)(void *)cifs_demultiplex_thread, srvTcp,
1725                                       CLONE_FS | CLONE_FILES | CLONE_VM);
1726                         if(rc < 0) {
1727                                 rc = -ENOMEM;
1728                                 sock_release(csocket);
1729                                 kfree(volume_info.UNC);
1730                                 kfree(volume_info.password);
1731                                 FreeXid(xid);
1732                                 return rc;
1733                         }
1734                         wait_for_completion(&cifsd_complete);
1735                         rc = 0;
1736                         memcpy(srvTcp->workstation_RFC1001_name, volume_info.source_rfc1001_name,16);
1737                         memcpy(srvTcp->server_RFC1001_name, volume_info.target_rfc1001_name,16);
1738                         srvTcp->sequence_number = 0;
1739                 }
1740         }
1741
1742         if (existingCifsSes) {
1743                 pSesInfo = existingCifsSes;
1744                 cFYI(1, ("Existing smb sess found"));
1745                 kfree(volume_info.password);
1746                 /* volume_info.UNC freed at end of function */
1747         } else if (!rc) {
1748                 cFYI(1, ("Existing smb sess not found"));
1749                 pSesInfo = sesInfoAlloc();
1750                 if (pSesInfo == NULL)
1751                         rc = -ENOMEM;
1752                 else {
1753                         pSesInfo->server = srvTcp;
1754                         sprintf(pSesInfo->serverName, "%u.%u.%u.%u",
1755                                 NIPQUAD(sin_server.sin_addr.s_addr));
1756                 }
1757
1758                 if (!rc){
1759                         /* volume_info.password freed at unmount */   
1760                         if (volume_info.password)
1761                                 pSesInfo->password = volume_info.password;
1762                         if (volume_info.username)
1763                                 strncpy(pSesInfo->userName,
1764                                         volume_info.username,MAX_USERNAME_SIZE);
1765                         if (volume_info.domainname)
1766                                 strncpy(pSesInfo->domainName,
1767                                         volume_info.domainname,MAX_USERNAME_SIZE);
1768                         pSesInfo->linux_uid = volume_info.linux_uid;
1769                         down(&pSesInfo->sesSem);
1770                         rc = cifs_setup_session(xid,pSesInfo, cifs_sb->local_nls);
1771                         up(&pSesInfo->sesSem);
1772                         if(!rc)
1773                                 atomic_inc(&srvTcp->socketUseCount);
1774                 } else
1775                         kfree(volume_info.password);
1776         }
1777     
1778         /* search for existing tcon to this server share */
1779         if (!rc) {
1780                 if(volume_info.rsize > CIFSMaxBufSize) {
1781                         cERROR(1,("rsize %d too large, using MaxBufSize",
1782                                 volume_info.rsize));
1783                         cifs_sb->rsize = CIFSMaxBufSize;
1784                 } else if((volume_info.rsize) && (volume_info.rsize <= CIFSMaxBufSize))
1785                         cifs_sb->rsize = volume_info.rsize;
1786                 else /* default */
1787                         cifs_sb->rsize = CIFSMaxBufSize;
1788
1789                 if(volume_info.wsize > PAGEVEC_SIZE * PAGE_CACHE_SIZE) {
1790                         cERROR(1,("wsize %d too large using 4096 instead",
1791                                   volume_info.wsize));
1792                         cifs_sb->wsize = 4096;
1793                 } else if(volume_info.wsize)
1794                         cifs_sb->wsize = volume_info.wsize;
1795                 else
1796                         cifs_sb->wsize = 
1797                                 min_t(const int, PAGEVEC_SIZE * PAGE_CACHE_SIZE,
1798                                         127*1024);
1799                         /* old default of CIFSMaxBufSize was too small now
1800                            that SMB Write2 can send multiple pages in kvec.   
1801                            RFC1001 does not describe what happens when frame
1802                            bigger than 128K is sent so use that as max in
1803                            conjunction with 52K kvec constraint on arch with 4K
1804                            page size  */
1805
1806                 if(cifs_sb->rsize < 2048) {
1807                         cifs_sb->rsize = 2048; 
1808                         /* Windows ME may prefer this */
1809                         cFYI(1,("readsize set to minimum 2048"));
1810                 }
1811                 cifs_sb->mnt_uid = volume_info.linux_uid;
1812                 cifs_sb->mnt_gid = volume_info.linux_gid;
1813                 cifs_sb->mnt_file_mode = volume_info.file_mode;
1814                 cifs_sb->mnt_dir_mode = volume_info.dir_mode;
1815                 cFYI(1,("file mode: 0x%x  dir mode: 0x%x",
1816                         cifs_sb->mnt_file_mode,cifs_sb->mnt_dir_mode));
1817
1818                 if(volume_info.noperm)
1819                         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_PERM;
1820                 if(volume_info.setuids)
1821                         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_SET_UID;
1822                 if(volume_info.server_ino)
1823                         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_SERVER_INUM;
1824                 if(volume_info.remap)
1825                         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_MAP_SPECIAL_CHR;
1826                 if(volume_info.no_xattr)
1827                         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_XATTR;
1828                 if(volume_info.sfu_emul)
1829                         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_UNX_EMUL;
1830                 if(volume_info.nobrl)
1831                         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_BRL;
1832                 if(volume_info.cifs_acl)
1833                         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_CIFS_ACL;
1834
1835                 if(volume_info.direct_io) {
1836                         cFYI(1,("mounting share using direct i/o"));
1837                         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_DIRECT_IO;
1838                 }
1839
1840                 tcon =
1841                     find_unc(sin_server.sin_addr.s_addr, volume_info.UNC,
1842                              volume_info.username);
1843                 if (tcon) {
1844                         cFYI(1, ("Found match on UNC path"));
1845                         /* we can have only one retry value for a connection
1846                            to a share so for resources mounted more than once
1847                            to the same server share the last value passed in 
1848                            for the retry flag is used */
1849                         tcon->retry = volume_info.retry;
1850                         tcon->nocase = volume_info.nocase;
1851                 } else {
1852                         tcon = tconInfoAlloc();
1853                         if (tcon == NULL)
1854                                 rc = -ENOMEM;
1855                         else {
1856                                 /* check for null share name ie connect to dfs root */
1857
1858                                 /* BB check if this works for exactly length three strings */
1859                                 if ((strchr(volume_info.UNC + 3, '\\') == NULL)
1860                                     && (strchr(volume_info.UNC + 3, '/') ==
1861                                         NULL)) {
1862                                         rc = connect_to_dfs_path(xid, pSesInfo,
1863                                                         "", cifs_sb->local_nls,
1864                                                         cifs_sb->mnt_cifs_flags & 
1865                                                           CIFS_MOUNT_MAP_SPECIAL_CHR);
1866                                         kfree(volume_info.UNC);
1867                                         FreeXid(xid);
1868                                         return -ENODEV;
1869                                 } else {
1870                                         rc = CIFSTCon(xid, pSesInfo, 
1871                                                 volume_info.UNC,
1872                                                 tcon, cifs_sb->local_nls);
1873                                         cFYI(1, ("CIFS Tcon rc = %d", rc));
1874                                 }
1875                                 if (!rc) {
1876                                         atomic_inc(&pSesInfo->inUse);
1877                                         tcon->retry = volume_info.retry;
1878                                         tcon->nocase = volume_info.nocase;
1879                                 }
1880                         }
1881                 }
1882         }
1883         if(pSesInfo) {
1884                 if (pSesInfo->capabilities & CAP_LARGE_FILES) {
1885                         sb->s_maxbytes = (u64) 1 << 63;
1886                 } else
1887                         sb->s_maxbytes = (u64) 1 << 31; /* 2 GB */
1888         }
1889
1890         sb->s_time_gran = 100;
1891
1892 /* on error free sesinfo and tcon struct if needed */
1893         if (rc) {
1894                 /* if session setup failed, use count is zero but
1895                 we still need to free cifsd thread */
1896                 if(atomic_read(&srvTcp->socketUseCount) == 0) {
1897                         spin_lock(&GlobalMid_Lock);
1898                         srvTcp->tcpStatus = CifsExiting;
1899                         spin_unlock(&GlobalMid_Lock);
1900                         if(srvTcp->tsk) {
1901                                 send_sig(SIGKILL,srvTcp->tsk,1);
1902                                 wait_for_completion(&cifsd_complete);
1903                         }
1904                 }
1905                  /* If find_unc succeeded then rc == 0 so we can not end */
1906                 if (tcon)  /* up accidently freeing someone elses tcon struct */
1907                         tconInfoFree(tcon);
1908                 if (existingCifsSes == NULL) {
1909                         if (pSesInfo) {
1910                                 if ((pSesInfo->server) && 
1911                                     (pSesInfo->status == CifsGood)) {
1912                                         int temp_rc;
1913                                         temp_rc = CIFSSMBLogoff(xid, pSesInfo);
1914                                         /* if the socketUseCount is now zero */
1915                                         if((temp_rc == -ESHUTDOWN) &&
1916                                            (pSesInfo->server->tsk)) {
1917                                                 send_sig(SIGKILL,pSesInfo->server->tsk,1);
1918                                                 wait_for_completion(&cifsd_complete);
1919                                         }
1920                                 } else
1921                                         cFYI(1, ("No session or bad tcon"));
1922                                 sesInfoFree(pSesInfo);
1923                                 /* pSesInfo = NULL; */
1924                         }
1925                 }
1926         } else {
1927                 atomic_inc(&tcon->useCount);
1928                 cifs_sb->tcon = tcon;
1929                 tcon->ses = pSesInfo;
1930
1931                 /* do not care if following two calls succeed - informational */
1932                 CIFSSMBQFSDeviceInfo(xid, tcon);
1933                 CIFSSMBQFSAttributeInfo(xid, tcon);
1934
1935                 if (tcon->ses->capabilities & CAP_UNIX) {
1936                         if(!CIFSSMBQFSUnixInfo(xid, tcon)) {
1937                                 __u64 cap = 
1938                                        le64_to_cpu(tcon->fsUnixInfo.Capability);
1939                                 cap &= CIFS_UNIX_CAP_MASK;
1940                                 if(volume_info.no_psx_acl)
1941                                         cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
1942                                 else if(CIFS_UNIX_POSIX_ACL_CAP & cap) {
1943                                         cFYI(1,("negotiated posix acl support"));
1944                                         sb->s_flags |= MS_POSIXACL;
1945                                 }
1946
1947                                 if(volume_info.posix_paths == 0)
1948                                         cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
1949                                 else if(cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
1950                                         cFYI(1,("negotiate posix pathnames"));
1951                                         cifs_sb->mnt_cifs_flags |= 
1952                                                 CIFS_MOUNT_POSIX_PATHS;
1953                                 }
1954                                         
1955                                 cFYI(1,("Negotiate caps 0x%x",(int)cap));
1956
1957                                 if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
1958                                         cFYI(1,("setting capabilities failed"));
1959                                 }
1960                         }
1961                 }
1962                 if (!(tcon->ses->capabilities & CAP_LARGE_WRITE_X))
1963                         cifs_sb->wsize = min(cifs_sb->wsize,
1964                                              (tcon->ses->server->maxBuf -
1965                                               MAX_CIFS_HDR_SIZE));
1966                 if (!(tcon->ses->capabilities & CAP_LARGE_READ_X))
1967                         cifs_sb->rsize = min(cifs_sb->rsize,
1968                                              (tcon->ses->server->maxBuf -
1969                                               MAX_CIFS_HDR_SIZE));
1970         }
1971
1972         /* volume_info.password is freed above when existing session found
1973         (in which case it is not needed anymore) but when new sesion is created
1974         the password ptr is put in the new session structure (in which case the
1975         password will be freed at unmount time) */
1976         kfree(volume_info.UNC);
1977         FreeXid(xid);
1978         return rc;
1979 }
1980
1981 static int
1982 CIFSSessSetup(unsigned int xid, struct cifsSesInfo *ses,
1983               char session_key[CIFS_SESSION_KEY_SIZE],
1984               const struct nls_table *nls_codepage)
1985 {
1986         struct smb_hdr *smb_buffer;
1987         struct smb_hdr *smb_buffer_response;
1988         SESSION_SETUP_ANDX *pSMB;
1989         SESSION_SETUP_ANDX *pSMBr;
1990         char *bcc_ptr;
1991         char *user;
1992         char *domain;
1993         int rc = 0;
1994         int remaining_words = 0;
1995         int bytes_returned = 0;
1996         int len;
1997         __u32 capabilities;
1998         __u16 count;
1999
2000         cFYI(1, ("In sesssetup"));
2001         if(ses == NULL)
2002                 return -EINVAL;
2003         user = ses->userName;
2004         domain = ses->domainName;
2005         smb_buffer = cifs_buf_get();
2006         if (smb_buffer == NULL) {
2007                 return -ENOMEM;
2008         }
2009         smb_buffer_response = smb_buffer;
2010         pSMBr = pSMB = (SESSION_SETUP_ANDX *) smb_buffer;
2011
2012         /* send SMBsessionSetup here */
2013         header_assemble(smb_buffer, SMB_COM_SESSION_SETUP_ANDX,
2014                         NULL /* no tCon exists yet */ , 13 /* wct */ );
2015
2016         smb_buffer->Mid = GetNextMid(ses->server);
2017         pSMB->req_no_secext.AndXCommand = 0xFF;
2018         pSMB->req_no_secext.MaxBufferSize = cpu_to_le16(ses->server->maxBuf);
2019         pSMB->req_no_secext.MaxMpxCount = cpu_to_le16(ses->server->maxReq);
2020
2021         if(ses->server->secMode & (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED))
2022                 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
2023
2024         capabilities = CAP_LARGE_FILES | CAP_NT_SMBS | CAP_LEVEL_II_OPLOCKS |
2025                 CAP_LARGE_WRITE_X | CAP_LARGE_READ_X;
2026         if (ses->capabilities & CAP_UNICODE) {
2027                 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
2028                 capabilities |= CAP_UNICODE;
2029         }
2030         if (ses->capabilities & CAP_STATUS32) {
2031                 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
2032                 capabilities |= CAP_STATUS32;
2033         }
2034         if (ses->capabilities & CAP_DFS) {
2035                 smb_buffer->Flags2 |= SMBFLG2_DFS;
2036                 capabilities |= CAP_DFS;
2037         }
2038         pSMB->req_no_secext.Capabilities = cpu_to_le32(capabilities);
2039
2040         pSMB->req_no_secext.CaseInsensitivePasswordLength = 
2041                 cpu_to_le16(CIFS_SESSION_KEY_SIZE);
2042
2043         pSMB->req_no_secext.CaseSensitivePasswordLength =
2044             cpu_to_le16(CIFS_SESSION_KEY_SIZE);
2045         bcc_ptr = pByteArea(smb_buffer);
2046         memcpy(bcc_ptr, (char *) session_key, CIFS_SESSION_KEY_SIZE);
2047         bcc_ptr += CIFS_SESSION_KEY_SIZE;
2048         memcpy(bcc_ptr, (char *) session_key, CIFS_SESSION_KEY_SIZE);
2049         bcc_ptr += CIFS_SESSION_KEY_SIZE;
2050
2051         if (ses->capabilities & CAP_UNICODE) {
2052                 if ((long) bcc_ptr % 2) { /* must be word aligned for Unicode */
2053                         *bcc_ptr = 0;
2054                         bcc_ptr++;
2055                 }
2056                 if(user == NULL)
2057                         bytes_returned = 0; /* skill null user */
2058                 else
2059                         bytes_returned =
2060                                 cifs_strtoUCS((__le16 *) bcc_ptr, user, 100,
2061                                         nls_codepage);
2062                 /* convert number of 16 bit words to bytes */
2063                 bcc_ptr += 2 * bytes_returned;
2064                 bcc_ptr += 2;   /* trailing null */
2065                 if (domain == NULL)
2066                         bytes_returned =
2067                             cifs_strtoUCS((__le16 *) bcc_ptr,
2068                                           "CIFS_LINUX_DOM", 32, nls_codepage);
2069                 else
2070                         bytes_returned =
2071                             cifs_strtoUCS((__le16 *) bcc_ptr, domain, 64,
2072                                           nls_codepage);
2073                 bcc_ptr += 2 * bytes_returned;
2074                 bcc_ptr += 2;
2075                 bytes_returned =
2076                     cifs_strtoUCS((__le16 *) bcc_ptr, "Linux version ",
2077                                   32, nls_codepage);
2078                 bcc_ptr += 2 * bytes_returned;
2079                 bytes_returned =
2080                     cifs_strtoUCS((__le16 *) bcc_ptr, system_utsname.release,
2081                                   32, nls_codepage);
2082                 bcc_ptr += 2 * bytes_returned;
2083                 bcc_ptr += 2;
2084                 bytes_returned =
2085                     cifs_strtoUCS((__le16 *) bcc_ptr, CIFS_NETWORK_OPSYS,
2086                                   64, nls_codepage);
2087                 bcc_ptr += 2 * bytes_returned;
2088                 bcc_ptr += 2;
2089         } else {
2090                 if(user != NULL) {                
2091                     strncpy(bcc_ptr, user, 200);
2092                     bcc_ptr += strnlen(user, 200);
2093                 }
2094                 *bcc_ptr = 0;
2095                 bcc_ptr++;
2096                 if (domain == NULL) {
2097                         strcpy(bcc_ptr, "CIFS_LINUX_DOM");
2098                         bcc_ptr += strlen("CIFS_LINUX_DOM") + 1;
2099                 } else {
2100                         strncpy(bcc_ptr, domain, 64);
2101                         bcc_ptr += strnlen(domain, 64);
2102                         *bcc_ptr = 0;
2103                         bcc_ptr++;
2104                 }
2105                 strcpy(bcc_ptr, "Linux version ");
2106                 bcc_ptr += strlen("Linux version ");
2107                 strcpy(bcc_ptr, system_utsname.release);
2108                 bcc_ptr += strlen(system_utsname.release) + 1;
2109                 strcpy(bcc_ptr, CIFS_NETWORK_OPSYS);
2110                 bcc_ptr += strlen(CIFS_NETWORK_OPSYS) + 1;
2111         }
2112         count = (long) bcc_ptr - (long) pByteArea(smb_buffer);
2113         smb_buffer->smb_buf_length += count;
2114         pSMB->req_no_secext.ByteCount = cpu_to_le16(count);
2115
2116         rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response,
2117                          &bytes_returned, 1);
2118         if (rc) {
2119 /* rc = map_smb_to_linux_error(smb_buffer_response); now done in SendReceive */
2120         } else if ((smb_buffer_response->WordCount == 3)
2121                    || (smb_buffer_response->WordCount == 4)) {
2122                 __u16 action = le16_to_cpu(pSMBr->resp.Action);
2123                 __u16 blob_len = le16_to_cpu(pSMBr->resp.SecurityBlobLength);
2124                 if (action & GUEST_LOGIN)
2125                         cFYI(1, (" Guest login"));      /* do we want to mark SesInfo struct ? */
2126                 ses->Suid = smb_buffer_response->Uid;   /* UID left in wire format (le) */
2127                 cFYI(1, ("UID = %d ", ses->Suid));
2128          /* response can have either 3 or 4 word count - Samba sends 3 */
2129                 bcc_ptr = pByteArea(smb_buffer_response);       
2130                 if ((pSMBr->resp.hdr.WordCount == 3)
2131                     || ((pSMBr->resp.hdr.WordCount == 4)
2132                         && (blob_len < pSMBr->resp.ByteCount))) {
2133                         if (pSMBr->resp.hdr.WordCount == 4)
2134                                 bcc_ptr += blob_len;
2135
2136                         if (smb_buffer->Flags2 & SMBFLG2_UNICODE) {
2137                                 if ((long) (bcc_ptr) % 2) {
2138                                         remaining_words =
2139                                             (BCC(smb_buffer_response) - 1) /2;
2140                                         bcc_ptr++;      /* Unicode strings must be word aligned */
2141                                 } else {
2142                                         remaining_words =
2143                                                 BCC(smb_buffer_response) / 2;
2144                                 }
2145                                 len =
2146                                     UniStrnlen((wchar_t *) bcc_ptr,
2147                                                remaining_words - 1);
2148 /* We look for obvious messed up bcc or strings in response so we do not go off
2149    the end since (at least) WIN2K and Windows XP have a major bug in not null
2150    terminating last Unicode string in response  */
2151                                 if(ses->serverOS)
2152                                         kfree(ses->serverOS);
2153                                 ses->serverOS = kzalloc(2 * (len + 1), GFP_KERNEL);
2154                                 if(ses->serverOS == NULL)
2155                                         goto sesssetup_nomem;
2156                                 cifs_strfromUCS_le(ses->serverOS,
2157                                            (__le16 *)bcc_ptr, len,nls_codepage);
2158                                 bcc_ptr += 2 * (len + 1);
2159                                 remaining_words -= len + 1;
2160                                 ses->serverOS[2 * len] = 0;
2161                                 ses->serverOS[1 + (2 * len)] = 0;
2162                                 if (remaining_words > 0) {
2163                                         len = UniStrnlen((wchar_t *)bcc_ptr,
2164                                                          remaining_words-1);
2165                                         if(ses->serverNOS)
2166                                                 kfree(ses->serverNOS);
2167                                         ses->serverNOS = kzalloc(2 * (len + 1),GFP_KERNEL);
2168                                         if(ses->serverNOS == NULL)
2169                                                 goto sesssetup_nomem;
2170                                         cifs_strfromUCS_le(ses->serverNOS,
2171                                                            (__le16 *)bcc_ptr,len,nls_codepage);
2172                                         bcc_ptr += 2 * (len + 1);
2173                                         ses->serverNOS[2 * len] = 0;
2174                                         ses->serverNOS[1 + (2 * len)] = 0;
2175                                         if(strncmp(ses->serverNOS,
2176                                                 "NT LAN Manager 4",16) == 0) {
2177                                                 cFYI(1,("NT4 server"));
2178                                                 ses->flags |= CIFS_SES_NT4;
2179                                         }
2180                                         remaining_words -= len + 1;
2181                                         if (remaining_words > 0) {
2182                                                 len = UniStrnlen((wchar_t *) bcc_ptr, remaining_words);
2183           /* last string is not always null terminated (for e.g. for Windows XP & 2000) */
2184                                                 if(ses->serverDomain)
2185                                                         kfree(ses->serverDomain);
2186                                                 ses->serverDomain =
2187                                                     kzalloc(2*(len+1),GFP_KERNEL);
2188                                                 if(ses->serverDomain == NULL)
2189                                                         goto sesssetup_nomem;
2190                                                 cifs_strfromUCS_le(ses->serverDomain,
2191                                                      (__le16 *)bcc_ptr,len,nls_codepage);
2192                                                 bcc_ptr += 2 * (len + 1);
2193                                                 ses->serverDomain[2*len] = 0;
2194                                                 ses->serverDomain[1+(2*len)] = 0;
2195                                         } /* else no more room so create dummy domain string */
2196                                         else {
2197                                                 if(ses->serverDomain)
2198                                                         kfree(ses->serverDomain);
2199                                                 ses->serverDomain = 
2200                                                         kzalloc(2, GFP_KERNEL);
2201                                         }
2202                                 } else {        /* no room so create dummy domain and NOS string */
2203                                         /* if these kcallocs fail not much we
2204                                            can do, but better to not fail the
2205                                            sesssetup itself */
2206                                         if(ses->serverDomain)
2207                                                 kfree(ses->serverDomain);
2208                                         ses->serverDomain =
2209                                             kzalloc(2, GFP_KERNEL);
2210                                         if(ses->serverNOS)
2211                                                 kfree(ses->serverNOS);
2212                                         ses->serverNOS =
2213                                             kzalloc(2, GFP_KERNEL);
2214                                 }
2215                         } else {        /* ASCII */
2216                                 len = strnlen(bcc_ptr, 1024);
2217                                 if (((long) bcc_ptr + len) - (long)
2218                                     pByteArea(smb_buffer_response)
2219                                             <= BCC(smb_buffer_response)) {
2220                                         if(ses->serverOS)
2221                                                 kfree(ses->serverOS);
2222                                         ses->serverOS = kzalloc(len + 1,GFP_KERNEL);
2223                                         if(ses->serverOS == NULL)
2224                                                 goto sesssetup_nomem;
2225                                         strncpy(ses->serverOS,bcc_ptr, len);
2226
2227                                         bcc_ptr += len;
2228                                         bcc_ptr[0] = 0; /* null terminate the string */
2229                                         bcc_ptr++;
2230
2231                                         len = strnlen(bcc_ptr, 1024);
2232                                         if(ses->serverNOS)
2233                                                 kfree(ses->serverNOS);
2234                                         ses->serverNOS = kzalloc(len + 1,GFP_KERNEL);
2235                                         if(ses->serverNOS == NULL)
2236                                                 goto sesssetup_nomem;
2237                                         strncpy(ses->serverNOS, bcc_ptr, len);
2238                                         bcc_ptr += len;
2239                                         bcc_ptr[0] = 0;
2240                                         bcc_ptr++;
2241
2242                                         len = strnlen(bcc_ptr, 1024);
2243                                         if(ses->serverDomain)
2244                                                 kfree(ses->serverDomain);
2245                                         ses->serverDomain = kzalloc(len + 1,GFP_KERNEL);
2246                                         if(ses->serverDomain == NULL)
2247                                                 goto sesssetup_nomem;
2248                                         strncpy(ses->serverDomain, bcc_ptr, len);
2249                                         bcc_ptr += len;
2250                                         bcc_ptr[0] = 0;
2251                                         bcc_ptr++;
2252                                 } else
2253                                         cFYI(1,
2254                                              ("Variable field of length %d extends beyond end of smb ",
2255                                               len));
2256                         }
2257                 } else {
2258                         cERROR(1,
2259                                (" Security Blob Length extends beyond end of SMB"));
2260                 }
2261         } else {
2262                 cERROR(1,
2263                        (" Invalid Word count %d: ",
2264                         smb_buffer_response->WordCount));
2265                 rc = -EIO;
2266         }
2267 sesssetup_nomem:        /* do not return an error on nomem for the info strings,
2268                            since that could make reconnection harder, and
2269                            reconnection might be needed to free memory */
2270         if (smb_buffer)
2271                 cifs_buf_release(smb_buffer);
2272
2273         return rc;
2274 }
2275
2276 static int
2277 CIFSSpnegoSessSetup(unsigned int xid, struct cifsSesInfo *ses,
2278                 char *SecurityBlob,int SecurityBlobLength,
2279                 const struct nls_table *nls_codepage)
2280 {
2281         struct smb_hdr *smb_buffer;
2282         struct smb_hdr *smb_buffer_response;
2283         SESSION_SETUP_ANDX *pSMB;
2284         SESSION_SETUP_ANDX *pSMBr;
2285         char *bcc_ptr;
2286         char *user;
2287         char *domain;
2288         int rc = 0;
2289         int remaining_words = 0;
2290         int bytes_returned = 0;
2291         int len;
2292         __u32 capabilities;
2293         __u16 count;
2294
2295         cFYI(1, ("In spnego sesssetup "));
2296         if(ses == NULL)
2297                 return -EINVAL;
2298         user = ses->userName;
2299         domain = ses->domainName;
2300
2301         smb_buffer = cifs_buf_get();
2302         if (smb_buffer == NULL) {
2303                 return -ENOMEM;
2304         }
2305         smb_buffer_response = smb_buffer;
2306         pSMBr = pSMB = (SESSION_SETUP_ANDX *) smb_buffer;
2307
2308         /* send SMBsessionSetup here */
2309         header_assemble(smb_buffer, SMB_COM_SESSION_SETUP_ANDX,
2310                         NULL /* no tCon exists yet */ , 12 /* wct */ );
2311
2312         smb_buffer->Mid = GetNextMid(ses->server);
2313         pSMB->req.hdr.Flags2 |= SMBFLG2_EXT_SEC;
2314         pSMB->req.AndXCommand = 0xFF;
2315         if(ses->server->maxBuf > 64*1024)
2316                 ses->server->maxBuf = (64*1023);
2317         pSMB->req.MaxBufferSize = cpu_to_le16(ses->server->maxBuf);
2318         pSMB->req.MaxMpxCount = cpu_to_le16(ses->server->maxReq);
2319
2320         if(ses->server->secMode & (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED))
2321                 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
2322
2323         capabilities = CAP_LARGE_FILES | CAP_NT_SMBS | CAP_LEVEL_II_OPLOCKS |
2324             CAP_EXTENDED_SECURITY;
2325         if (ses->capabilities & CAP_UNICODE) {
2326                 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
2327                 capabilities |= CAP_UNICODE;
2328         }
2329         if (ses->capabilities & CAP_STATUS32) {
2330                 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
2331                 capabilities |= CAP_STATUS32;
2332         }
2333         if (ses->capabilities & CAP_DFS) {
2334                 smb_buffer->Flags2 |= SMBFLG2_DFS;
2335                 capabilities |= CAP_DFS;
2336         }
2337         pSMB->req.Capabilities = cpu_to_le32(capabilities);
2338
2339         pSMB->req.SecurityBlobLength = cpu_to_le16(SecurityBlobLength);
2340         bcc_ptr = pByteArea(smb_buffer);
2341         memcpy(bcc_ptr, SecurityBlob, SecurityBlobLength);
2342         bcc_ptr += SecurityBlobLength;
2343
2344         if (ses->capabilities & CAP_UNICODE) {
2345                 if ((long) bcc_ptr % 2) {       /* must be word aligned for Unicode strings */
2346                         *bcc_ptr = 0;
2347                         bcc_ptr++;
2348                 }
2349                 bytes_returned =
2350                     cifs_strtoUCS((__le16 *) bcc_ptr, user, 100, nls_codepage);
2351                 bcc_ptr += 2 * bytes_returned;  /* convert num of 16 bit words to bytes */
2352                 bcc_ptr += 2;   /* trailing null */
2353                 if (domain == NULL)
2354                         bytes_returned =
2355                             cifs_strtoUCS((__le16 *) bcc_ptr,
2356                                           "CIFS_LINUX_DOM", 32, nls_codepage);
2357                 else
2358                         bytes_returned =
2359                             cifs_strtoUCS((__le16 *) bcc_ptr, domain, 64,
2360                                           nls_codepage);
2361                 bcc_ptr += 2 * bytes_returned;
2362                 bcc_ptr += 2;
2363                 bytes_returned =
2364                     cifs_strtoUCS((__le16 *) bcc_ptr, "Linux version ",
2365                                   32, nls_codepage);
2366                 bcc_ptr += 2 * bytes_returned;
2367                 bytes_returned =
2368                     cifs_strtoUCS((__le16 *) bcc_ptr, system_utsname.release, 32,
2369                                   nls_codepage);
2370                 bcc_ptr += 2 * bytes_returned;
2371                 bcc_ptr += 2;
2372                 bytes_returned =
2373                     cifs_strtoUCS((__le16 *) bcc_ptr, CIFS_NETWORK_OPSYS,
2374                                   64, nls_codepage);
2375                 bcc_ptr += 2 * bytes_returned;
2376                 bcc_ptr += 2;
2377         } else {
2378                 strncpy(bcc_ptr, user, 200);
2379                 bcc_ptr += strnlen(user, 200);
2380                 *bcc_ptr = 0;
2381                 bcc_ptr++;
2382                 if (domain == NULL) {
2383                         strcpy(bcc_ptr, "CIFS_LINUX_DOM");
2384                         bcc_ptr += strlen("CIFS_LINUX_DOM") + 1;
2385                 } else {
2386                         strncpy(bcc_ptr, domain, 64);
2387                         bcc_ptr += strnlen(domain, 64);
2388                         *bcc_ptr = 0;
2389                         bcc_ptr++;
2390                 }
2391                 strcpy(bcc_ptr, "Linux version ");
2392                 bcc_ptr += strlen("Linux version ");
2393                 strcpy(bcc_ptr, system_utsname.release);
2394                 bcc_ptr += strlen(system_utsname.release) + 1;
2395                 strcpy(bcc_ptr, CIFS_NETWORK_OPSYS);
2396                 bcc_ptr += strlen(CIFS_NETWORK_OPSYS) + 1;
2397         }
2398         count = (long) bcc_ptr - (long) pByteArea(smb_buffer);
2399         smb_buffer->smb_buf_length += count;
2400         pSMB->req.ByteCount = cpu_to_le16(count);
2401
2402         rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response,
2403                          &bytes_returned, 1);
2404         if (rc) {
2405 /*    rc = map_smb_to_linux_error(smb_buffer_response);  *//* done in SendReceive now */
2406         } else if ((smb_buffer_response->WordCount == 3)
2407                    || (smb_buffer_response->WordCount == 4)) {
2408                 __u16 action = le16_to_cpu(pSMBr->resp.Action);
2409                 __u16 blob_len =
2410                     le16_to_cpu(pSMBr->resp.SecurityBlobLength);
2411                 if (action & GUEST_LOGIN)
2412                         cFYI(1, (" Guest login"));      /* BB do we want to set anything in SesInfo struct ? */
2413                 if (ses) {
2414                         ses->Suid = smb_buffer_response->Uid;   /* UID left in wire format (le) */
2415                         cFYI(1, ("UID = %d ", ses->Suid));
2416                         bcc_ptr = pByteArea(smb_buffer_response);       /* response can have either 3 or 4 word count - Samba sends 3 */
2417
2418                         /* BB Fix below to make endian neutral !! */
2419
2420                         if ((pSMBr->resp.hdr.WordCount == 3)
2421                             || ((pSMBr->resp.hdr.WordCount == 4)
2422                                 && (blob_len <
2423                                     pSMBr->resp.ByteCount))) {
2424                                 if (pSMBr->resp.hdr.WordCount == 4) {
2425                                         bcc_ptr +=
2426                                             blob_len;
2427                                         cFYI(1,
2428                                              ("Security Blob Length %d ",
2429                                               blob_len));
2430                                 }
2431
2432                                 if (smb_buffer->Flags2 & SMBFLG2_UNICODE) {
2433                                         if ((long) (bcc_ptr) % 2) {
2434                                                 remaining_words =
2435                                                     (BCC(smb_buffer_response)
2436                                                      - 1) / 2;
2437                                                 bcc_ptr++;      /* Unicode strings must be word aligned */
2438                                         } else {
2439                                                 remaining_words =
2440                                                     BCC
2441                                                     (smb_buffer_response) / 2;
2442                                         }
2443                                         len =
2444                                             UniStrnlen((wchar_t *) bcc_ptr,
2445                                                        remaining_words - 1);
2446 /* We look for obvious messed up bcc or strings in response so we do not go off
2447    the end since (at least) WIN2K and Windows XP have a major bug in not null
2448    terminating last Unicode string in response  */
2449                                         if(ses->serverOS)
2450                                                 kfree(ses->serverOS);
2451                                         ses->serverOS =
2452                                             kzalloc(2 * (len + 1), GFP_KERNEL);
2453                                         cifs_strfromUCS_le(ses->serverOS,
2454                                                            (__le16 *)
2455                                                            bcc_ptr, len,
2456                                                            nls_codepage);
2457                                         bcc_ptr += 2 * (len + 1);
2458                                         remaining_words -= len + 1;
2459                                         ses->serverOS[2 * len] = 0;
2460                                         ses->serverOS[1 + (2 * len)] = 0;
2461                                         if (remaining_words > 0) {
2462                                                 len = UniStrnlen((wchar_t *)bcc_ptr,
2463                                                                  remaining_words
2464                                                                  - 1);
2465                                                 if(ses->serverNOS)
2466                                                         kfree(ses->serverNOS);
2467                                                 ses->serverNOS =
2468                                                     kzalloc(2 * (len + 1),
2469                                                             GFP_KERNEL);
2470                                                 cifs_strfromUCS_le(ses->serverNOS,
2471                                                                    (__le16 *)bcc_ptr,
2472                                                                    len,
2473                                                                    nls_codepage);
2474                                                 bcc_ptr += 2 * (len + 1);
2475                                                 ses->serverNOS[2 * len] = 0;
2476                                                 ses->serverNOS[1 + (2 * len)] = 0;
2477                                                 remaining_words -= len + 1;
2478                                                 if (remaining_words > 0) {
2479                                                         len = UniStrnlen((wchar_t *) bcc_ptr, remaining_words); 
2480                      /* last string not null terminated (e.g.Windows XP/2000) */
2481                                                         if(ses->serverDomain)
2482                                                                 kfree(ses->serverDomain);
2483                                                         ses->serverDomain = kzalloc(2*(len+1),GFP_KERNEL);
2484                                                         cifs_strfromUCS_le(ses->serverDomain,
2485                                                              (__le16 *)bcc_ptr, 
2486                                                              len, nls_codepage);
2487                                                         bcc_ptr += 2*(len+1);
2488                                                         ses->serverDomain[2*len] = 0;
2489                                                         ses->serverDomain[1+(2*len)] = 0;
2490                                                 } /* else no more room so create dummy domain string */
2491                                                 else {
2492                                                         if(ses->serverDomain)
2493         `                                                       kfree(ses->serverDomain);
2494                                                         ses->serverDomain =
2495                                                             kzalloc(2,GFP_KERNEL);
2496                                                 }
2497                                         } else {/* no room use dummy domain&NOS */
2498                                                 if(ses->serverDomain)
2499                                                         kfree(ses->serverDomain);
2500                                                 ses->serverDomain = kzalloc(2, GFP_KERNEL);
2501                                                 if(ses->serverNOS)
2502                                                         kfree(ses->serverNOS);
2503                                                 ses->serverNOS = kzalloc(2, GFP_KERNEL);
2504                                         }
2505                                 } else {        /* ASCII */
2506
2507                                         len = strnlen(bcc_ptr, 1024);
2508                                         if (((long) bcc_ptr + len) - (long)
2509                                             pByteArea(smb_buffer_response)
2510                                             <= BCC(smb_buffer_response)) {
2511                                                 if(ses->serverOS)
2512                                                         kfree(ses->serverOS);
2513                                                 ses->serverOS = kzalloc(len + 1, GFP_KERNEL);
2514                                                 strncpy(ses->serverOS, bcc_ptr, len);
2515
2516                                                 bcc_ptr += len;
2517                                                 bcc_ptr[0] = 0; /* null terminate the string */
2518                                                 bcc_ptr++;
2519
2520                                                 len = strnlen(bcc_ptr, 1024);
2521                                                 if(ses->serverNOS)
2522                                                         kfree(ses->serverNOS);
2523                                                 ses->serverNOS = kzalloc(len + 1,GFP_KERNEL);
2524                                                 strncpy(ses->serverNOS, bcc_ptr, len);
2525                                                 bcc_ptr += len;
2526                                                 bcc_ptr[0] = 0;
2527                                                 bcc_ptr++;
2528
2529                                                 len = strnlen(bcc_ptr, 1024);
2530                                                 if(ses->serverDomain)
2531                                                         kfree(ses->severDomain);
2532                                                 ses->serverDomain = kzalloc(len + 1, GFP_KERNEL);
2533                                                 strncpy(ses->serverDomain, bcc_ptr, len);
2534                                                 bcc_ptr += len;
2535                                                 bcc_ptr[0] = 0;
2536                                                 bcc_ptr++;
2537                                         } else
2538                                                 cFYI(1,
2539                                                      ("Variable field of length %d extends beyond end of smb ",
2540                                                       len));
2541                                 }
2542                         } else {
2543                                 cERROR(1,
2544                                        (" Security Blob Length extends beyond end of SMB"));
2545                         }
2546                 } else {
2547                         cERROR(1, ("No session structure passed in."));
2548                 }
2549         } else {
2550                 cERROR(1,
2551                        (" Invalid Word count %d: ",
2552                         smb_buffer_response->WordCount));
2553                 rc = -EIO;
2554         }
2555
2556         if (smb_buffer)
2557                 cifs_buf_release(smb_buffer);
2558
2559         return rc;
2560 }
2561
2562 static int
2563 CIFSNTLMSSPNegotiateSessSetup(unsigned int xid,
2564                               struct cifsSesInfo *ses, int * pNTLMv2_flag,
2565                               const struct nls_table *nls_codepage)
2566 {
2567         struct smb_hdr *smb_buffer;
2568         struct smb_hdr *smb_buffer_response;
2569         SESSION_SETUP_ANDX *pSMB;
2570         SESSION_SETUP_ANDX *pSMBr;
2571         char *bcc_ptr;
2572         char *domain;
2573         int rc = 0;
2574         int remaining_words = 0;
2575         int bytes_returned = 0;
2576         int len;
2577         int SecurityBlobLength = sizeof (NEGOTIATE_MESSAGE);
2578         PNEGOTIATE_MESSAGE SecurityBlob;
2579         PCHALLENGE_MESSAGE SecurityBlob2;
2580         __u32 negotiate_flags, capabilities;
2581         __u16 count;
2582
2583         cFYI(1, ("In NTLMSSP sesssetup (negotiate)"));
2584         if(ses == NULL)
2585                 return -EINVAL;
2586         domain = ses->domainName;
2587         *pNTLMv2_flag = FALSE;
2588         smb_buffer = cifs_buf_get();
2589         if (smb_buffer == NULL) {
2590                 return -ENOMEM;
2591         }
2592         smb_buffer_response = smb_buffer;
2593         pSMB = (SESSION_SETUP_ANDX *) smb_buffer;
2594         pSMBr = (SESSION_SETUP_ANDX *) smb_buffer_response;
2595
2596         /* send SMBsessionSetup here */
2597         header_assemble(smb_buffer, SMB_COM_SESSION_SETUP_ANDX,
2598                         NULL /* no tCon exists yet */ , 12 /* wct */ );
2599
2600         smb_buffer->Mid = GetNextMid(ses->server);
2601         pSMB->req.hdr.Flags2 |= SMBFLG2_EXT_SEC;
2602         pSMB->req.hdr.Flags |= (SMBFLG_CASELESS | SMBFLG_CANONICAL_PATH_FORMAT);
2603
2604         pSMB->req.AndXCommand = 0xFF;
2605         pSMB->req.MaxBufferSize = cpu_to_le16(ses->server->maxBuf);
2606         pSMB->req.MaxMpxCount = cpu_to_le16(ses->server->maxReq);
2607
2608         if(ses->server->secMode & (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED))
2609                 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
2610
2611         capabilities = CAP_LARGE_FILES | CAP_NT_SMBS | CAP_LEVEL_II_OPLOCKS |
2612             CAP_EXTENDED_SECURITY;
2613         if (ses->capabilities & CAP_UNICODE) {
2614                 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
2615                 capabilities |= CAP_UNICODE;
2616         }
2617         if (ses->capabilities & CAP_STATUS32) {
2618                 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
2619                 capabilities |= CAP_STATUS32;
2620         }
2621         if (ses->capabilities & CAP_DFS) {
2622                 smb_buffer->Flags2 |= SMBFLG2_DFS;
2623                 capabilities |= CAP_DFS;
2624         }
2625         pSMB->req.Capabilities = cpu_to_le32(capabilities);
2626
2627         bcc_ptr = (char *) &pSMB->req.SecurityBlob;
2628         SecurityBlob = (PNEGOTIATE_MESSAGE) bcc_ptr;
2629         strncpy(SecurityBlob->Signature, NTLMSSP_SIGNATURE, 8);
2630         SecurityBlob->MessageType = NtLmNegotiate;
2631         negotiate_flags =
2632             NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_NEGOTIATE_OEM |
2633             NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_NTLM |
2634             NTLMSSP_NEGOTIATE_56 |
2635             /* NTLMSSP_NEGOTIATE_ALWAYS_SIGN | */ NTLMSSP_NEGOTIATE_128;
2636         if(sign_CIFS_PDUs)
2637                 negotiate_flags |= NTLMSSP_NEGOTIATE_SIGN;
2638         if(ntlmv2_support)
2639                 negotiate_flags |= NTLMSSP_NEGOTIATE_NTLMV2;
2640         /* setup pointers to domain name and workstation name */
2641         bcc_ptr += SecurityBlobLength;
2642
2643         SecurityBlob->WorkstationName.Buffer = 0;
2644         SecurityBlob->WorkstationName.Length = 0;
2645         SecurityBlob->WorkstationName.MaximumLength = 0;
2646
2647         /* Domain not sent on first Sesssetup in NTLMSSP, instead it is sent
2648         along with username on auth request (ie the response to challenge) */
2649         SecurityBlob->DomainName.Buffer = 0;
2650         SecurityBlob->DomainName.Length = 0;
2651         SecurityBlob->DomainName.MaximumLength = 0;
2652         if (ses->capabilities & CAP_UNICODE) {
2653                 if ((long) bcc_ptr % 2) {
2654                         *bcc_ptr = 0;
2655                         bcc_ptr++;
2656                 }
2657
2658                 bytes_returned =
2659                     cifs_strtoUCS((__le16 *) bcc_ptr, "Linux version ",
2660                                   32, nls_codepage);
2661                 bcc_ptr += 2 * bytes_returned;
2662                 bytes_returned =
2663                     cifs_strtoUCS((__le16 *) bcc_ptr, system_utsname.release, 32,
2664                                   nls_codepage);
2665                 bcc_ptr += 2 * bytes_returned;
2666                 bcc_ptr += 2;   /* null terminate Linux version */
2667                 bytes_returned =
2668                     cifs_strtoUCS((__le16 *) bcc_ptr, CIFS_NETWORK_OPSYS,
2669                                   64, nls_codepage);
2670                 bcc_ptr += 2 * bytes_returned;
2671                 *(bcc_ptr + 1) = 0;
2672                 *(bcc_ptr + 2) = 0;
2673                 bcc_ptr += 2;   /* null terminate network opsys string */
2674                 *(bcc_ptr + 1) = 0;
2675                 *(bcc_ptr + 2) = 0;
2676                 bcc_ptr += 2;   /* null domain */
2677         } else {                /* ASCII */
2678                 strcpy(bcc_ptr, "Linux version ");
2679                 bcc_ptr += strlen("Linux version ");
2680                 strcpy(bcc_ptr, system_utsname.release);
2681                 bcc_ptr += strlen(system_utsname.release) + 1;
2682                 strcpy(bcc_ptr, CIFS_NETWORK_OPSYS);
2683                 bcc_ptr += strlen(CIFS_NETWORK_OPSYS) + 1;
2684                 bcc_ptr++;      /* empty domain field */
2685                 *bcc_ptr = 0;
2686         }
2687         SecurityBlob->NegotiateFlags = cpu_to_le32(negotiate_flags);
2688         pSMB->req.SecurityBlobLength = cpu_to_le16(SecurityBlobLength);
2689         count = (long) bcc_ptr - (long) pByteArea(smb_buffer);
2690         smb_buffer->smb_buf_length += count;
2691         pSMB->req.ByteCount = cpu_to_le16(count);
2692
2693         rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response,
2694                          &bytes_returned, 1);
2695
2696         if (smb_buffer_response->Status.CifsError ==
2697             cpu_to_le32(NT_STATUS_MORE_PROCESSING_REQUIRED))
2698                 rc = 0;
2699
2700         if (rc) {
2701 /*    rc = map_smb_to_linux_error(smb_buffer_response);  *//* done in SendReceive now */
2702         } else if ((smb_buffer_response->WordCount == 3)
2703                    || (smb_buffer_response->WordCount == 4)) {
2704                 __u16 action = le16_to_cpu(pSMBr->resp.Action);
2705                 __u16 blob_len = le16_to_cpu(pSMBr->resp.SecurityBlobLength);
2706
2707                 if (action & GUEST_LOGIN)
2708                         cFYI(1, (" Guest login"));      
2709         /* Do we want to set anything in SesInfo struct when guest login? */
2710
2711                 bcc_ptr = pByteArea(smb_buffer_response);       
2712         /* response can have either 3 or 4 word count - Samba sends 3 */
2713
2714                 SecurityBlob2 = (PCHALLENGE_MESSAGE) bcc_ptr;
2715                 if (SecurityBlob2->MessageType != NtLmChallenge) {
2716                         cFYI(1,
2717                              ("Unexpected NTLMSSP message type received %d",
2718                               SecurityBlob2->MessageType));
2719                 } else if (ses) {
2720                         ses->Suid = smb_buffer_response->Uid; /* UID left in le format */ 
2721                         cFYI(1, ("UID = %d", ses->Suid));
2722                         if ((pSMBr->resp.hdr.WordCount == 3)
2723                             || ((pSMBr->resp.hdr.WordCount == 4)
2724                                 && (blob_len <
2725                                     pSMBr->resp.ByteCount))) {
2726
2727                                 if (pSMBr->resp.hdr.WordCount == 4) {
2728                                         bcc_ptr += blob_len;
2729                                         cFYI(1, ("Security Blob Length %d",
2730                                               blob_len));
2731                                 }
2732
2733                                 cFYI(1, ("NTLMSSP Challenge rcvd"));
2734
2735                                 memcpy(ses->server->cryptKey,
2736                                        SecurityBlob2->Challenge,
2737                                        CIFS_CRYPTO_KEY_SIZE);
2738                                 if(SecurityBlob2->NegotiateFlags & 
2739                                         cpu_to_le32(NTLMSSP_NEGOTIATE_NTLMV2))
2740                                         *pNTLMv2_flag = TRUE;
2741
2742                                 if((SecurityBlob2->NegotiateFlags & 
2743                                         cpu_to_le32(NTLMSSP_NEGOTIATE_ALWAYS_SIGN)) 
2744                                         || (sign_CIFS_PDUs > 1))
2745                                                 ses->server->secMode |= 
2746                                                         SECMODE_SIGN_REQUIRED;  
2747                                 if ((SecurityBlob2->NegotiateFlags & 
2748                                         cpu_to_le32(NTLMSSP_NEGOTIATE_SIGN)) && (sign_CIFS_PDUs))
2749                                                 ses->server->secMode |= 
2750                                                         SECMODE_SIGN_ENABLED;
2751
2752                                 if (smb_buffer->Flags2 & SMBFLG2_UNICODE) {
2753                                         if ((long) (bcc_ptr) % 2) {
2754                                                 remaining_words =
2755                                                     (BCC(smb_buffer_response)
2756                                                      - 1) / 2;
2757                                                 bcc_ptr++;      /* Unicode strings must be word aligned */
2758                                         } else {
2759                                                 remaining_words =
2760                                                     BCC
2761                                                     (smb_buffer_response) / 2;
2762                                         }
2763                                         len =
2764                                             UniStrnlen((wchar_t *) bcc_ptr,
2765                                                        remaining_words - 1);
2766 /* We look for obvious messed up bcc or strings in response so we do not go off
2767    the end since (at least) WIN2K and Windows XP have a major bug in not null
2768    terminating last Unicode string in response  */
2769                                         if(ses->serverOS)
2770                                                 kfree(ses->serverOS);
2771                                         ses->serverOS =
2772                                             kzalloc(2 * (len + 1), GFP_KERNEL);
2773                                         cifs_strfromUCS_le(ses->serverOS,
2774                                                            (__le16 *)
2775                                                            bcc_ptr, len,
2776                                                            nls_codepage);
2777                                         bcc_ptr += 2 * (len + 1);
2778                                         remaining_words -= len + 1;
2779                                         ses->serverOS[2 * len] = 0;
2780                                         ses->serverOS[1 + (2 * len)] = 0;
2781                                         if (remaining_words > 0) {
2782                                                 len = UniStrnlen((wchar_t *)
2783                                                                  bcc_ptr,
2784                                                                  remaining_words
2785                                                                  - 1);
2786                                                 if(ses->serverNOS)
2787                                                         kfree(ses->serverNOS);
2788                                                 ses->serverNOS =
2789                                                     kzalloc(2 * (len + 1),
2790                                                             GFP_KERNEL);
2791                                                 cifs_strfromUCS_le(ses->
2792                                                                    serverNOS,
2793                                                                    (__le16 *)
2794                                                                    bcc_ptr,
2795                                                                    len,
2796                                                                    nls_codepage);
2797                                                 bcc_ptr += 2 * (len + 1);
2798                                                 ses->serverNOS[2 * len] = 0;
2799                                                 ses->serverNOS[1 +
2800                                                                (2 * len)] = 0;
2801                                                 remaining_words -= len + 1;
2802                                                 if (remaining_words > 0) {
2803                                                         len = UniStrnlen((wchar_t *) bcc_ptr, remaining_words); 
2804            /* last string is not always null terminated (for e.g. for Windows XP & 2000) */
2805                                                         if(ses->serverDomain)
2806                                                                 kfree(ses->serverDomain);
2807                                                         ses->serverDomain =
2808                                                             kzalloc(2 *
2809                                                                     (len +
2810                                                                      1),
2811                                                                     GFP_KERNEL);
2812                                                         cifs_strfromUCS_le
2813                                                             (ses->serverDomain,
2814                                                              (__le16 *)bcc_ptr,
2815                                                              len, nls_codepage);
2816                                                         bcc_ptr +=
2817                                                             2 * (len + 1);
2818                                                         ses->serverDomain[2*len]
2819                                                             = 0;
2820                                                         ses->serverDomain
2821                                                                 [1 + (2 * len)]
2822                                                             = 0;
2823                                                 } /* else no more room so create dummy domain string */
2824                                                 else {
2825                                                         if(ses->serverDomain)
2826                                                                 kfree(ses->serverDomain);
2827                                                         ses->serverDomain =
2828                                                             kzalloc(2,
2829                                                                     GFP_KERNEL);
2830                                                 }
2831                                         } else {        /* no room so create dummy domain and NOS string */
2832                                                 if(ses->serverDomain);
2833                                                         kfree(ses->serverDomain);
2834                                                 ses->serverDomain =
2835                                                     kzalloc(2, GFP_KERNEL);
2836                                                 if(ses->serverNOS)
2837                                                         kfree(ses->serverNOS);
2838                                                 ses->serverNOS =
2839                                                     kzalloc(2, GFP_KERNEL);
2840                                         }
2841                                 } else {        /* ASCII */
2842                                         len = strnlen(bcc_ptr, 1024);
2843                                         if (((long) bcc_ptr + len) - (long)
2844                                             pByteArea(smb_buffer_response)
2845                                             <= BCC(smb_buffer_response)) {
2846                                                 if(ses->serverOS)
2847                                                         kfree(ses->serverOS);
2848                                                 ses->serverOS =
2849                                                     kzalloc(len + 1,
2850                                                             GFP_KERNEL);
2851                                                 strncpy(ses->serverOS,
2852                                                         bcc_ptr, len);
2853
2854                                                 bcc_ptr += len;
2855                                                 bcc_ptr[0] = 0; /* null terminate string */
2856                                                 bcc_ptr++;
2857
2858                                                 len = strnlen(bcc_ptr, 1024);
2859                                                 if(ses->serverNOS)
2860                                                         kfree(ses->serverNOS);
2861                                                 ses->serverNOS =
2862                                                     kzalloc(len + 1,
2863                                                             GFP_KERNEL);
2864                                                 strncpy(ses->serverNOS, bcc_ptr, len);
2865                                                 bcc_ptr += len;
2866                                                 bcc_ptr[0] = 0;
2867                                                 bcc_ptr++;
2868
2869                                                 len = strnlen(bcc_ptr, 1024);
2870                                                 if(ses->serverDomain)
2871                                                         kfree(ses->serverDomain);
2872                                                 ses->serverDomain =
2873                                                     kzalloc(len + 1,
2874                                                             GFP_KERNEL);
2875                                                 strncpy(ses->serverDomain, bcc_ptr, len);       
2876                                                 bcc_ptr += len;
2877                                                 bcc_ptr[0] = 0;
2878                                                 bcc_ptr++;
2879                                         } else
2880                                                 cFYI(1,
2881                                                      ("Variable field of length %d extends beyond end of smb",
2882                                                       len));
2883                                 }
2884                         } else {
2885                                 cERROR(1,
2886                                        (" Security Blob Length extends beyond end of SMB"));
2887                         }
2888                 } else {
2889                         cERROR(1, ("No session structure passed in."));
2890                 }
2891         } else {
2892                 cERROR(1,
2893                        (" Invalid Word count %d:",
2894                         smb_buffer_response->WordCount));
2895                 rc = -EIO;
2896         }
2897
2898         if (smb_buffer)
2899                 cifs_buf_release(smb_buffer);
2900
2901         return rc;
2902 }
2903 static int
2904 CIFSNTLMSSPAuthSessSetup(unsigned int xid, struct cifsSesInfo *ses,
2905                 char *ntlm_session_key, int ntlmv2_flag,
2906                 const struct nls_table *nls_codepage)
2907 {
2908         struct smb_hdr *smb_buffer;
2909         struct smb_hdr *smb_buffer_response;
2910         SESSION_SETUP_ANDX *pSMB;
2911         SESSION_SETUP_ANDX *pSMBr;
2912         char *bcc_ptr;
2913         char *user;
2914         char *domain;
2915         int rc = 0;
2916         int remaining_words = 0;
2917         int bytes_returned = 0;
2918         int len;
2919         int SecurityBlobLength = sizeof (AUTHENTICATE_MESSAGE);
2920         PAUTHENTICATE_MESSAGE SecurityBlob;
2921         __u32 negotiate_flags, capabilities;
2922         __u16 count;
2923
2924         cFYI(1, ("In NTLMSSPSessSetup (Authenticate)"));
2925         if(ses == NULL)
2926                 return -EINVAL;
2927         user = ses->userName;
2928         domain = ses->domainName;
2929         smb_buffer = cifs_buf_get();
2930         if (smb_buffer == NULL) {
2931                 return -ENOMEM;
2932         }
2933         smb_buffer_response = smb_buffer;
2934         pSMB = (SESSION_SETUP_ANDX *) smb_buffer;
2935         pSMBr = (SESSION_SETUP_ANDX *) smb_buffer_response;
2936
2937         /* send SMBsessionSetup here */
2938         header_assemble(smb_buffer, SMB_COM_SESSION_SETUP_ANDX,
2939                         NULL /* no tCon exists yet */ , 12 /* wct */ );
2940
2941         smb_buffer->Mid = GetNextMid(ses->server);
2942         pSMB->req.hdr.Flags |= (SMBFLG_CASELESS | SMBFLG_CANONICAL_PATH_FORMAT);
2943         pSMB->req.hdr.Flags2 |= SMBFLG2_EXT_SEC;
2944         pSMB->req.AndXCommand = 0xFF;
2945         pSMB->req.MaxBufferSize = cpu_to_le16(ses->server->maxBuf);
2946         pSMB->req.MaxMpxCount = cpu_to_le16(ses->server->maxReq);
2947
2948         pSMB->req.hdr.Uid = ses->Suid;
2949
2950         if(ses->server->secMode & (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED))
2951                 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
2952
2953         capabilities = CAP_LARGE_FILES | CAP_NT_SMBS | CAP_LEVEL_II_OPLOCKS |
2954             CAP_EXTENDED_SECURITY;
2955         if (ses->capabilities & CAP_UNICODE) {
2956                 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
2957                 capabilities |= CAP_UNICODE;
2958         }
2959         if (ses->capabilities & CAP_STATUS32) {
2960                 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
2961                 capabilities |= CAP_STATUS32;
2962         }
2963         if (ses->capabilities & CAP_DFS) {
2964                 smb_buffer->Flags2 |= SMBFLG2_DFS;
2965                 capabilities |= CAP_DFS;
2966         }
2967         pSMB->req.Capabilities = cpu_to_le32(capabilities);
2968
2969         bcc_ptr = (char *) &pSMB->req.SecurityBlob;
2970         SecurityBlob = (PAUTHENTICATE_MESSAGE) bcc_ptr;
2971         strncpy(SecurityBlob->Signature, NTLMSSP_SIGNATURE, 8);
2972         SecurityBlob->MessageType = NtLmAuthenticate;
2973         bcc_ptr += SecurityBlobLength;
2974         negotiate_flags = 
2975             NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_REQUEST_TARGET |
2976             NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_TARGET_INFO |
2977             0x80000000 | NTLMSSP_NEGOTIATE_128;
2978         if(sign_CIFS_PDUs)
2979                 negotiate_flags |= /* NTLMSSP_NEGOTIATE_ALWAYS_SIGN |*/ NTLMSSP_NEGOTIATE_SIGN;
2980         if(ntlmv2_flag)
2981                 negotiate_flags |= NTLMSSP_NEGOTIATE_NTLMV2;
2982
2983 /* setup pointers to domain name and workstation name */
2984
2985         SecurityBlob->WorkstationName.Buffer = 0;
2986         SecurityBlob->WorkstationName.Length = 0;
2987         SecurityBlob->WorkstationName.MaximumLength = 0;
2988         SecurityBlob->SessionKey.Length = 0;
2989         SecurityBlob->SessionKey.MaximumLength = 0;
2990         SecurityBlob->SessionKey.Buffer = 0;
2991
2992         SecurityBlob->LmChallengeResponse.Length = 0;
2993         SecurityBlob->LmChallengeResponse.MaximumLength = 0;
2994         SecurityBlob->LmChallengeResponse.Buffer = 0;
2995
2996         SecurityBlob->NtChallengeResponse.Length =
2997             cpu_to_le16(CIFS_SESSION_KEY_SIZE);
2998         SecurityBlob->NtChallengeResponse.MaximumLength =
2999             cpu_to_le16(CIFS_SESSION_KEY_SIZE);
3000         memcpy(bcc_ptr, ntlm_session_key, CIFS_SESSION_KEY_SIZE);
3001         SecurityBlob->NtChallengeResponse.Buffer =
3002             cpu_to_le32(SecurityBlobLength);
3003         SecurityBlobLength += CIFS_SESSION_KEY_SIZE;
3004         bcc_ptr += CIFS_SESSION_KEY_SIZE;
3005
3006         if (ses->capabilities & CAP_UNICODE) {
3007                 if (domain == NULL) {
3008                         SecurityBlob->DomainName.Buffer = 0;
3009                         SecurityBlob->DomainName.Length = 0;
3010                         SecurityBlob->DomainName.MaximumLength = 0;
3011                 } else {
3012                         __u16 len =
3013                             cifs_strtoUCS((__le16 *) bcc_ptr, domain, 64,
3014                                           nls_codepage);
3015                         len *= 2;
3016                         SecurityBlob->DomainName.MaximumLength =
3017                             cpu_to_le16(len);
3018                         SecurityBlob->DomainName.Buffer =
3019                             cpu_to_le32(SecurityBlobLength);
3020                         bcc_ptr += len;
3021                         SecurityBlobLength += len;
3022                         SecurityBlob->DomainName.Length =
3023                             cpu_to_le16(len);
3024                 }
3025                 if (user == NULL) {
3026                         SecurityBlob->UserName.Buffer = 0;
3027                         SecurityBlob->UserName.Length = 0;
3028                         SecurityBlob->UserName.MaximumLength = 0;
3029                 } else {
3030                         __u16 len =
3031                             cifs_strtoUCS((__le16 *) bcc_ptr, user, 64,
3032                                           nls_codepage);
3033                         len *= 2;
3034                         SecurityBlob->UserName.MaximumLength =
3035                             cpu_to_le16(len);
3036                         SecurityBlob->UserName.Buffer =
3037                             cpu_to_le32(SecurityBlobLength);
3038                         bcc_ptr += len;
3039                         SecurityBlobLength += len;
3040                         SecurityBlob->UserName.Length =
3041                             cpu_to_le16(len);
3042                 }
3043
3044                 /* SecurityBlob->WorkstationName.Length = cifs_strtoUCS((__le16 *) bcc_ptr, "AMACHINE",64, nls_codepage);
3045                    SecurityBlob->WorkstationName.Length *= 2;
3046                    SecurityBlob->WorkstationName.MaximumLength = cpu_to_le16(SecurityBlob->WorkstationName.Length);
3047                    SecurityBlob->WorkstationName.Buffer = cpu_to_le32(SecurityBlobLength);
3048                    bcc_ptr += SecurityBlob->WorkstationName.Length;
3049                    SecurityBlobLength += SecurityBlob->WorkstationName.Length;
3050                    SecurityBlob->WorkstationName.Length = cpu_to_le16(SecurityBlob->WorkstationName.Length);  */
3051
3052                 if ((long) bcc_ptr % 2) {
3053                         *bcc_ptr = 0;
3054                         bcc_ptr++;
3055                 }
3056                 bytes_returned =
3057                     cifs_strtoUCS((__le16 *) bcc_ptr, "Linux version ",
3058                                   32, nls_codepage);
3059                 bcc_ptr += 2 * bytes_returned;
3060                 bytes_returned =
3061                     cifs_strtoUCS((__le16 *) bcc_ptr, system_utsname.release, 32,
3062                                   nls_codepage);
3063                 bcc_ptr += 2 * bytes_returned;
3064                 bcc_ptr += 2;   /* null term version string */
3065                 bytes_returned =
3066                     cifs_strtoUCS((__le16 *) bcc_ptr, CIFS_NETWORK_OPSYS,
3067                                   64, nls_codepage);
3068                 bcc_ptr += 2 * bytes_returned;
3069                 *(bcc_ptr + 1) = 0;
3070                 *(bcc_ptr + 2) = 0;
3071                 bcc_ptr += 2;   /* null terminate network opsys string */
3072                 *(bcc_ptr + 1) = 0;
3073                 *(bcc_ptr + 2) = 0;
3074                 bcc_ptr += 2;   /* null domain */
3075         } else {                /* ASCII */
3076                 if (domain == NULL) {
3077                         SecurityBlob->DomainName.Buffer = 0;
3078                         SecurityBlob->DomainName.Length = 0;
3079                         SecurityBlob->DomainName.MaximumLength = 0;
3080                 } else {
3081                         __u16 len;
3082                         negotiate_flags |= NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED;
3083                         strncpy(bcc_ptr, domain, 63);
3084                         len = strnlen(domain, 64);
3085                         SecurityBlob->DomainName.MaximumLength =
3086                             cpu_to_le16(len);
3087                         SecurityBlob->DomainName.Buffer =
3088                             cpu_to_le32(SecurityBlobLength);
3089                         bcc_ptr += len;
3090                         SecurityBlobLength += len;
3091                         SecurityBlob->DomainName.Length = cpu_to_le16(len);
3092                 }
3093                 if (user == NULL) {
3094                         SecurityBlob->UserName.Buffer = 0;
3095                         SecurityBlob->UserName.Length = 0;
3096                         SecurityBlob->UserName.MaximumLength = 0;
3097                 } else {
3098                         __u16 len;
3099                         strncpy(bcc_ptr, user, 63);
3100                         len = strnlen(user, 64);
3101                         SecurityBlob->UserName.MaximumLength =
3102                             cpu_to_le16(len);
3103                         SecurityBlob->UserName.Buffer =
3104                             cpu_to_le32(SecurityBlobLength);
3105                         bcc_ptr += len;
3106                         SecurityBlobLength += len;
3107                         SecurityBlob->UserName.Length = cpu_to_le16(len);
3108                 }
3109                 /* BB fill in our workstation name if known BB */
3110
3111                 strcpy(bcc_ptr, "Linux version ");
3112                 bcc_ptr += strlen("Linux version ");
3113                 strcpy(bcc_ptr, system_utsname.release);
3114                 bcc_ptr += strlen(system_utsname.release) + 1;
3115                 strcpy(bcc_ptr, CIFS_NETWORK_OPSYS);
3116                 bcc_ptr += strlen(CIFS_NETWORK_OPSYS) + 1;
3117                 bcc_ptr++;      /* null domain */
3118                 *bcc_ptr = 0;
3119         }
3120         SecurityBlob->NegotiateFlags = cpu_to_le32(negotiate_flags);
3121         pSMB->req.SecurityBlobLength = cpu_to_le16(SecurityBlobLength);
3122         count = (long) bcc_ptr - (long) pByteArea(smb_buffer);
3123         smb_buffer->smb_buf_length += count;
3124         pSMB->req.ByteCount = cpu_to_le16(count);
3125
3126         rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response,
3127                          &bytes_returned, 1);
3128         if (rc) {
3129 /*    rc = map_smb_to_linux_error(smb_buffer_response);  *//* done in SendReceive now */
3130         } else if ((smb_buffer_response->WordCount == 3)
3131                    || (smb_buffer_response->WordCount == 4)) {
3132                 __u16 action = le16_to_cpu(pSMBr->resp.Action);
3133                 __u16 blob_len =
3134                     le16_to_cpu(pSMBr->resp.SecurityBlobLength);
3135                 if (action & GUEST_LOGIN)
3136                         cFYI(1, (" Guest login"));      /* BB do we want to set anything in SesInfo struct ? */
3137 /*        if(SecurityBlob2->MessageType != NtLm??){                               
3138                  cFYI("Unexpected message type on auth response is %d ")); 
3139         } */
3140                 if (ses) {
3141                         cFYI(1,
3142                              ("Does UID on challenge %d match auth response UID %d ",
3143                               ses->Suid, smb_buffer_response->Uid));
3144                         ses->Suid = smb_buffer_response->Uid; /* UID left in wire format */
3145                         bcc_ptr = pByteArea(smb_buffer_response);       
3146             /* response can have either 3 or 4 word count - Samba sends 3 */
3147                         if ((pSMBr->resp.hdr.WordCount == 3)
3148                             || ((pSMBr->resp.hdr.WordCount == 4)
3149                                 && (blob_len <
3150                                     pSMBr->resp.ByteCount))) {
3151                                 if (pSMBr->resp.hdr.WordCount == 4) {
3152                                         bcc_ptr +=
3153                                             blob_len;
3154                                         cFYI(1,
3155                                              ("Security Blob Length %d ",
3156                                               blob_len));
3157                                 }
3158
3159                                 cFYI(1,
3160                                      ("NTLMSSP response to Authenticate "));
3161
3162                                 if (smb_buffer->Flags2 & SMBFLG2_UNICODE) {
3163                                         if ((long) (bcc_ptr) % 2) {
3164                                                 remaining_words =
3165                                                     (BCC(smb_buffer_response)
3166                                                      - 1) / 2;
3167                                                 bcc_ptr++;      /* Unicode strings must be word aligned */
3168                                         } else {
3169                                                 remaining_words = BCC(smb_buffer_response) / 2;
3170                                         }
3171                                         len =
3172                                             UniStrnlen((wchar_t *) bcc_ptr,remaining_words - 1);
3173 /* We look for obvious messed up bcc or strings in response so we do not go off
3174   the end since (at least) WIN2K and Windows XP have a major bug in not null
3175   terminating last Unicode string in response  */
3176                                         if(ses->serverOS)
3177                                                 kfree(serverOS);
3178                                         ses->serverOS =
3179                                             kzalloc(2 * (len + 1), GFP_KERNEL);
3180                                         cifs_strfromUCS_le(ses->serverOS,
3181                                                            (__le16 *)
3182                                                            bcc_ptr, len,
3183                                                            nls_codepage);
3184                                         bcc_ptr += 2 * (len + 1);
3185                                         remaining_words -= len + 1;
3186                                         ses->serverOS[2 * len] = 0;
3187                                         ses->serverOS[1 + (2 * len)] = 0;
3188                                         if (remaining_words > 0) {
3189                                                 len = UniStrnlen((wchar_t *)
3190                                                                  bcc_ptr,
3191                                                                  remaining_words
3192                                                                  - 1);
3193                                                 if(ses->serverNOS)
3194                                                         kfree(ses->serverNOS);
3195                                                 ses->serverNOS =
3196                                                     kzalloc(2 * (len + 1),
3197                                                             GFP_KERNEL);
3198                                                 cifs_strfromUCS_le(ses->
3199                                                                    serverNOS,
3200                                                                    (__le16 *)
3201                                                                    bcc_ptr,
3202                                                                    len,
3203                                                                    nls_codepage);
3204                                                 bcc_ptr += 2 * (len + 1);
3205                                                 ses->serverNOS[2 * len] = 0;
3206                                                 ses->serverNOS[1+(2*len)] = 0;
3207                                                 remaining_words -= len + 1;
3208                                                 if (remaining_words > 0) {
3209                                                         len = UniStrnlen((wchar_t *) bcc_ptr, remaining_words); 
3210      /* last string not always null terminated (e.g. for Windows XP & 2000) */
3211                                                         if(ses->serverDomain)
3212                                                                 kfree(ses->serverDomain);
3213                                                         ses->serverDomain =
3214                                                             kzalloc(2 *
3215                                                                     (len +
3216                                                                      1),
3217                                                                     GFP_KERNEL);
3218                                                         cifs_strfromUCS_le
3219                                                             (ses->
3220                                                              serverDomain,
3221                                                              (__le16 *)
3222                                                              bcc_ptr, len,
3223                                                              nls_codepage);
3224                                                         bcc_ptr +=
3225                                                             2 * (len + 1);
3226                                                         ses->
3227                                                             serverDomain[2
3228                                                                          * len]
3229                                                             = 0;
3230                                                         ses->
3231                                                             serverDomain[1
3232                                                                          +
3233                                                                          (2
3234                                                                           *
3235                                                                           len)]
3236                                                             = 0;
3237                                                 } /* else no more room so create dummy domain string */
3238                                                 else {
3239                                                         if(ses->serverDomain)
3240                                                                 kfree(ses->serverDomain);
3241                                                         ses->serverDomain = kzalloc(2,GFP_KERNEL);
3242                                                 }
3243                                         } else {  /* no room so create dummy domain and NOS string */
3244                                                 if(ses->serverDomain)
3245                                                         kfree(ses->serverDomain);
3246                                                 ses->serverDomain = kzalloc(2, GFP_KERNEL);
3247                                                 if(ses->serverNOS)
3248                                                         kfree(ses->serverNOS);
3249                                                 ses->serverNOS = kzalloc(2, GFP_KERNEL);
3250                                         }
3251                                 } else {        /* ASCII */
3252                                         len = strnlen(bcc_ptr, 1024);
3253                                         if (((long) bcc_ptr + len) - 
3254                         (long) pByteArea(smb_buffer_response) 
3255                             <= BCC(smb_buffer_response)) {
3256                                                 if(ses->serverOS)
3257                                                         kfree(ses->serverOS);
3258                                                 ses->serverOS = kzalloc(len + 1,GFP_KERNEL);
3259                                                 strncpy(ses->serverOS,bcc_ptr, len);
3260
3261                                                 bcc_ptr += len;
3262                                                 bcc_ptr[0] = 0; /* null terminate the string */
3263                                                 bcc_ptr++;
3264
3265                                                 len = strnlen(bcc_ptr, 1024);
3266                                                 if(ses->serverNOS)
3267                                                         kfree(ses->serverNOS);
3268                                                 ses->serverNOS = kzalloc(len+1,GFP_KERNEL);
3269                                                 strncpy(ses->serverNOS, bcc_ptr, len);  
3270                                                 bcc_ptr += len;
3271                                                 bcc_ptr[0] = 0;
3272                                                 bcc_ptr++;
3273
3274                                                 len = strnlen(bcc_ptr, 1024);
3275                                                 if(ses->serverDomain)
3276                                                         kfree(ses->serverDomain);
3277                                                 ses->serverDomain = kzalloc(len+1,GFP_KERNEL);
3278                                                 strncpy(ses->serverDomain, bcc_ptr, len);
3279                                                 bcc_ptr += len;
3280                                                 bcc_ptr[0] = 0;
3281                                                 bcc_ptr++;
3282                                         } else
3283                                                 cFYI(1,
3284                                                      ("Variable field of length %d extends beyond end of smb ",
3285                                                       len));
3286                                 }
3287                         } else {
3288                                 cERROR(1,
3289                                        (" Security Blob Length extends beyond end of SMB"));
3290                         }
3291                 } else {
3292                         cERROR(1, ("No session structure passed in."));
3293                 }
3294         } else {
3295                 cERROR(1,
3296                        (" Invalid Word count %d: ",
3297                         smb_buffer_response->WordCount));
3298                 rc = -EIO;
3299         }
3300
3301         if (smb_buffer)
3302                 cifs_buf_release(smb_buffer);
3303
3304         return rc;
3305 }
3306
3307 int
3308 CIFSTCon(unsigned int xid, struct cifsSesInfo *ses,
3309          const char *tree, struct cifsTconInfo *tcon,
3310          const struct nls_table *nls_codepage)
3311 {
3312         struct smb_hdr *smb_buffer;
3313         struct smb_hdr *smb_buffer_response;
3314         TCONX_REQ *pSMB;
3315         TCONX_RSP *pSMBr;
3316         unsigned char *bcc_ptr;
3317         int rc = 0;
3318         int length;
3319         __u16 count;
3320
3321         if (ses == NULL)
3322                 return -EIO;
3323
3324         smb_buffer = cifs_buf_get();
3325         if (smb_buffer == NULL) {
3326                 return -ENOMEM;
3327         }
3328         smb_buffer_response = smb_buffer;
3329
3330         header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
3331                         NULL /*no tid */ , 4 /*wct */ );
3332
3333         smb_buffer->Mid = GetNextMid(ses->server);
3334         smb_buffer->Uid = ses->Suid;
3335         pSMB = (TCONX_REQ *) smb_buffer;
3336         pSMBr = (TCONX_RSP *) smb_buffer_response;
3337
3338         pSMB->AndXCommand = 0xFF;
3339         pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
3340         bcc_ptr = &pSMB->Password[0];
3341         if((ses->server->secMode) & SECMODE_USER) {
3342                 pSMB->PasswordLength = cpu_to_le16(1);  /* minimum */
3343                 bcc_ptr++;              /* skip password */
3344         } else {
3345                 pSMB->PasswordLength = cpu_to_le16(CIFS_SESSION_KEY_SIZE);
3346                 /* BB FIXME add code to fail this if NTLMv2 or Kerberos
3347                    specified as required (when that support is added to
3348                    the vfs in the future) as only NTLM or the much
3349                    weaker LANMAN (which we do not send) is accepted
3350                    by Samba (not sure whether other servers allow
3351                    NTLMv2 password here) */
3352                 SMBNTencrypt(ses->password,
3353                              ses->server->cryptKey,
3354                              bcc_ptr);
3355
3356                 bcc_ptr += CIFS_SESSION_KEY_SIZE;
3357                 *bcc_ptr = 0;
3358                 bcc_ptr++; /* align */
3359         }
3360
3361         if(ses->server->secMode & 
3362                         (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED))
3363                 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
3364
3365         if (ses->capabilities & CAP_STATUS32) {
3366                 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
3367         }
3368         if (ses->capabilities & CAP_DFS) {
3369                 smb_buffer->Flags2 |= SMBFLG2_DFS;
3370         }
3371         if (ses->capabilities & CAP_UNICODE) {
3372                 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
3373                 length =
3374                     cifs_strtoUCS((__le16 *) bcc_ptr, tree, 
3375                         6 /* max utf8 char length in bytes */ * 
3376                         (/* server len*/ + 256 /* share len */), nls_codepage);
3377                 bcc_ptr += 2 * length;  /* convert num 16 bit words to bytes */
3378                 bcc_ptr += 2;   /* skip trailing null */
3379         } else {                /* ASCII */
3380                 strcpy(bcc_ptr, tree);
3381                 bcc_ptr += strlen(tree) + 1;
3382         }
3383         strcpy(bcc_ptr, "?????");
3384         bcc_ptr += strlen("?????");
3385         bcc_ptr += 1;
3386         count = bcc_ptr - &pSMB->Password[0];
3387         pSMB->hdr.smb_buf_length += count;
3388         pSMB->ByteCount = cpu_to_le16(count);
3389
3390         rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length, 0);
3391
3392         /* if (rc) rc = map_smb_to_linux_error(smb_buffer_response); */
3393         /* above now done in SendReceive */
3394         if ((rc == 0) && (tcon != NULL)) {
3395                 tcon->tidStatus = CifsGood;
3396                 tcon->tid = smb_buffer_response->Tid;
3397                 bcc_ptr = pByteArea(smb_buffer_response);
3398                 length = strnlen(bcc_ptr, BCC(smb_buffer_response) - 2);
3399         /* skip service field (NB: this field is always ASCII) */
3400                 bcc_ptr += length + 1;  
3401                 strncpy(tcon->treeName, tree, MAX_TREE_SIZE);
3402                 if (smb_buffer->Flags2 & SMBFLG2_UNICODE) {
3403                         length = UniStrnlen((wchar_t *) bcc_ptr, 512);
3404                         if ((bcc_ptr + (2 * length)) -
3405                              pByteArea(smb_buffer_response) <=
3406                             BCC(smb_buffer_response)) {
3407                                 kfree(tcon->nativeFileSystem);
3408                                 tcon->nativeFileSystem =
3409                                     kzalloc(length + 2, GFP_KERNEL);
3410                                 cifs_strfromUCS_le(tcon->nativeFileSystem,
3411                                                    (__le16 *) bcc_ptr,
3412                                                    length, nls_codepage);
3413                                 bcc_ptr += 2 * length;
3414                                 bcc_ptr[0] = 0; /* null terminate the string */
3415                                 bcc_ptr[1] = 0;
3416                                 bcc_ptr += 2;
3417                         }
3418                         /* else do not bother copying these informational fields */
3419                 } else {
3420                         length = strnlen(bcc_ptr, 1024);
3421                         if ((bcc_ptr + length) -
3422                             pByteArea(smb_buffer_response) <=
3423                             BCC(smb_buffer_response)) {
3424                                 kfree(tcon->nativeFileSystem);
3425                                 tcon->nativeFileSystem =
3426                                     kzalloc(length + 1, GFP_KERNEL);
3427                                 strncpy(tcon->nativeFileSystem, bcc_ptr,
3428                                         length);
3429                         }
3430                         /* else do not bother copying these informational fields */
3431                 }
3432                 tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
3433                 cFYI(1, ("Tcon flags: 0x%x ", tcon->Flags));
3434         } else if ((rc == 0) && tcon == NULL) {
3435         /* all we need to save for IPC$ connection */
3436                 ses->ipc_tid = smb_buffer_response->Tid;
3437         }
3438
3439         if (smb_buffer)
3440                 cifs_buf_release(smb_buffer);
3441         return rc;
3442 }
3443
3444 int
3445 cifs_umount(struct super_block *sb, struct cifs_sb_info *cifs_sb)
3446 {
3447         int rc = 0;
3448         int xid;
3449         struct cifsSesInfo *ses = NULL;
3450         struct task_struct *cifsd_task;
3451
3452         xid = GetXid();
3453
3454         if (cifs_sb->tcon) {
3455                 ses = cifs_sb->tcon->ses; /* save ptr to ses before delete tcon!*/
3456                 rc = CIFSSMBTDis(xid, cifs_sb->tcon);
3457                 if (rc == -EBUSY) {
3458                         FreeXid(xid);
3459                         return 0;
3460                 }
3461                 tconInfoFree(cifs_sb->tcon);
3462                 if ((ses) && (ses->server)) {
3463                         /* save off task so we do not refer to ses later */
3464                         cifsd_task = ses->server->tsk;
3465                         cFYI(1, ("About to do SMBLogoff "));
3466                         rc = CIFSSMBLogoff(xid, ses);
3467                         if (rc == -EBUSY) {
3468                                 FreeXid(xid);
3469                                 return 0;
3470                         } else if (rc == -ESHUTDOWN) {
3471                                 cFYI(1,("Waking up socket by sending it signal"));
3472                                 if(cifsd_task) {
3473                                         send_sig(SIGKILL,cifsd_task,1);
3474                                         wait_for_completion(&cifsd_complete);
3475                                 }
3476                                 rc = 0;
3477                         } /* else - we have an smb session
3478                                 left on this socket do not kill cifsd */
3479                 } else
3480                         cFYI(1, ("No session or bad tcon"));
3481         }
3482         
3483         cifs_sb->tcon = NULL;
3484         if (ses)
3485                 schedule_timeout_interruptible(msecs_to_jiffies(500));
3486         if (ses)
3487                 sesInfoFree(ses);
3488
3489         FreeXid(xid);
3490         return rc;              /* BB check if we should always return zero here */
3491
3492
3493 int cifs_setup_session(unsigned int xid, struct cifsSesInfo *pSesInfo,
3494                                            struct nls_table * nls_info)
3495 {
3496         int rc = 0;
3497         char ntlm_session_key[CIFS_SESSION_KEY_SIZE];
3498         int ntlmv2_flag = FALSE;
3499         int first_time = 0;
3500
3501         /* what if server changes its buffer size after dropping the session? */
3502         if(pSesInfo->server->maxBuf == 0) /* no need to send on reconnect */ {
3503                 rc = CIFSSMBNegotiate(xid, pSesInfo);
3504                 if(rc == -EAGAIN) /* retry only once on 1st time connection */ {
3505                         rc = CIFSSMBNegotiate(xid, pSesInfo);
3506                         if(rc == -EAGAIN) 
3507                                 rc = -EHOSTDOWN;
3508                 }
3509                 if(rc == 0) {
3510                         spin_lock(&GlobalMid_Lock);
3511                         if(pSesInfo->server->tcpStatus != CifsExiting)
3512                                 pSesInfo->server->tcpStatus = CifsGood;
3513                         else
3514                                 rc = -EHOSTDOWN;
3515                         spin_unlock(&GlobalMid_Lock);
3516
3517                 }
3518                 first_time = 1;
3519         }
3520         if (!rc) {
3521                 pSesInfo->capabilities = pSesInfo->server->capabilities;
3522                 if(linuxExtEnabled == 0)
3523                         pSesInfo->capabilities &= (~CAP_UNIX);
3524         /*      pSesInfo->sequence_number = 0;*/
3525                 cFYI(1,("Security Mode: 0x%x Capabilities: 0x%x Time Zone: %d",
3526                         pSesInfo->server->secMode,
3527                         pSesInfo->server->capabilities,
3528                         pSesInfo->server->timeZone));
3529 #ifdef CONFIG_CIFS_EXPERIMENTAL
3530                 if(experimEnabled > 1)
3531                         rc = CIFS_SessSetup(xid, pSesInfo, CIFS_NTLM /* type */,
3532                                             &ntlmv2_flag, nls_info);    
3533                 else
3534 #endif
3535                 if (extended_security
3536                                 && (pSesInfo->capabilities & CAP_EXTENDED_SECURITY)
3537                                 && (pSesInfo->server->secType == NTLMSSP)) {
3538                         cFYI(1, ("New style sesssetup"));
3539                         rc = CIFSSpnegoSessSetup(xid, pSesInfo,
3540                                 NULL /* security blob */, 
3541                                 0 /* blob length */,
3542                                 nls_info);
3543                 } else if (extended_security
3544                            && (pSesInfo->capabilities & CAP_EXTENDED_SECURITY)
3545                            && (pSesInfo->server->secType == RawNTLMSSP)) {
3546                         cFYI(1, ("NTLMSSP sesssetup"));
3547                         rc = CIFSNTLMSSPNegotiateSessSetup(xid,
3548                                                 pSesInfo,
3549                                                 &ntlmv2_flag,
3550                                                 nls_info);
3551                         if (!rc) {
3552                                 if(ntlmv2_flag) {
3553                                         char * v2_response;
3554                                         cFYI(1,("Can use more secure NTLM version 2 password hash"));
3555                                         if(CalcNTLMv2_partial_mac_key(pSesInfo, 
3556                                                 nls_info)) {
3557                                                 rc = -ENOMEM;
3558                                                 goto ss_err_exit;
3559                                         } else
3560                                                 v2_response = kmalloc(16 + 64 /* blob */, GFP_KERNEL);
3561                                         if(v2_response) {
3562                                                 CalcNTLMv2_response(pSesInfo,v2_response);
3563                                 /*              if(first_time)
3564                                                         cifs_calculate_ntlmv2_mac_key(
3565                                                           pSesInfo->server->mac_signing_key, 
3566                                                           response, ntlm_session_key, */
3567                                                 kfree(v2_response);
3568                                         /* BB Put dummy sig in SessSetup PDU? */
3569                                         } else {
3570                                                 rc = -ENOMEM;
3571                                                 goto ss_err_exit;
3572                                         }
3573
3574                                 } else {
3575                                         SMBNTencrypt(pSesInfo->password,
3576                                                 pSesInfo->server->cryptKey,
3577                                                 ntlm_session_key);
3578
3579                                         if(first_time)
3580                                                 cifs_calculate_mac_key(
3581                                                         pSesInfo->server->mac_signing_key,
3582                                                         ntlm_session_key,
3583                                                         pSesInfo->password);
3584                                 }
3585                         /* for better security the weaker lanman hash not sent
3586                            in AuthSessSetup so we no longer calculate it */
3587
3588                                 rc = CIFSNTLMSSPAuthSessSetup(xid,
3589                                         pSesInfo,
3590                                         ntlm_session_key,
3591                                         ntlmv2_flag,
3592                                         nls_info);
3593                         }
3594                 } else { /* old style NTLM 0.12 session setup */
3595                         SMBNTencrypt(pSesInfo->password,
3596                                 pSesInfo->server->cryptKey,
3597                                 ntlm_session_key);
3598
3599                         if(first_time)          
3600                                 cifs_calculate_mac_key(
3601                                         pSesInfo->server->mac_signing_key,
3602                                         ntlm_session_key, pSesInfo->password);
3603
3604                         rc = CIFSSessSetup(xid, pSesInfo,
3605                                 ntlm_session_key, nls_info);
3606                 }
3607                 if (rc) {
3608                         cERROR(1,("Send error in SessSetup = %d",rc));
3609                 } else {
3610                         cFYI(1,("CIFS Session Established successfully"));
3611                         pSesInfo->status = CifsGood;
3612                 }
3613         }
3614 ss_err_exit:
3615         return rc;
3616 }
3617