4 * Copyright (C) International Business Machines Corp., 2002,2005
5 * Author(s): Steve French (sfrench@us.ibm.com)
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.
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.
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
22 #include <linux/slab.h>
23 #include <linux/ctype.h>
24 #include <linux/mempool.h>
27 #include "cifsproto.h"
28 #include "cifs_debug.h"
31 #include "cifs_unicode.h"
33 extern mempool_t *cifs_sm_req_poolp;
34 extern mempool_t *cifs_req_poolp;
35 extern struct task_struct * oplockThread;
37 /* The xid serves as a useful identifier for each incoming vfs request,
38 in a similar way to the mid which is useful to track each sent smb,
39 and CurrentXid can also provide a running counter (although it
40 will eventually wrap past zero) of the total vfs operations handled
41 since the cifs fs was mounted */
48 spin_lock(&GlobalMid_Lock);
49 GlobalTotalActiveXid++;
50 if (GlobalTotalActiveXid > GlobalMaxActiveXid)
51 GlobalMaxActiveXid = GlobalTotalActiveXid; /* keep high water mark for number of simultaneous vfs ops in our filesystem */
52 if(GlobalTotalActiveXid > 65000)
53 cFYI(1,("warning: more than 65000 requests active"));
54 xid = GlobalCurrentXid++;
55 spin_unlock(&GlobalMid_Lock);
60 _FreeXid(unsigned int xid)
62 spin_lock(&GlobalMid_Lock);
63 /* if(GlobalTotalActiveXid == 0)
65 GlobalTotalActiveXid--;
66 spin_unlock(&GlobalMid_Lock);
72 struct cifsSesInfo *ret_buf;
75 (struct cifsSesInfo *) kmalloc(sizeof (struct cifsSesInfo),
78 memset(ret_buf, 0, sizeof (struct cifsSesInfo));
79 write_lock(&GlobalSMBSeslock);
80 atomic_inc(&sesInfoAllocCount);
81 ret_buf->status = CifsNew;
82 list_add(&ret_buf->cifsSessionList, &GlobalSMBSessionList);
83 init_MUTEX(&ret_buf->sesSem);
84 write_unlock(&GlobalSMBSeslock);
90 sesInfoFree(struct cifsSesInfo *buf_to_free)
92 if (buf_to_free == NULL) {
93 cFYI(1, ("Null buffer passed to sesInfoFree"));
97 write_lock(&GlobalSMBSeslock);
98 atomic_dec(&sesInfoAllocCount);
99 list_del(&buf_to_free->cifsSessionList);
100 write_unlock(&GlobalSMBSeslock);
101 kfree(buf_to_free->serverOS);
102 kfree(buf_to_free->serverDomain);
103 kfree(buf_to_free->serverNOS);
104 kfree(buf_to_free->password);
108 struct cifsTconInfo *
111 struct cifsTconInfo *ret_buf;
113 (struct cifsTconInfo *) kmalloc(sizeof (struct cifsTconInfo),
116 memset(ret_buf, 0, sizeof (struct cifsTconInfo));
117 write_lock(&GlobalSMBSeslock);
118 atomic_inc(&tconInfoAllocCount);
119 list_add(&ret_buf->cifsConnectionList,
120 &GlobalTreeConnectionList);
121 ret_buf->tidStatus = CifsNew;
122 INIT_LIST_HEAD(&ret_buf->openFileList);
123 init_MUTEX(&ret_buf->tconSem);
124 #ifdef CONFIG_CIFS_STATS
125 spin_lock_init(&ret_buf->stat_lock);
127 write_unlock(&GlobalSMBSeslock);
133 tconInfoFree(struct cifsTconInfo *buf_to_free)
135 if (buf_to_free == NULL) {
136 cFYI(1, ("Null buffer passed to tconInfoFree"));
139 write_lock(&GlobalSMBSeslock);
140 atomic_dec(&tconInfoAllocCount);
141 list_del(&buf_to_free->cifsConnectionList);
142 write_unlock(&GlobalSMBSeslock);
143 kfree(buf_to_free->nativeFileSystem);
150 struct smb_hdr *ret_buf = NULL;
152 /* We could use negotiated size instead of max_msgsize -
153 but it may be more efficient to always alloc same size
154 albeit slightly larger than necessary and maxbuffersize
155 defaults to this and can not be bigger */
157 (struct smb_hdr *) mempool_alloc(cifs_req_poolp, SLAB_KERNEL | SLAB_NOFS);
159 /* clear the first few header bytes */
160 /* for most paths, more is cleared in header_assemble */
162 memset(ret_buf, 0, sizeof(struct smb_hdr) + 3);
163 atomic_inc(&bufAllocCount);
164 #ifdef CONFIG_CIFS_STATS2
165 atomic_inc(&totBufAllocCount);
166 #endif /* CONFIG_CIFS_STATS2 */
173 cifs_buf_release(void *buf_to_free)
176 if (buf_to_free == NULL) {
177 /* cFYI(1, ("Null buffer passed to cifs_buf_release"));*/
180 mempool_free(buf_to_free,cifs_req_poolp);
182 atomic_dec(&bufAllocCount);
187 cifs_small_buf_get(void)
189 struct smb_hdr *ret_buf = NULL;
191 /* We could use negotiated size instead of max_msgsize -
192 but it may be more efficient to always alloc same size
193 albeit slightly larger than necessary and maxbuffersize
194 defaults to this and can not be bigger */
196 (struct smb_hdr *) mempool_alloc(cifs_sm_req_poolp, SLAB_KERNEL | SLAB_NOFS);
198 /* No need to clear memory here, cleared in header assemble */
199 /* memset(ret_buf, 0, sizeof(struct smb_hdr) + 27);*/
200 atomic_inc(&smBufAllocCount);
201 #ifdef CONFIG_CIFS_STATS2
202 atomic_inc(&totSmBufAllocCount);
203 #endif /* CONFIG_CIFS_STATS2 */
210 cifs_small_buf_release(void *buf_to_free)
213 if (buf_to_free == NULL) {
214 cFYI(1, ("Null buffer passed to cifs_small_buf_release"));
217 mempool_free(buf_to_free,cifs_sm_req_poolp);
219 atomic_dec(&smBufAllocCount);
224 Find a free multiplex id (SMB mid). Otherwise there could be
225 mid collisions which might cause problems, demultiplexing the
226 wrong response to this request. Multiplex ids could collide if
227 one of a series requests takes much longer than the others, or
228 if a very large number of long lived requests (byte range
229 locks or FindNotify requests) are pending. No more than
230 64K-1 requests can be outstanding at one time. If no
231 mids are available, return zero. A future optimization
232 could make the combination of mids and uid the key we use
233 to demultiplex on (rather than mid alone).
234 In addition to the above check, the cifs demultiplex
235 code already used the command code as a secondary
236 check of the frame and if signing is negotiated the
237 response would be discarded if the mid were the same
238 but the signature was wrong. Since the mid is not put in the
239 pending queue until later (when it is about to be dispatched)
240 we do have to limit the number of outstanding requests
241 to somewhat less than 64K-1 although it is hard to imagine
242 so many threads being in the vfs at one time.
244 __u16 GetNextMid(struct TCP_Server_Info *server)
253 spin_lock(&GlobalMid_Lock);
254 last_mid = server->CurrentMid; /* we do not want to loop forever */
255 server->CurrentMid++;
256 /* This nested loop looks more expensive than it is.
257 In practice the list of pending requests is short,
258 fewer than 50, and the mids are likely to be unique
259 on the first pass through the loop unless some request
260 takes longer than the 64 thousand requests before it
261 (and it would also have to have been a request that
263 while(server->CurrentMid != last_mid) {
264 struct list_head *tmp;
265 struct mid_q_entry *mid_entry;
268 if(server->CurrentMid == 0)
269 server->CurrentMid++;
271 list_for_each(tmp, &server->pending_mid_q) {
272 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
274 if ((mid_entry->mid == server->CurrentMid) &&
275 (mid_entry->midState == MID_REQUEST_SUBMITTED)) {
276 /* This mid is in use, try a different one */
282 mid = server->CurrentMid;
285 server->CurrentMid++;
287 spin_unlock(&GlobalMid_Lock);
291 /* NB: MID can not be set if treeCon not passed in, in that
292 case it is responsbility of caller to set the mid */
294 header_assemble(struct smb_hdr *buffer, char smb_command /* command */ ,
295 const struct cifsTconInfo *treeCon, int word_count
296 /* length of fixed section (word count) in two byte units */)
298 struct list_head* temp_item;
299 struct cifsSesInfo * ses;
300 char *temp = (char *) buffer;
302 memset(temp,0,256); /* bigger than MAX_CIFS_HDR_SIZE */
304 buffer->smb_buf_length =
305 (2 * word_count) + sizeof (struct smb_hdr) -
306 4 /* RFC 1001 length field does not count */ +
307 2 /* for bcc field itself */ ;
308 /* Note that this is the only network field that has to be converted
309 to big endian and it is done just before we send it */
311 buffer->Protocol[0] = 0xFF;
312 buffer->Protocol[1] = 'S';
313 buffer->Protocol[2] = 'M';
314 buffer->Protocol[3] = 'B';
315 buffer->Command = smb_command;
316 buffer->Flags = 0x00; /* case sensitive */
317 buffer->Flags2 = SMBFLG2_KNOWS_LONG_NAMES;
318 buffer->Pid = cpu_to_le16((__u16)current->tgid);
319 buffer->PidHigh = cpu_to_le16((__u16)(current->tgid >> 16));
320 spin_lock(&GlobalMid_Lock);
321 spin_unlock(&GlobalMid_Lock);
323 buffer->Tid = treeCon->tid;
325 if (treeCon->ses->capabilities & CAP_UNICODE)
326 buffer->Flags2 |= SMBFLG2_UNICODE;
327 if (treeCon->ses->capabilities & CAP_STATUS32) {
328 buffer->Flags2 |= SMBFLG2_ERR_STATUS;
330 /* Uid is not converted */
331 buffer->Uid = treeCon->ses->Suid;
332 buffer->Mid = GetNextMid(treeCon->ses->server);
333 if(multiuser_mount != 0) {
334 /* For the multiuser case, there are few obvious technically */
335 /* possible mechanisms to match the local linux user (uid) */
336 /* to a valid remote smb user (smb_uid): */
337 /* 1) Query Winbind (or other local pam/nss daemon */
338 /* for userid/password/logon_domain or credential */
339 /* 2) Query Winbind for uid to sid to username mapping */
340 /* and see if we have a matching password for existing*/
341 /* session for that user perhas getting password by */
342 /* adding a new pam_cifs module that stores passwords */
343 /* so that the cifs vfs can get at that for all logged*/
345 /* 3) (Which is the mechanism we have chosen) */
346 /* Search through sessions to the same server for a */
347 /* a match on the uid that was passed in on mount */
348 /* with the current processes uid (or euid?) and use */
349 /* that smb uid. If no existing smb session for */
350 /* that uid found, use the default smb session ie */
351 /* the smb session for the volume mounted which is */
352 /* the same as would be used if the multiuser mount */
353 /* flag were disabled. */
355 /* BB Add support for establishing new tCon and SMB Session */
356 /* with userid/password pairs found on the smb session */
357 /* for other target tcp/ip addresses BB */
358 if(current->fsuid != treeCon->ses->linux_uid) {
359 cFYI(1,("Multiuser mode and UID did not match tcon uid"));
360 read_lock(&GlobalSMBSeslock);
361 list_for_each(temp_item, &GlobalSMBSessionList) {
362 ses = list_entry(temp_item, struct cifsSesInfo, cifsSessionList);
363 if(ses->linux_uid == current->fsuid) {
364 if(ses->server == treeCon->ses->server) {
365 cFYI(1,("found matching uid substitute right smb_uid"));
366 buffer->Uid = ses->Suid;
369 /* BB eventually call cifs_setup_session here */
370 cFYI(1,("local UID found but smb sess with this server does not exist"));
374 read_unlock(&GlobalSMBSeslock);
378 if (treeCon->Flags & SMB_SHARE_IS_IN_DFS)
379 buffer->Flags2 |= SMBFLG2_DFS;
381 buffer->Flags |= SMBFLG_CASELESS;
382 if((treeCon->ses) && (treeCon->ses->server))
383 if(treeCon->ses->server->secMode &
384 (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED))
385 buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
388 /* endian conversion of flags is now done just before sending */
389 buffer->WordCount = (char) word_count;
394 checkSMBhdr(struct smb_hdr *smb, __u16 mid)
396 /* Make sure that this really is an SMB, that it is a response,
397 and that the message ids match */
398 if ((*(__le32 *) smb->Protocol == cpu_to_le32(0x424d53ff)) &&
400 if(smb->Flags & SMBFLG_RESPONSE)
403 /* only one valid case where server sends us request */
404 if(smb->Command == SMB_COM_LOCKING_ANDX)
407 cERROR(1, ("Rcvd Request not response"));
409 } else { /* bad signature or mid */
410 if (*(__le32 *) smb->Protocol != cpu_to_le32(0x424d53ff))
412 ("Bad protocol string signature header %x",
413 *(unsigned int *) smb->Protocol));
415 cERROR(1, ("Mids do not match"));
417 cERROR(1, ("bad smb detected. The Mid=%d", smb->Mid));
422 checkSMB(struct smb_hdr *smb, __u16 mid, int length)
424 __u32 len = smb->smb_buf_length;
425 __u32 clc_len; /* calculated length */
427 ("Entering checkSMB with Length: %x, smb_buf_length: %x",
429 if (((unsigned int)length < 2 + sizeof (struct smb_hdr)) ||
430 (len > CIFSMaxBufSize + MAX_CIFS_HDR_SIZE - 4)) {
431 if ((unsigned int)length < 2 + sizeof (struct smb_hdr)) {
432 if (((unsigned int)length >=
433 sizeof (struct smb_hdr) - 1)
434 && (smb->Status.CifsError != 0)) {
436 return 0; /* some error cases do not return wct and bcc */
438 cERROR(1, ("Length less than smb header size"));
442 if (len > CIFSMaxBufSize + MAX_CIFS_HDR_SIZE - 4)
444 ("smb_buf_length greater than MaxBufSize"));
446 ("bad smb detected. Illegal length. mid=%d",
451 if (checkSMBhdr(smb, mid))
453 clc_len = smbCalcSize_LE(smb);
454 if ((4 + len != clc_len)
455 || (4 + len != (unsigned int)length)) {
456 cERROR(1, ("Calculated size 0x%x vs actual length 0x%x",
458 cERROR(1, ("bad smb size detected for Mid=%d", smb->Mid));
459 /* Windows XP can return a few bytes too much, presumably
460 an illegal pad, at the end of byte range lock responses
461 so we allow for that three byte pad, as long as actual
462 received length is as long or longer than calculated length */
463 /* We have now had to extend this more, since there is a
464 case in which it needs to be bigger still to handle a
465 malformed response to transact2 findfirst from WinXP when
466 access denied is returned and thus bcc and wct are zero
467 but server says length is 0x21 bytes too long as if the server
468 forget to reset the smb rfc1001 length when it reset the
469 wct and bcc to minimum size and drop the t2 parms and data */
470 if((4+len > clc_len) && (len <= clc_len + 512))
478 is_valid_oplock_break(struct smb_hdr *buf, struct TCP_Server_Info *srv)
480 struct smb_com_lock_req * pSMB = (struct smb_com_lock_req *)buf;
481 struct list_head *tmp;
482 struct list_head *tmp1;
483 struct cifsTconInfo *tcon;
484 struct cifsFileInfo *netfile;
486 cFYI(1,("Checking for oplock break or dnotify response"));
487 if((pSMB->hdr.Command == SMB_COM_NT_TRANSACT) &&
488 (pSMB->hdr.Flags & SMBFLG_RESPONSE)) {
489 struct smb_com_transaction_change_notify_rsp * pSMBr =
490 (struct smb_com_transaction_change_notify_rsp *)buf;
491 struct file_notify_information * pnotify;
492 __u32 data_offset = 0;
493 if(pSMBr->ByteCount > sizeof(struct file_notify_information)) {
494 data_offset = le32_to_cpu(pSMBr->DataOffset);
496 pnotify = (struct file_notify_information *)((char *)&pSMBr->hdr.Protocol
498 cFYI(1,("dnotify on %s with action: 0x%x",pnotify->FileName,
499 pnotify->Action)); /* BB removeme BB */
500 /* cifs_dump_mem("Received notify Data is: ",buf,sizeof(struct smb_hdr)+60); */
503 if(pSMBr->hdr.Status.CifsError) {
504 cFYI(1,("notify err 0x%d",pSMBr->hdr.Status.CifsError));
509 if(pSMB->hdr.Command != SMB_COM_LOCKING_ANDX)
511 if(pSMB->hdr.Flags & SMBFLG_RESPONSE) {
512 /* no sense logging error on invalid handle on oplock
513 break - harmless race between close request and oplock
514 break response is expected from time to time writing out
515 large dirty files cached on the client */
516 if ((NT_STATUS_INVALID_HANDLE) ==
517 le32_to_cpu(pSMB->hdr.Status.CifsError)) {
518 cFYI(1,("invalid handle on oplock break"));
520 } else if (ERRbadfid ==
521 le16_to_cpu(pSMB->hdr.Status.DosError.Error)) {
524 return FALSE; /* on valid oplock brk we get "request" */
527 if(pSMB->hdr.WordCount != 8)
530 cFYI(1,(" oplock type 0x%d level 0x%d",pSMB->LockType,pSMB->OplockLevel));
531 if(!(pSMB->LockType & LOCKING_ANDX_OPLOCK_RELEASE))
534 /* look up tcon based on tid & uid */
535 read_lock(&GlobalSMBSeslock);
536 list_for_each(tmp, &GlobalTreeConnectionList) {
537 tcon = list_entry(tmp, struct cifsTconInfo, cifsConnectionList);
538 if ((tcon->tid == buf->Tid) && (srv == tcon->ses->server)) {
539 cifs_stats_inc(&tcon->num_oplock_brks);
540 list_for_each(tmp1,&tcon->openFileList){
541 netfile = list_entry(tmp1,struct cifsFileInfo,
543 if(pSMB->Fid == netfile->netfid) {
544 struct cifsInodeInfo *pCifsInode;
545 read_unlock(&GlobalSMBSeslock);
546 cFYI(1,("file id match, oplock break"));
548 CIFS_I(netfile->pInode);
549 pCifsInode->clientCanCacheAll = FALSE;
550 if(pSMB->OplockLevel == 0)
551 pCifsInode->clientCanCacheRead
553 pCifsInode->oplockPending = TRUE;
554 AllocOplockQEntry(netfile->pInode,
557 cFYI(1,("about to wake up oplock thd"));
559 wake_up_process(oplockThread);
563 read_unlock(&GlobalSMBSeslock);
564 cFYI(1,("No matching file for oplock break"));
568 read_unlock(&GlobalSMBSeslock);
569 cFYI(1,("Can not process oplock break for non-existent connection"));
574 dump_smb(struct smb_hdr *smb_buf, int smb_buf_length)
578 unsigned char *buffer;
583 buffer = (unsigned char *) smb_buf;
584 for (i = 0, j = 0; i < smb_buf_length; i++, j++) {
585 if (i % 8 == 0) { /* have reached the beginning of line */
586 printk(KERN_DEBUG "| ");
589 printk("%0#4x ", buffer[i]);
590 debug_line[2 * j] = ' ';
591 if (isprint(buffer[i]))
592 debug_line[1 + (2 * j)] = buffer[i];
594 debug_line[1 + (2 * j)] = '_';
596 if (i % 8 == 7) { /* reached end of line, time to print ascii */
598 printk(" | %s\n", debug_line);
603 debug_line[2 * j] = ' ';
604 debug_line[1 + (2 * j)] = ' ';
606 printk( " | %s\n", debug_line);
610 /* Windows maps these to the user defined 16 bit Unicode range since they are
611 reserved symbols (along with \ and /), otherwise illegal to store
612 in filenames in NTFS */
613 #define UNI_ASTERIK (__u16) ('*' + 0xF000)
614 #define UNI_QUESTION (__u16) ('?' + 0xF000)
615 #define UNI_COLON (__u16) (':' + 0xF000)
616 #define UNI_GRTRTHAN (__u16) ('>' + 0xF000)
617 #define UNI_LESSTHAN (__u16) ('<' + 0xF000)
618 #define UNI_PIPE (__u16) ('|' + 0xF000)
619 #define UNI_SLASH (__u16) ('\\' + 0xF000)
621 /* Convert 16 bit Unicode pathname from wire format to string in current code
622 page. Conversion may involve remapping up the seven characters that are
623 only legal in POSIX-like OS (if they are present in the string). Path
624 names are little endian 16 bit Unicode on the wire */
626 cifs_convertUCSpath(char *target, const __le16 * source, int maxlen,
627 const struct nls_table * cp)
632 for(i = 0, j = 0; i < maxlen; i++) {
633 src_char = le16_to_cpu(source[i]);
636 goto cUCS_out; /* BB check this BB */
646 /* BB We can not handle remapping slash until
647 all the calls to build_path_from_dentry
648 are modified, as they use slash as separator BB */
662 len = cp->uni2char(src_char, &target[j],
663 NLS_MAX_CHARSET_SIZE);
672 /* make sure we do not overrun callers allocated temp buffer */
673 if(j >= (2 * NAME_MAX))
681 /* Convert 16 bit Unicode pathname to wire format from string in current code
682 page. Conversion may involve remapping up the seven characters that are
683 only legal in POSIX-like OS (if they are present in the string). Path
684 names are little endian 16 bit Unicode on the wire */
686 cifsConvertToUCS(__le16 * target, const char *source, int maxlen,
687 const struct nls_table * cp, int mapChars)
690 int len_remaining = maxlen;
695 return cifs_strtoUCS(target, source, PATH_MAX, cp);
697 for(i = 0, j = 0; i < maxlen; j++) {
698 src_char = source[i];
704 target[j] = cpu_to_le16(UNI_COLON);
707 target[j] = cpu_to_le16(UNI_ASTERIK);
710 target[j] = cpu_to_le16(UNI_QUESTION);
713 target[j] = cpu_to_le16(UNI_LESSTHAN);
716 target[j] = cpu_to_le16(UNI_GRTRTHAN);
719 target[j] = cpu_to_le16(UNI_PIPE);
721 /* BB We can not handle remapping slash until
722 all the calls to build_path_from_dentry
723 are modified, as they use slash as separator BB */
725 target[j] = cpu_to_le16(UNI_SLASH);
728 charlen = cp->char2uni(source+i,
729 len_remaining, &temp);
730 /* if no match, use question mark, which
731 at least in some cases servers as wild card */
733 target[j] = cpu_to_le16(0x003f);
736 target[j] = cpu_to_le16(temp);
737 len_remaining -= charlen;
738 /* character may take more than one byte in the
739 the source string, but will take exactly two
740 bytes in the target string */
744 i++; /* move to next char in source string */