2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
12 #define NOMOREFILESFIX 1
14 #include <afs/param.h>
20 #include <sys/timeb.h>
35 #include "lanahelper.h"
37 /* These characters are illegal in Windows filenames */
38 static char *illegalChars = "\\/:*?\"<>|";
39 BOOL isWindows2000 = FALSE;
41 smb_vc_t *dead_vcp = NULL;
42 smb_vc_t *active_vcp = NULL;
44 /* TODO; logout mechanism needs to be thread-safe */
45 char *loggedOutName = NULL;
46 smb_user_t *loggedOutUserp = NULL;
47 unsigned long loggedOutTime;
49 int smbShutdownFlag = 0;
51 int smb_LogoffTokenTransfer;
52 unsigned long smb_LogoffTransferTimeout;
54 DWORD last_msg_time = 0;
58 unsigned int sessionGen = 0;
60 extern void afsi_log(char *pattern, ...);
61 extern HANDLE afsi_file;
63 osi_hyper_t hzero = {0, 0};
64 osi_hyper_t hones = {0xFFFFFFFF, -1};
67 osi_rwlock_t smb_globalLock;
68 osi_rwlock_t smb_rctLock;
69 osi_mutex_t smb_ListenerLock;
72 unsigned char smb_sharename[NCBNAMSZ+1] = {0};
75 long smb_maxObsConcurrentCalls=0;
76 long smb_concurrentCalls=0;
78 smb_dispatch_t smb_dispatchTable[SMB_NOPCODES];
80 smb_packet_t *smb_packetFreeListp;
81 smb_ncb_t *smb_ncbFreeListp;
83 int smb_NumServerThreads;
85 int numNCBs, numSessions;
87 int smb_maxVCPerServer;
88 int smb_maxMpxRequests;
90 #define NCBmax MAXIMUM_WAIT_OBJECTS
91 EVENT_HANDLE NCBavails[NCBmax], NCBevents[NCBmax];
92 EVENT_HANDLE **NCBreturns;
93 DWORD NCBsessions[NCBmax];
95 struct smb_packet *bufs[NCBmax];
97 #define Sessionmax MAXIMUM_WAIT_OBJECTS
98 EVENT_HANDLE SessionEvents[Sessionmax];
99 unsigned short LSNs[Sessionmax];
100 int lanas[Sessionmax];
101 BOOL dead_sessions[Sessionmax];
105 osi_mutex_t smb_RawBufLock;
107 #define SMB_RAW_BUFS 4
109 int smb_RawBufSel[SMB_RAW_BUFS];
114 #define RAWTIMEOUT INFINITE
117 typedef struct raw_write_cont {
130 /* dir search stuff */
131 long smb_dirSearchCounter = 1;
132 smb_dirSearch_t *smb_firstDirSearchp;
133 smb_dirSearch_t *smb_lastDirSearchp;
135 /* hide dot files? */
136 int smb_hideDotFiles;
138 /* global state about V3 protocols */
139 int smb_useV3; /* try to negotiate V3 */
142 static showErrors = 1;
143 /* MessageBox or something like it */
144 int (_stdcall *smb_MBfunc)(HWND, LPCTSTR, LPCTSTR, UINT) = NULL;
145 extern HANDLE WaitToTerminate;
149 * Time in Unix format of midnight, 1/1/1970 local time.
150 * When added to dosUTime, gives Unix (AFS) time.
154 /* Time difference for converting to kludge-GMT */
157 char *smb_localNamep = NULL;
159 smb_vc_t *smb_allVCsp;
161 smb_username_t *usernamesp = NULL;
163 smb_waitingLock_t *smb_allWaitingLocks;
166 void smb_DispatchPacket(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp,
167 NCB *ncbp, raw_write_cont_t *rwcp);
168 void smb_NetbiosInit();
170 #ifndef AFS_WIN95_ENV
171 DWORD smb_ServerExceptionFilter(void);
174 extern char cm_HostName[];
175 extern char cm_confDir[];
179 #define LPTSTR char *
180 #define GetComputerName(str, sizep) \
181 strcpy((str), cm_HostName); \
182 *(sizep) = strlen(cm_HostName)
185 extern char AFSConfigKeyName[];
190 * To build an expiring version, comment out the definition of NOEXPIRE,
191 * and set the definition of EXPIREDATE to the desired value.
194 #define EXPIREDATE 834000000 /* Wed Jun 5 1996 */
197 char * myCrt_Dispatch(int i)
202 return "unknown SMB op";
204 return "(00)ReceiveCoreMakeDir";
206 return "(01)ReceiveCoreRemoveDir";
208 return "(02)ReceiveCoreOpen";
210 return "(03)ReceiveCoreCreate";
212 return "(04)ReceiveCoreClose";
214 return "(05)ReceiveCoreFlush";
216 return "(06)ReceiveCoreUnlink";
218 return "(07)ReceiveCoreRename";
220 return "(08)ReceiveCoreGetFileAttributes";
222 return "(09)ReceiveCoreSetFileAttributes";
224 return "(0a)ReceiveCoreRead";
226 return "(0b)ReceiveCoreWrite";
228 return "(0c)ReceiveCoreLockRecord";
230 return "(0d)ReceiveCoreUnlockRecord";
232 return "(0e)SendCoreBadOp";
234 return "(0f)ReceiveCoreCreate";
236 return "(10)ReceiveCoreCheckPath";
238 return "(11)SendCoreBadOp";
240 return "(12)ReceiveCoreSeek";
242 return "(1a)ReceiveCoreReadRaw";
244 return "(1d)ReceiveCoreWriteRawDummy";
246 return "(22)ReceiveV3SetAttributes";
248 return "(23)ReceiveV3GetAttributes";
250 return "(24)ReceiveV3LockingX";
252 return "(29)SendCoreBadOp";
254 return "(2b)ReceiveCoreEcho";
256 return "(2d)ReceiveV3OpenX";
258 return "(2e)ReceiveV3ReadX";
260 return "(32)ReceiveV3Tran2A";
262 return "(33)ReceiveV3Tran2A";
264 return "(34)ReceiveV3FindClose";
266 return "(35)ReceiveV3FindNotifyClose";
268 return "(70)ReceiveCoreTreeConnect";
270 return "(71)ReceiveCoreTreeDisconnect";
272 return "(72)ReceiveNegotiate";
274 return "(73)ReceiveV3SessionSetupX";
276 return "(74)ReceiveV3UserLogoffX";
278 return "(75)ReceiveV3TreeConnectX";
280 return "(80)ReceiveCoreGetDiskAttributes";
282 return "(81)ReceiveCoreSearchDir";
284 return "(A0)ReceiveNTTransact";
286 return "(A2)ReceiveNTCreateX";
288 return "(A4)ReceiveNTCancel";
290 return "(c0)SendCoreBadOp";
292 return "(c1)SendCoreBadOp";
294 return "(c2)SendCoreBadOp";
296 return "(c3)SendCoreBadOp";
300 char * myCrt_2Dispatch(int i)
305 return "unknown SMB op-2";
307 return "S(00)CreateFile";
309 return "S(01)FindFirst";
311 return "S(02)FindNext"; /* FindNext */
313 return "S(03)QueryFileSystem_ReceiveTran2QFSInfo";
317 return "S(05)QueryFileInfo_ReceiveTran2QPathInfo";
319 return "S(06)SetFileInfo_ReceiveTran2SetPathInfo";
321 return "S(07)SetInfoHandle_ReceiveTran2QFileInfo";
323 return "S(08)??_ReceiveTran2SetFileInfo";
325 return "S(09)??_ReceiveTran2FSCTL";
327 return "S(0a)_ReceiveTran2IOCTL";
329 return "S(0b)_ReceiveTran2FindNotifyFirst";
331 return "S(0c)_ReceiveTran2FindNotifyNext";
333 return "S(0d)CreateDirectory_ReceiveTran2MKDir";
337 /* scache must be locked */
338 unsigned int smb_Attributes(cm_scache_t *scp)
342 if (scp->fileType == CM_SCACHETYPE_DIRECTORY
343 || scp->fileType == CM_SCACHETYPE_MOUNTPOINT)
344 attrs = SMB_ATTR_DIRECTORY;
349 * We used to mark a file RO if it was in an RO volume, but that
350 * turns out to be impolitic in NT. See defect 10007.
353 if ((scp->unixModeBits & 0222) == 0 || (scp->flags & CM_SCACHEFLAG_RO))
355 if ((scp->unixModeBits & 0222) == 0)
356 attrs |= SMB_ATTR_READONLY; /* turn on read-only flag */
361 /* Check if the named file/dir is a dotfile/dotdir */
362 /* String pointed to by lastComp can have leading slashes, but otherwise should have
363 no other patch components */
364 unsigned int smb_IsDotFile(char *lastComp) {
367 /* skip over slashes */
368 for(s=lastComp;*s && (*s == '\\' || *s == '/'); s++);
373 /* nulls, curdir and parent dir doesn't count */
376 if(!*(s + 1)) return 0;
377 if(*(s+1) == '.' && !*(s + 2)) return 0;
383 static int ExtractBits(WORD bits, short start, short len)
390 num = bits << (16 - end);
391 num = num >> ((16 - end) + start);
397 void ShowUnixTime(char *FuncName, long unixTime)
402 smb_LargeSearchTimeFromUnixTime(&ft, unixTime);
404 if (!FileTimeToDosDateTime(&ft, &wDate, &wTime))
405 osi_Log1(smb_logp, "Failed to convert filetime to dos datetime: %d", GetLastError());
407 int day, month, year, sec, min, hour;
410 day = ExtractBits(wDate, 0, 5);
411 month = ExtractBits(wDate, 5, 4);
412 year = ExtractBits(wDate, 9, 7) + 1980;
414 sec = ExtractBits(wTime, 0, 5);
415 min = ExtractBits(wTime, 5, 6);
416 hour = ExtractBits(wTime, 11, 5);
418 sprintf(msg, "%s = %02d-%02d-%04d %02d:%02d:%02d", FuncName, month, day, year, hour, min, sec);
419 osi_Log1(smb_logp, "%s", osi_LogSaveString(smb_logp, msg));
425 /* Determine if we are observing daylight savings time */
426 void GetTimeZoneInfo(BOOL *pDST, LONG *pDstBias, LONG *pBias)
428 TIME_ZONE_INFORMATION timeZoneInformation;
429 SYSTEMTIME utc, local, localDST;
431 /* Get the time zone info. NT uses this to calc if we are in DST. */
432 GetTimeZoneInformation(&timeZoneInformation);
434 /* Return the daylight bias */
435 *pDstBias = timeZoneInformation.DaylightBias;
437 /* Return the bias */
438 *pBias = timeZoneInformation.Bias;
440 /* Now determine if DST is being observed */
442 /* Get the UTC (GMT) time */
445 /* Convert UTC time to local time using the time zone info. If we are
446 observing DST, the calculated local time will include this.
448 SystemTimeToTzSpecificLocalTime(&timeZoneInformation, &utc, &localDST);
450 /* Set the daylight bias to 0. The daylight bias is the amount of change
451 in time that we use for daylight savings time. By setting this to 0
452 we cause there to be no change in time during daylight savings time.
454 timeZoneInformation.DaylightBias = 0;
456 /* Convert the utc time to local time again, but this time without any
457 adjustment for daylight savings time.
459 SystemTimeToTzSpecificLocalTime(&timeZoneInformation, &utc, &local);
461 /* If the two times are different, then it means that the localDST that
462 we calculated includes the daylight bias, and therefore we are
463 observing daylight savings time.
465 *pDST = localDST.wHour != local.wHour;
468 /* Determine if we are observing daylight savings time */
469 void GetTimeZoneInfo(BOOL *pDST, LONG *pDstBias, LONG *pBias)
475 *pDstBias = -60; /* where can this be different? */
481 void CompensateForSmbClientLastWriteTimeBugs(long *pLastWriteTime)
483 BOOL dst; /* Will be TRUE if observing DST */
484 LONG dstBias; /* Offset from local time if observing DST */
485 LONG bias; /* Offset from GMT for local time */
488 * This function will adjust the last write time to compensate
489 * for two bugs in the smb client:
491 * 1) During Daylight Savings Time, the LastWriteTime is ahead
492 * in time by the DaylightBias (ignoring the sign - the
493 * DaylightBias is always stored as a negative number). If
494 * the DaylightBias is -60, then the LastWriteTime will be
495 * ahead by 60 minutes.
497 * 2) If the local time zone is a positive offset from GMT, then
498 * the LastWriteTime will be the correct local time plus the
499 * Bias (ignoring the sign - a positive offset from GMT is
500 * always stored as a negative Bias). If the Bias is -120,
501 * then the LastWriteTime will be ahead by 120 minutes.
503 * These bugs can occur at the same time.
506 GetTimeZoneInfo(&dst, &dstBias, &bias);
508 /* First adjust for DST */
510 *pLastWriteTime -= (-dstBias * 60); /* Convert dstBias to seconds */
512 /* Now adjust for a positive offset from GMT (a negative bias). */
514 *pLastWriteTime -= (-bias * 60); /* Convert bias to seconds */
518 * Calculate the difference (in seconds) between local time and GMT.
519 * This enables us to convert file times to kludge-GMT.
525 struct tm gmt_tm, local_tm;
526 int days, hours, minutes, seconds;
529 gmt_tm = *(gmtime(&t));
530 local_tm = *(localtime(&t));
532 days = local_tm.tm_yday - gmt_tm.tm_yday;
533 hours = 24 * days + local_tm.tm_hour - gmt_tm.tm_hour
535 /* There is a problem with DST immediately after the time change
536 * which may continue to exist until the machine is rebooted
538 - (local_tm.tm_isdst ? 1 : 0)
541 minutes = 60 * hours + local_tm.tm_min - gmt_tm.tm_min;
542 seconds = 60 * minutes + local_tm.tm_sec - gmt_tm.tm_sec;
548 void smb_LargeSearchTimeFromUnixTime(FILETIME *largeTimep, long unixTime)
553 long ersatz_unixTime;
556 * Must use kludge-GMT instead of real GMT.
557 * kludge-GMT is computed by adding time zone difference to localtime.
560 * ltp = gmtime(&unixTime);
562 ersatz_unixTime = unixTime - smb_NowTZ;
563 ltp = localtime(&ersatz_unixTime);
565 /* if we fail, make up something */
568 localJunk.tm_year = 89 - 20;
569 localJunk.tm_mon = 4;
570 localJunk.tm_mday = 12;
571 localJunk.tm_hour = 0;
572 localJunk.tm_min = 0;
573 localJunk.tm_sec = 0;
576 stm.wYear = ltp->tm_year + 1900;
577 stm.wMonth = ltp->tm_mon + 1;
578 stm.wDayOfWeek = ltp->tm_wday;
579 stm.wDay = ltp->tm_mday;
580 stm.wHour = ltp->tm_hour;
581 stm.wMinute = ltp->tm_min;
582 stm.wSecond = ltp->tm_sec;
583 stm.wMilliseconds = 0;
585 SystemTimeToFileTime(&stm, largeTimep);
588 void smb_LargeSearchTimeFromUnixTime(FILETIME *largeTimep, long unixTime)
590 /* unixTime: seconds since 1/1/1970 00:00:00 GMT */
591 /* FILETIME: 100ns intervals since 1/1/1601 00:00:00 ??? */
592 LARGE_INTEGER *ft = (LARGE_INTEGER *) largeTimep;
594 int leap_years = 89; /* leap years betw 1/1/1601 and 1/1/1970 */
596 /* set ft to number of 100ns intervals betw 1/1/1601 and 1/1/1970 GMT */
597 *ft = ConvertLongToLargeInteger(((EPOCH_YEAR-1601) * 365 + leap_years)
599 *ft = LargeIntegerMultiplyByLong(*ft, 60);
600 *ft = LargeIntegerMultiplyByLong(*ft, 10000000);
603 ut = ConvertLongToLargeInteger(unixTime);
604 ut = LargeIntegerMultiplyByLong(ut, 10000000);
605 *ft = LargeIntegerAdd(*ft, ut);
610 void smb_UnixTimeFromLargeSearchTime(long *unixTimep, FILETIME *largeTimep)
616 FileTimeToSystemTime(largeTimep, &stm);
618 lt.tm_year = stm.wYear - 1900;
619 lt.tm_mon = stm.wMonth - 1;
620 lt.tm_wday = stm.wDayOfWeek;
621 lt.tm_mday = stm.wDay;
622 lt.tm_hour = stm.wHour;
623 lt.tm_min = stm.wMinute;
624 lt.tm_sec = stm.wSecond;
627 save_timezone = _timezone;
628 _timezone += smb_NowTZ;
629 *unixTimep = mktime(<);
630 _timezone = save_timezone;
633 void smb_UnixTimeFromLargeSearchTime(long *unixTimep, FILETIME *largeTimep)
635 /* unixTime: seconds since 1/1/1970 00:00:00 GMT */
636 /* FILETIME: 100ns intervals since 1/1/1601 00:00:00 GMT? */
637 LARGE_INTEGER *ft = (LARGE_INTEGER *) largeTimep;
641 /* set to number of 100ns intervals betw 1/1/1601 and 1/1/1970 */
642 a = ConvertLongToLargeInteger(((EPOCH_YEAR-1601) * 365 + leap_years) * 24 * 60);
643 a = LargeIntegerMultiplyByLong(a, 60);
644 a = LargeIntegerMultiplyByLong(a, 10000000);
646 /* subtract it from ft */
647 a = LargeIntegerSubtract(*ft, a);
649 /* divide down to seconds */
650 *unixTimep = LargeIntegerDivideByLong(a, 10000000);
654 void smb_SearchTimeFromUnixTime(long *dosTimep, long unixTime)
661 ltp = localtime((time_t*) &unixTime);
663 /* if we fail, make up something */
666 localJunk.tm_year = 89 - 20;
667 localJunk.tm_mon = 4;
668 localJunk.tm_mday = 12;
669 localJunk.tm_hour = 0;
670 localJunk.tm_min = 0;
671 localJunk.tm_sec = 0;
674 dosDate = ((ltp->tm_year-80)<<9) | ((ltp->tm_mon+1) << 5) | (ltp->tm_mday);
675 dosTime = (ltp->tm_hour<<11) | (ltp->tm_min << 5) | (ltp->tm_sec / 2);
676 *dosTimep = (dosDate<<16) | dosTime;
679 void smb_UnixTimeFromSearchTime(long *unixTimep, long searchTime)
681 unsigned short dosDate;
682 unsigned short dosTime;
685 dosDate = searchTime & 0xffff;
686 dosTime = (searchTime >> 16) & 0xffff;
688 localTm.tm_year = 80 + ((dosDate>>9) & 0x3f);
689 localTm.tm_mon = ((dosDate >> 5) & 0xf) - 1; /* January is 0 in localTm */
690 localTm.tm_mday = (dosDate) & 0x1f;
691 localTm.tm_hour = (dosTime>>11) & 0x1f;
692 localTm.tm_min = (dosTime >> 5) & 0x3f;
693 localTm.tm_sec = (dosTime & 0x1f) * 2;
694 localTm.tm_isdst = -1; /* compute whether DST in effect */
696 *unixTimep = mktime(&localTm);
699 void smb_DosUTimeFromUnixTime(long *dosUTimep, long unixTime)
701 *dosUTimep = unixTime - smb_localZero;
704 void smb_UnixTimeFromDosUTime(long *unixTimep, long dosTime)
707 *unixTimep = dosTime + smb_localZero;
709 /* dosTime seems to be already adjusted for GMT */
710 *unixTimep = dosTime;
714 smb_vc_t *smb_FindVC(unsigned short lsn, int flags, int lana)
718 lock_ObtainWrite(&smb_rctLock);
719 for(vcp = smb_allVCsp; vcp; vcp=vcp->nextp) {
720 if (lsn == vcp->lsn && lana == vcp->lana) {
725 if (!vcp && (flags & SMB_FLAG_CREATE)) {
726 vcp = malloc(sizeof(*vcp));
727 memset(vcp, 0, sizeof(*vcp));
731 vcp->uidCounter = 1; /* UID 0 is reserved for blank user */
732 vcp->nextp = smb_allVCsp;
734 lock_InitializeMutex(&vcp->mx, "vc_t mutex");
738 lock_ReleaseWrite(&smb_rctLock);
742 int smb_IsStarMask(char *maskp)
747 for(i=0; i<11; i++) {
749 if (tc == '?' || tc == '*' || tc == '>') return 1;
754 void smb_ReleaseVC(smb_vc_t *vcp)
756 lock_ObtainWrite(&smb_rctLock);
757 osi_assert(vcp->refCount-- > 0);
758 lock_ReleaseWrite(&smb_rctLock);
761 void smb_HoldVC(smb_vc_t *vcp)
763 lock_ObtainWrite(&smb_rctLock);
765 lock_ReleaseWrite(&smb_rctLock);
768 smb_tid_t *smb_FindTID(smb_vc_t *vcp, unsigned short tid, int flags)
772 lock_ObtainWrite(&smb_rctLock);
773 for(tidp = vcp->tidsp; tidp; tidp = tidp->nextp) {
774 if (tid == tidp->tid) {
779 if (!tidp && (flags & SMB_FLAG_CREATE)) {
780 tidp = malloc(sizeof(*tidp));
781 memset(tidp, 0, sizeof(*tidp));
782 tidp->nextp = vcp->tidsp;
786 lock_InitializeMutex(&tidp->mx, "tid_t mutex");
789 lock_ReleaseWrite(&smb_rctLock);
793 void smb_ReleaseTID(smb_tid_t *tidp)
800 lock_ObtainWrite(&smb_rctLock);
801 osi_assert(tidp->refCount-- > 0);
802 if (tidp->refCount == 0 && (tidp->flags & SMB_TIDFLAG_DELETE)) {
803 ltpp = &tidp->vcp->tidsp;
804 for(tp = *ltpp; tp; ltpp = &tp->nextp, tp = *ltpp) {
805 if (tp == tidp) break;
807 osi_assert(tp != NULL);
809 lock_FinalizeMutex(&tidp->mx);
810 userp = tidp->userp; /* remember to drop ref later */
812 lock_ReleaseWrite(&smb_rctLock);
814 cm_ReleaseUser(userp);
818 smb_user_t *smb_FindUID(smb_vc_t *vcp, unsigned short uid, int flags)
820 smb_user_t *uidp = NULL;
822 lock_ObtainWrite(&smb_rctLock);
823 for(uidp = vcp->usersp; uidp; uidp = uidp->nextp) {
824 if (uid == uidp->userID) {
826 osi_LogEvent("AFS smb_FindUID (Find by UID)",NULL," VCP[%x] found-uid[%d] name[%s]",(int)vcp,uidp->userID,(uidp->unp) ? uidp->unp->name : "");
830 if (!uidp && (flags & SMB_FLAG_CREATE)) {
831 uidp = malloc(sizeof(*uidp));
832 memset(uidp, 0, sizeof(*uidp));
833 uidp->nextp = vcp->usersp;
837 lock_InitializeMutex(&uidp->mx, "uid_t mutex");
839 osi_LogEvent("AFS smb_FindUID (Find by UID)",NULL,"VCP[%x] new-uid[%d] name[%s]",(int)vcp,uidp->userID,(uidp->unp ? uidp->unp->name : ""));
841 lock_ReleaseWrite(&smb_rctLock);
845 smb_username_t *smb_FindUserByName(char *usern, char *machine, int flags)
847 smb_username_t *unp= NULL;
849 lock_ObtainWrite(&smb_rctLock);
850 for(unp = usernamesp; unp; unp = unp->nextp) {
851 if (stricmp(unp->name, usern) == 0 &&
852 stricmp(unp->machine, machine) == 0) {
857 if (!unp && (flags & SMB_FLAG_CREATE)) {
858 unp = malloc(sizeof(*unp));
859 memset(unp, 0, sizeof(*unp));
861 unp->nextp = usernamesp;
862 unp->name = strdup(usern);
863 unp->machine = strdup(machine);
865 lock_InitializeMutex(&unp->mx, "username_t mutex");
867 lock_ReleaseWrite(&smb_rctLock);
871 smb_user_t *smb_FindUserByNameThisSession(smb_vc_t *vcp, char *usern)
873 smb_user_t *uidp= NULL;
875 lock_ObtainWrite(&smb_rctLock);
876 for(uidp = vcp->usersp; uidp; uidp = uidp->nextp) {
879 if (stricmp(uidp->unp->name, usern) == 0) {
881 osi_LogEvent("AFS smb_FindUserByNameThisSession",NULL,"VCP[%x] uid[%d] match-name[%s]",(int)vcp,uidp->userID,usern);
886 lock_ReleaseWrite(&smb_rctLock);
889 void smb_ReleaseUID(smb_user_t *uidp)
896 lock_ObtainWrite(&smb_rctLock);
897 osi_assert(uidp->refCount-- > 0);
898 if (uidp->refCount == 0 && (uidp->flags & SMB_USERFLAG_DELETE)) {
899 lupp = &uidp->vcp->usersp;
900 for(up = *lupp; up; lupp = &up->nextp, up = *lupp) {
901 if (up == uidp) break;
903 osi_assert(up != NULL);
905 lock_FinalizeMutex(&uidp->mx);
907 userp = uidp->unp->userp; /* remember to drop ref later */
908 uidp->unp->userp = NULL;
911 lock_ReleaseWrite(&smb_rctLock);
913 cm_ReleaseUserVCRef(userp);
914 cm_ReleaseUser(userp);
918 /* retrieve a held reference to a user structure corresponding to an incoming
920 * corresponding release function is cm_ReleaseUser.
922 cm_user_t *smb_GetUser(smb_vc_t *vcp, smb_packet_t *inp)
928 smbp = (smb_t *) inp;
929 uidp = smb_FindUID(vcp, smbp->uid, 0);
930 if ((!uidp) || (!uidp->unp))
933 lock_ObtainMutex(&uidp->mx);
934 up = uidp->unp->userp;
936 lock_ReleaseMutex(&uidp->mx);
938 smb_ReleaseUID(uidp);
944 * Return a pointer to a pathname extracted from a TID structure. The
945 * TID structure is not held; assume it won't go away.
947 char *smb_GetTIDPath(smb_vc_t *vcp, unsigned short tid)
952 tidp = smb_FindTID(vcp, tid, 0);
955 tpath = tidp->pathname;
956 smb_ReleaseTID(tidp);
960 /* check to see if we have a chained fid, that is, a fid that comes from an
961 * OpenAndX message that ran earlier in this packet. In this case, the fid
962 * field in a read, for example, request, isn't set, since the value is
963 * supposed to be inherited from the openAndX call.
965 int smb_ChainFID(int fid, smb_packet_t *inp)
967 if (inp->fid == 0 || inp->inCount == 0)
973 /* are we a priv'd user? What does this mean on NT? */
974 int smb_SUser(cm_user_t *userp)
979 /* find a file ID. If pass in 0, we'll allocate on on a create operation. */
980 smb_fid_t *smb_FindFID(smb_vc_t *vcp, unsigned short fid, int flags)
985 lock_ObtainWrite(&smb_rctLock);
986 /* figure out if we need to allocate a new file ID */
989 fid = vcp->fidCounter;
994 for(fidp = vcp->fidsp; fidp; fidp = (smb_fid_t *) osi_QNext(&fidp->q)) {
995 if (fid == fidp->fid) {
1006 if (!fidp && (flags & SMB_FLAG_CREATE)) {
1007 char eventName[MAX_PATH];
1008 sprintf(eventName,"fid_t event fid=%d", fid);
1009 fidp = malloc(sizeof(*fidp));
1010 memset(fidp, 0, sizeof(*fidp));
1011 osi_QAdd((osi_queue_t **)&vcp->fidsp, &fidp->q);
1014 lock_InitializeMutex(&fidp->mx, "fid_t mutex");
1016 fidp->curr_chunk = fidp->prev_chunk = -2;
1017 fidp->raw_write_event = thrd_CreateEvent(NULL, FALSE, TRUE, eventName);
1018 if ( GetLastError() == ERROR_ALREADY_EXISTS )
1019 afsi_log("Event Object Already Exists: %s", eventName);
1021 vcp->fidCounter = fid+1;
1022 if (vcp->fidCounter == 0)
1023 vcp->fidCounter = 1;
1026 lock_ReleaseWrite(&smb_rctLock);
1030 void smb_ReleaseFID(smb_fid_t *fidp)
1034 smb_ioctl_t *ioctlp;
1040 lock_ObtainWrite(&smb_rctLock);
1041 osi_assert(fidp->refCount-- > 0);
1042 if (fidp->refCount == 0 && (fidp->flags & SMB_FID_DELETE)) {
1044 if (!(fidp->flags & SMB_FID_IOCTL))
1046 osi_QRemove((osi_queue_t **) &vcp->fidsp, &fidp->q);
1047 thrd_CloseHandle(fidp->raw_write_event);
1049 /* and see if there is ioctl stuff to free */
1050 ioctlp = fidp->ioctlp;
1052 if (ioctlp->prefix) cm_FreeSpace(ioctlp->prefix);
1053 if (ioctlp->inAllocp) free(ioctlp->inAllocp);
1054 if (ioctlp->outAllocp) free(ioctlp->outAllocp);
1060 lock_ReleaseWrite(&smb_rctLock);
1062 /* now release the scache structure */
1064 cm_ReleaseSCache(scp);
1068 * Case-insensitive search for one string in another;
1069 * used to find variable names in submount pathnames.
1071 static char *smb_stristr(char *str1, char *str2)
1075 for (cursor = str1; *cursor; cursor++)
1076 if (stricmp(cursor, str2) == 0)
1083 * Substitute a variable value for its name in a submount pathname. Variable
1084 * name has been identified by smb_stristr() and is in substr. Variable name
1085 * length (plus one) is in substr_size. Variable value is in newstr.
1087 static void smb_subst(char *str1, char *substr, unsigned int substr_size,
1092 strcpy(temp, substr + substr_size - 1);
1093 strcpy(substr, newstr);
1097 char VNUserName[] = "%USERNAME%";
1098 char VNLCUserName[] = "%LCUSERNAME%";
1099 char VNComputerName[] = "%COMPUTERNAME%";
1100 char VNLCComputerName[] = "%LCCOMPUTERNAME%";
1102 /* List available shares */
1103 int smb_ListShares()
1107 char shareBuf[4096];
1115 /*strcpy(shareNameList[num_shares], "all");
1116 strcpy(pathNameList[num_shares++], "/afs");*/
1117 fprintf(stderr, "The following shares are available:\n");
1118 fprintf(stderr, "Share Name (AFS Path)\n");
1119 fprintf(stderr, "---------------------\n");
1120 fprintf(stderr, "\\\\%s\\%-16s (%s)\n", smb_localNamep, "ALL", cm_mountRoot);
1123 code = GetWindowsDirectory(sbmtpath, sizeof(sbmtpath));
1124 if (code == 0 || code > sizeof(sbmtpath)) return -1;
1126 strcpy(sbmtpath, cm_confDir);
1128 strcat(sbmtpath, "/afsdsbmt.ini");
1129 len = GetPrivateProfileString("AFS Submounts", NULL, NULL,
1130 shareBuf, sizeof(shareBuf),
1136 this_share = shareBuf;
1140 /*strcpy(shareNameList[num_shares], this_share);*/
1141 len = GetPrivateProfileString("AFS Submounts", this_share,
1148 if (strncmp(p, cm_mountRoot, strlen(cm_mountRoot)) != 0)
1151 if (*p == '\\') *p = '/'; /* change to / */
1155 fprintf(stderr, "\\\\%s\\%-16s (%s%s)\n",
1156 smb_localNamep, this_share, (print_afs ? cm_mountRoot : "\0"),
1159 while (*this_share != 0) this_share++; /* find next NUL */
1160 this_share++; /* skip past the NUL */
1161 } while (*this_share != 0); /* stop at final NUL */
1166 /* find a shareName in the table of submounts */
1167 int smb_FindShare(smb_vc_t *vcp, smb_packet_t *inp, char *shareName,
1171 char pathName[1024];
1176 char sbmtpath[MAX_PATH];
1180 DWORD allSubmount = 1;
1182 if (strcmp(shareName, "IPC$") == 0) {
1187 /* if allSubmounts == 0, only return the //mountRoot/all share
1188 * if in fact it has been been created in the subMounts table.
1189 * This is to allow sites that want to restrict access to the
1192 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSConfigKeyName,
1193 0, KEY_QUERY_VALUE, &parmKey);
1194 if (code == ERROR_SUCCESS) {
1195 len = sizeof(allSubmount);
1196 code = RegQueryValueEx(parmKey, "AllSubmount", NULL, NULL,
1197 (BYTE *) &allSubmount, &len);
1198 if (code != ERROR_SUCCESS) {
1201 RegCloseKey (parmKey);
1204 if (allSubmount && _stricmp(shareName, "all") == 0) {
1209 /* In case, the all share is disabled we need to still be able
1210 * to handle ioctl requests
1212 if (_stricmp(shareName, "ioctl$") == 0) {
1213 *pathNamep = strdup("/.__ioctl__");
1218 strcpy(sbmtpath, "afsdsbmt.ini");
1220 strcpy(sbmtpath, cm_confDir);
1221 strcat(sbmtpath, "/afsdsbmt.ini");
1223 len = GetPrivateProfileString("AFS Submounts", shareName, "",
1224 pathName, sizeof(pathName), sbmtpath);
1225 if (len != 0 && len != sizeof(pathName) - 1) {
1226 /* We can accept either unix or PC style AFS pathnames. Convert
1227 * Unix-style to PC style here for internal use.
1230 if (strncmp(p, cm_mountRoot, strlen(cm_mountRoot)) == 0)
1231 p += strlen(cm_mountRoot); /* skip mount path */
1234 if (*q == '/') *q = '\\'; /* change to \ */
1240 if (var = smb_stristr(p, VNUserName)) {
1241 uidp = smb_FindUID(vcp, ((smb_t *)inp)->uid, 0);
1242 if (uidp && uidp->unp)
1243 smb_subst(p, var, sizeof(VNUserName),uidp->unp->name);
1245 smb_subst(p, var, sizeof(VNUserName)," ");
1247 smb_ReleaseUID(uidp);
1249 else if (var = smb_stristr(p, VNLCUserName))
1251 uidp = smb_FindUID(vcp, ((smb_t *)inp)->uid, 0);
1252 if (uidp && uidp->unp)
1253 strcpy(temp, uidp->unp->name);
1257 smb_subst(p, var, sizeof(VNLCUserName), temp);
1259 smb_ReleaseUID(uidp);
1261 else if (var = smb_stristr(p, VNComputerName))
1263 sizeTemp = sizeof(temp);
1264 GetComputerName((LPTSTR)temp, &sizeTemp);
1265 smb_subst(p, var, sizeof(VNComputerName), temp);
1267 else if (var = smb_stristr(p, VNLCComputerName))
1269 sizeTemp = sizeof(temp);
1270 GetComputerName((LPTSTR)temp, &sizeTemp);
1272 smb_subst(p, var, sizeof(VNLCComputerName), temp);
1277 *pathNamep = strdup(p);
1280 else /* create \\<netbiosName>\<cellname> */
1282 char * p = shareName;
1289 /* Get the full name for this cell */
1290 code = cm_SearchCellFile(p, temp, 0, 0);
1291 #ifdef AFS_AFSDB_ENV
1292 if (code && cm_dnsEnabled) {
1294 code = cm_SearchCellByDNS(p, temp, &ttl, 0, 0);
1297 /* construct the path */
1299 sprintf(pathName,rw ? "/.%s/" : "/%s/",temp);
1300 *pathNamep = strdup(strlwr(pathName));
1309 /* find a dir search structure by cookie value, and return it held.
1310 * Must be called with smb_globalLock held.
1312 smb_dirSearch_t *smb_FindDirSearchNL(long cookie)
1314 smb_dirSearch_t *dsp;
1316 for(dsp = smb_firstDirSearchp; dsp; dsp = (smb_dirSearch_t *) osi_QNext(&dsp->q)) {
1317 if (dsp->cookie == cookie) {
1318 if (dsp != smb_firstDirSearchp) {
1319 /* move to head of LRU queue, too, if we're not already there */
1320 if (smb_lastDirSearchp == (smb_dirSearch_t *) &dsp->q)
1321 smb_lastDirSearchp = (smb_dirSearch_t *)
1323 osi_QRemove((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1324 osi_QAdd((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1325 if (!smb_lastDirSearchp)
1326 smb_lastDirSearchp = (smb_dirSearch_t *) &dsp->q;
1335 void smb_DeleteDirSearch(smb_dirSearch_t *dsp)
1337 lock_ObtainWrite(&smb_globalLock);
1338 dsp->flags |= SMB_DIRSEARCH_DELETE;
1339 lock_ReleaseWrite(&smb_globalLock);
1340 lock_ObtainMutex(&dsp->mx);
1341 if(dsp->scp != NULL) {
1342 lock_ObtainMutex(&dsp->scp->mx);
1343 if (dsp->flags & SMB_DIRSEARCH_BULKST) {
1344 dsp->flags &= ~SMB_DIRSEARCH_BULKST;
1345 dsp->scp->flags &= ~CM_SCACHEFLAG_BULKSTATTING;
1346 dsp->scp->bulkStatProgress = hones;
1348 lock_ReleaseMutex(&dsp->scp->mx);
1350 lock_ReleaseMutex(&dsp->mx);
1353 void smb_ReleaseDirSearch(smb_dirSearch_t *dsp)
1359 lock_ObtainWrite(&smb_globalLock);
1360 osi_assert(dsp->refCount-- > 0);
1361 if (dsp->refCount == 0 && (dsp->flags & SMB_DIRSEARCH_DELETE)) {
1362 if (&dsp->q == (osi_queue_t *) smb_lastDirSearchp)
1363 smb_lastDirSearchp = (smb_dirSearch_t *) osi_QPrev(&smb_lastDirSearchp->q);
1364 osi_QRemove((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1365 lock_FinalizeMutex(&dsp->mx);
1369 lock_ReleaseWrite(&smb_globalLock);
1371 /* do this now to avoid spurious locking hierarchy creation */
1372 if (scp) cm_ReleaseSCache(scp);
1375 /* find a dir search structure by cookie value, and return it held */
1376 smb_dirSearch_t *smb_FindDirSearch(long cookie)
1378 smb_dirSearch_t *dsp;
1380 lock_ObtainWrite(&smb_globalLock);
1381 dsp = smb_FindDirSearchNL(cookie);
1382 lock_ReleaseWrite(&smb_globalLock);
1386 /* GC some dir search entries, in the address space expected by the specific protocol.
1387 * Must be called with smb_globalLock held; release the lock temporarily.
1389 #define SMB_DIRSEARCH_GCMAX 10 /* how many at once */
1390 void smb_GCDirSearches(int isV3)
1392 smb_dirSearch_t *prevp;
1393 smb_dirSearch_t *tp;
1394 smb_dirSearch_t *victimsp[SMB_DIRSEARCH_GCMAX];
1398 victimCount = 0; /* how many have we got so far */
1399 for(tp = smb_lastDirSearchp; tp; tp=prevp) {
1400 /* we'll move tp from queue, so
1403 prevp = (smb_dirSearch_t *) osi_QPrev(&tp->q);
1404 /* if no one is using this guy, and we're either in the new protocol,
1405 * or we're in the old one and this is a small enough ID to be useful
1406 * to the old protocol, GC this guy.
1408 if (tp->refCount == 0 && (isV3 || tp->cookie <= 255)) {
1409 /* hold and delete */
1410 tp->flags |= SMB_DIRSEARCH_DELETE;
1411 victimsp[victimCount++] = tp;
1415 /* don't do more than this */
1416 if (victimCount >= SMB_DIRSEARCH_GCMAX) break;
1419 /* now release them */
1420 lock_ReleaseWrite(&smb_globalLock);
1421 for(i = 0; i < victimCount; i++) {
1422 smb_ReleaseDirSearch(victimsp[i]);
1424 lock_ObtainWrite(&smb_globalLock);
1427 /* function for allocating a dir search entry. We need these to remember enough context
1428 * since we don't get passed the path from call to call during a directory search.
1430 * Returns a held dir search structure, and bumps the reference count on the vnode,
1431 * since it saves a pointer to the vnode.
1433 smb_dirSearch_t *smb_NewDirSearch(int isV3)
1435 smb_dirSearch_t *dsp;
1439 lock_ObtainWrite(&smb_globalLock);
1442 /* what's the biggest ID allowed in this version of the protocol */
1443 if (isV3) maxAllowed = 65535;
1444 else maxAllowed = 255;
1447 /* twice so we have enough tries to find guys we GC after one pass;
1448 * 10 extra is just in case I mis-counted.
1450 if (++counter > 2*maxAllowed+10) osi_panic("afsd: dir search cookie leak",
1451 __FILE__, __LINE__);
1452 if (smb_dirSearchCounter > maxAllowed) {
1453 smb_dirSearchCounter = 1;
1454 smb_GCDirSearches(isV3); /* GC some (drops global lock) */
1456 dsp = smb_FindDirSearchNL(smb_dirSearchCounter);
1458 /* don't need to watch for refcount zero and deleted, since
1459 * we haven't dropped the global lock.
1462 ++smb_dirSearchCounter;
1466 dsp = malloc(sizeof(*dsp));
1467 memset(dsp, 0, sizeof(*dsp));
1468 osi_QAdd((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1469 if (!smb_lastDirSearchp) smb_lastDirSearchp = (smb_dirSearch_t *) &dsp->q;
1470 dsp->cookie = smb_dirSearchCounter;
1471 ++smb_dirSearchCounter;
1473 lock_InitializeMutex(&dsp->mx, "cm_dirSearch_t");
1474 dsp->lastTime = osi_Time();
1477 lock_ReleaseWrite(&smb_globalLock);
1481 static smb_packet_t *GetPacket(void)
1485 unsigned int npar, seg, tb_sel;
1488 lock_ObtainWrite(&smb_globalLock);
1489 tbp = smb_packetFreeListp;
1491 smb_packetFreeListp = tbp->nextp;
1492 lock_ReleaseWrite(&smb_globalLock);
1495 tbp = calloc(65540,1);
1497 tbp = malloc(sizeof(smb_packet_t));
1499 tbp->magic = SMB_PACKETMAGIC;
1502 tbp->resumeCode = 0;
1508 tbp->ncb_length = 0;
1513 npar = SMB_PACKETSIZE >> 4; /* number of paragraphs */
1516 __dpmi_allocate_dos_memory(npar, &tb_sel); /* DOS segment */
1518 afsi_log("Cannot allocate %d paragraphs of DOS memory",
1520 osi_panic("",__FILE__,__LINE__);
1523 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X",
1528 tbp->dos_pkt = (seg * 16) + 0; /* DOS physical address */
1529 tbp->dos_pkt_sel = tb_sel;
1532 osi_assert(tbp->magic == SMB_PACKETMAGIC);
1537 smb_packet_t *smb_CopyPacket(smb_packet_t *pkt)
1541 memcpy(tbp, pkt, sizeof(smb_packet_t));
1542 tbp->wctp = tbp->data + ((unsigned int)pkt->wctp - (unsigned int)pkt->data);
1546 static NCB *GetNCB(void)
1551 unsigned int npar, seg, tb_sel;
1554 lock_ObtainWrite(&smb_globalLock);
1555 tbp = smb_ncbFreeListp;
1557 smb_ncbFreeListp = tbp->nextp;
1558 lock_ReleaseWrite(&smb_globalLock);
1561 tbp = calloc(sizeof(*tbp),1);
1563 tbp = malloc(sizeof(*tbp));
1564 npar = (sizeof(NCB)+15) >> 4; /* number of paragraphs */
1567 __dpmi_allocate_dos_memory(npar, &tb_sel); /* DOS segment */
1569 afsi_log("Cannot allocate %d paragraphs of DOS mem in GetNCB",
1571 osi_panic("",__FILE__,__LINE__);
1573 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X in GetNCB",
1578 tbp->dos_ncb = (seg * 16) + 0; /* DOS physical address */
1579 tbp->dos_ncb_sel = tb_sel;
1581 tbp->magic = SMB_NCBMAGIC;
1584 osi_assert(tbp->magic == SMB_NCBMAGIC);
1586 memset(&tbp->ncb, 0, sizeof(NCB));
1589 dos_memset(tbp->dos_ncb, 0, sizeof(NCB));
1594 void smb_FreePacket(smb_packet_t *tbp)
1596 osi_assert(tbp->magic == SMB_PACKETMAGIC);
1598 lock_ObtainWrite(&smb_globalLock);
1599 tbp->nextp = smb_packetFreeListp;
1600 smb_packetFreeListp = tbp;
1601 tbp->magic = SMB_PACKETMAGIC;
1604 tbp->resumeCode = 0;
1610 tbp->ncb_length = 0;
1612 lock_ReleaseWrite(&smb_globalLock);
1615 static void FreeNCB(NCB *bufferp)
1619 tbp = (smb_ncb_t *) bufferp;
1620 osi_assert(tbp->magic == SMB_NCBMAGIC);
1622 lock_ObtainWrite(&smb_globalLock);
1623 tbp->nextp = smb_ncbFreeListp;
1624 smb_ncbFreeListp = tbp;
1625 lock_ReleaseWrite(&smb_globalLock);
1628 /* get a ptr to the data part of a packet, and its count */
1629 unsigned char *smb_GetSMBData(smb_packet_t *smbp, int *nbytesp)
1633 unsigned char *afterParmsp;
1635 parmBytes = *smbp->wctp << 1;
1636 afterParmsp = smbp->wctp + parmBytes + 1;
1638 dataBytes = afterParmsp[0] + (afterParmsp[1]<<8);
1639 if (nbytesp) *nbytesp = dataBytes;
1641 /* don't forget to skip the data byte count, since it follows
1642 * the parameters; that's where the "2" comes from below.
1644 return (unsigned char *) (afterParmsp + 2);
1647 /* must set all the returned parameters before playing around with the
1648 * data region, since the data region is located past the end of the
1649 * variable number of parameters.
1651 void smb_SetSMBDataLength(smb_packet_t *smbp, unsigned int dsize)
1653 unsigned char *afterParmsp;
1655 afterParmsp = smbp->wctp + ((*smbp->wctp)<<1) + 1;
1657 *afterParmsp++ = dsize & 0xff;
1658 *afterParmsp = (dsize>>8) & 0xff;
1661 /* return the parm'th parameter in the smbp packet */
1662 unsigned int smb_GetSMBParm(smb_packet_t *smbp, int parm)
1665 unsigned char *parmDatap;
1667 parmCount = *smbp->wctp;
1669 if (parm >= parmCount) {
1674 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
1675 sprintf(s, "Bad SMB param %d out of %d, ncb len %d",
1676 parm, parmCount, smbp->ncb_length);
1678 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1006, NULL,
1679 1, smbp->ncb_length, ptbuf, smbp);
1680 DeregisterEventSource(h);
1684 sprintf(s, "Bad SMB param %d out of %d, ncb len %d",
1685 parm, parmCount, smbp->ncb_length);
1686 osi_Log0(smb_logp, s);
1688 osi_panic(s, __FILE__, __LINE__);
1690 parmDatap = smbp->wctp + (2*parm) + 1;
1692 return parmDatap[0] + (parmDatap[1] << 8);
1695 /* return the parm'th parameter in the smbp packet */
1696 unsigned int smb_GetSMBOffsetParm(smb_packet_t *smbp, int parm, int offset)
1699 unsigned char *parmDatap;
1701 parmCount = *smbp->wctp;
1703 if (parm * 2 + offset >= parmCount * 2) {
1708 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
1709 sprintf(s, "Bad SMB param %d offset %d out of %d, ncb len %d",
1710 parm, offset, parmCount, smbp->ncb_length);
1712 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1006, NULL,
1713 1, smbp->ncb_length, ptbuf, smbp);
1714 DeregisterEventSource(h);
1718 sprintf(s, "Bad SMB param %d offset %d out of %d, "
1720 parm, offset, parmCount, smbp->ncb_length);
1721 osi_Log0(smb_logp, s);
1724 osi_panic(s, __FILE__, __LINE__);
1726 parmDatap = smbp->wctp + (2*parm) + 1 + offset;
1728 return parmDatap[0] + (parmDatap[1] << 8);
1731 void smb_SetSMBParm(smb_packet_t *smbp, int slot, unsigned int parmValue)
1735 /* make sure we have enough slots */
1736 if (*smbp->wctp <= slot) *smbp->wctp = slot+1;
1738 parmDatap = smbp->wctp + 2*slot + 1 + smbp->oddByte;
1739 *parmDatap++ = parmValue & 0xff;
1740 *parmDatap = (parmValue>>8) & 0xff;
1743 void smb_SetSMBParmLong(smb_packet_t *smbp, int slot, unsigned int parmValue)
1747 /* make sure we have enough slots */
1748 if (*smbp->wctp <= slot) *smbp->wctp = slot+2;
1750 parmDatap = smbp->wctp + 2*slot + 1 + smbp->oddByte;
1751 *parmDatap++ = parmValue & 0xff;
1752 *parmDatap++ = (parmValue>>8) & 0xff;
1753 *parmDatap++ = (parmValue>>16) & 0xff;
1754 *parmDatap++ = (parmValue>>24) & 0xff;
1757 void smb_SetSMBParmDouble(smb_packet_t *smbp, int slot, char *parmValuep)
1762 /* make sure we have enough slots */
1763 if (*smbp->wctp <= slot) *smbp->wctp = slot+4;
1765 parmDatap = smbp->wctp + 2*slot + 1 + smbp->oddByte;
1767 *parmDatap++ = *parmValuep++;
1770 void smb_SetSMBParmByte(smb_packet_t *smbp, int slot, unsigned int parmValue)
1774 /* make sure we have enough slots */
1775 if (*smbp->wctp <= slot) {
1776 if (smbp->oddByte) {
1778 *smbp->wctp = slot+1;
1783 parmDatap = smbp->wctp + 2*slot + 1 + (1 - smbp->oddByte);
1784 *parmDatap++ = parmValue & 0xff;
1787 void smb_StripLastComponent(char *outPathp, char **lastComponentp, char *inPathp)
1791 lastSlashp = strrchr(inPathp, '\\');
1793 *lastComponentp = lastSlashp;
1796 if (inPathp == lastSlashp)
1798 *outPathp++ = *inPathp++;
1807 unsigned char *smb_ParseASCIIBlock(unsigned char *inp, char **chainpp)
1812 *chainpp = inp + strlen(inp) + 1; /* skip over null-terminated string */
1817 unsigned char *smb_ParseVblBlock(unsigned char *inp, char **chainpp, int *lengthp)
1823 tlen = inp[0] + (inp[1]<<8);
1824 inp += 2; /* skip length field */
1827 *chainpp = inp + tlen;
1836 /* format a packet as a response */
1837 void smb_FormatResponsePacket(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *op)
1842 outp = (smb_t *) op;
1844 /* zero the basic structure through the smb_wct field, and zero the data
1845 * size field, assuming that wct stays zero; otherwise, you have to
1846 * explicitly set the data size field, too.
1848 inSmbp = (smb_t *) inp;
1849 memset(outp, 0, sizeof(smb_t)+2);
1855 outp->com = inSmbp->com;
1856 outp->tid = inSmbp->tid;
1857 outp->pid = inSmbp->pid;
1858 outp->uid = inSmbp->uid;
1859 outp->mid = inSmbp->mid;
1860 outp->res[0] = inSmbp->res[0];
1861 outp->res[1] = inSmbp->res[1];
1862 op->inCom = inSmbp->com;
1864 outp->reb = 0x80; /* SERVER_RESP */
1865 outp->flg2 = 0x1; /* KNOWS_LONG_NAMES */
1867 /* copy fields in generic packet area */
1868 op->wctp = &outp->wct;
1871 /* send a (probably response) packet; vcp tells us to whom to send it.
1872 * we compute the length by looking at wct and bcc fields.
1874 void smb_SendPacket(smb_vc_t *vcp, smb_packet_t *inp)
1891 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
1894 memset((char *)ncbp, 0, sizeof(NCB));
1896 extra = 2 * (*inp->wctp); /* space used by parms, in bytes */
1897 tp = inp->wctp + 1+ extra; /* points to count of data bytes */
1898 extra += tp[0] + (tp[1]<<8);
1899 extra += ((unsigned int)inp->wctp - (unsigned int)inp->data); /* distance to last wct field */
1900 extra += 3; /* wct and length fields */
1902 ncbp->ncb_length = extra; /* bytes to send */
1903 ncbp->ncb_lsn = (unsigned char) vcp->lsn; /* vc to use */
1904 ncbp->ncb_lana_num = vcp->lana;
1905 ncbp->ncb_command = NCBSEND; /* op means send data */
1907 ncbp->ncb_buffer = (char *) inp;/* packet */
1908 code = Netbios(ncbp);
1910 ncbp->ncb_buffer = inp->dos_pkt;/* packet */
1911 ((smb_ncb_t*)ncbp)->orig_pkt = inp;
1913 /* copy header information from virtual to DOS address space */
1914 dosmemput((char*)inp, SMB_PACKETSIZE, inp->dos_pkt);
1915 code = Netbios(ncbp, dos_ncb);
1919 osi_Log1(smb_logp, "SendPacket failure code %d", code);
1925 void smb_MapNTError(long code, unsigned long *NTStatusp)
1927 unsigned long NTStatus;
1929 /* map CM_ERROR_* errors to NT 32-bit status codes */
1930 if (code == CM_ERROR_NOSUCHCELL) {
1931 NTStatus = 0xC000000FL; /* No such file */
1933 else if (code == CM_ERROR_NOSUCHVOLUME) {
1934 NTStatus = 0xC000000FL; /* No such file */
1936 else if (code == CM_ERROR_TIMEDOUT) {
1937 NTStatus = 0xC00000CFL; /* Sharing Paused */
1939 else if (code == CM_ERROR_RETRY) {
1940 NTStatus = 0xC000022DL; /* Retry */
1942 else if (code == CM_ERROR_NOACCESS) {
1943 NTStatus = 0xC0000022L; /* Access denied */
1945 else if (code == CM_ERROR_READONLY) {
1946 NTStatus = 0xC00000A2L; /* Write protected */
1948 else if (code == CM_ERROR_NOSUCHFILE) {
1949 NTStatus = 0xC000000FL; /* No such file */
1951 else if (code == CM_ERROR_NOSUCHPATH) {
1952 NTStatus = 0xC000003AL; /* Object path not found */
1954 else if (code == CM_ERROR_TOOBIG) {
1955 NTStatus = 0xC000007BL; /* Invalid image format */
1957 else if (code == CM_ERROR_INVAL) {
1958 NTStatus = 0xC000000DL; /* Invalid parameter */
1960 else if (code == CM_ERROR_BADFD) {
1961 NTStatus = 0xC0000008L; /* Invalid handle */
1963 else if (code == CM_ERROR_BADFDOP) {
1964 NTStatus = 0xC0000022L; /* Access denied */
1966 else if (code == CM_ERROR_EXISTS) {
1967 NTStatus = 0xC0000035L; /* Object name collision */
1969 else if (code == CM_ERROR_NOTEMPTY) {
1970 NTStatus = 0xC0000101L; /* Directory not empty */
1972 else if (code == CM_ERROR_CROSSDEVLINK) {
1973 NTStatus = 0xC00000D4L; /* Not same device */
1975 else if (code == CM_ERROR_NOTDIR) {
1976 NTStatus = 0xC0000103L; /* Not a directory */
1978 else if (code == CM_ERROR_ISDIR) {
1979 NTStatus = 0xC00000BAL; /* File is a directory */
1981 else if (code == CM_ERROR_BADOP) {
1982 NTStatus = 0xC09820FFL; /* SMB no support */
1984 else if (code == CM_ERROR_BADSHARENAME) {
1985 NTStatus = 0xC00000CCL; /* Bad network name */
1987 else if (code == CM_ERROR_NOIPC) {
1989 NTStatus = 0xC0000022L; /* Access Denied */
1991 NTStatus = 0xC000013DL; /* Remote Resources */
1994 else if (code == CM_ERROR_CLOCKSKEW) {
1995 NTStatus = 0xC0000133L; /* Time difference at DC */
1997 else if (code == CM_ERROR_BADTID) {
1998 NTStatus = 0xC0982005L; /* SMB bad TID */
2000 else if (code == CM_ERROR_USESTD) {
2001 NTStatus = 0xC09820FBL; /* SMB use standard */
2003 else if (code == CM_ERROR_QUOTA) {
2004 NTStatus = 0xC0000044L; /* Quota exceeded */
2006 else if (code == CM_ERROR_SPACE) {
2007 NTStatus = 0xC000007FL; /* Disk full */
2009 else if (code == CM_ERROR_ATSYS) {
2010 NTStatus = 0xC0000033L; /* Object name invalid */
2012 else if (code == CM_ERROR_BADNTFILENAME) {
2013 NTStatus = 0xC0000033L; /* Object name invalid */
2015 else if (code == CM_ERROR_WOULDBLOCK) {
2016 NTStatus = 0xC0000055L; /* Lock not granted */
2018 else if (code == CM_ERROR_PARTIALWRITE) {
2019 NTStatus = 0xC000007FL; /* Disk full */
2021 else if (code == CM_ERROR_BUFFERTOOSMALL) {
2022 NTStatus = 0xC0000023L; /* Buffer too small */
2025 NTStatus = 0xC0982001L; /* SMB non-specific error */
2028 *NTStatusp = NTStatus;
2029 osi_Log2(smb_logp, "SMB SEND code %x as NT %x", code, NTStatus);
2032 void smb_MapCoreError(long code, smb_vc_t *vcp, unsigned short *scodep,
2033 unsigned char *classp)
2035 unsigned char class;
2036 unsigned short error;
2038 /* map CM_ERROR_* errors to SMB errors */
2039 if (code == CM_ERROR_NOSUCHCELL) {
2041 error = 3; /* bad path */
2043 else if (code == CM_ERROR_NOSUCHVOLUME) {
2045 error = 3; /* bad path */
2047 else if (code == CM_ERROR_TIMEDOUT) {
2049 error = 81; /* server is paused */
2051 else if (code == CM_ERROR_RETRY) {
2052 class = 2; /* shouldn't happen */
2055 else if (code == CM_ERROR_NOACCESS) {
2057 error = 4; /* bad access */
2059 else if (code == CM_ERROR_READONLY) {
2061 error = 19; /* read only */
2063 else if (code == CM_ERROR_NOSUCHFILE) {
2065 error = 2; /* ENOENT! */
2067 else if (code == CM_ERROR_NOSUCHPATH) {
2069 error = 3; /* Bad path */
2071 else if (code == CM_ERROR_TOOBIG) {
2073 error = 11; /* bad format */
2075 else if (code == CM_ERROR_INVAL) {
2076 class = 2; /* server non-specific error code */
2079 else if (code == CM_ERROR_BADFD) {
2081 error = 6; /* invalid file handle */
2083 else if (code == CM_ERROR_BADFDOP) {
2084 class = 1; /* invalid op on FD */
2087 else if (code == CM_ERROR_EXISTS) {
2089 error = 80; /* file already exists */
2091 else if (code == CM_ERROR_NOTEMPTY) {
2093 error = 5; /* delete directory not empty */
2095 else if (code == CM_ERROR_CROSSDEVLINK) {
2097 error = 17; /* EXDEV */
2099 else if (code == CM_ERROR_NOTDIR) {
2100 class = 1; /* bad path */
2103 else if (code == CM_ERROR_ISDIR) {
2104 class = 1; /* access denied; DOS doesn't have a good match */
2107 else if (code == CM_ERROR_BADOP) {
2111 else if (code == CM_ERROR_BADSHARENAME) {
2115 else if (code == CM_ERROR_NOIPC) {
2117 error = 4; /* bad access */
2119 else if (code == CM_ERROR_CLOCKSKEW) {
2120 class = 1; /* invalid function */
2123 else if (code == CM_ERROR_BADTID) {
2127 else if (code == CM_ERROR_USESTD) {
2131 else if (code == CM_ERROR_REMOTECONN) {
2135 else if (code == CM_ERROR_QUOTA) {
2136 if (vcp->flags & SMB_VCFLAG_USEV3) {
2138 error = 39; /* disk full */
2142 error = 5; /* access denied */
2145 else if (code == CM_ERROR_SPACE) {
2146 if (vcp->flags & SMB_VCFLAG_USEV3) {
2148 error = 39; /* disk full */
2152 error = 5; /* access denied */
2155 else if (code == CM_ERROR_PARTIALWRITE) {
2157 error = 39; /* disk full */
2159 else if (code == CM_ERROR_ATSYS) {
2161 error = 2; /* ENOENT */
2163 else if (code == CM_ERROR_WOULDBLOCK) {
2165 error = 33; /* lock conflict */
2167 else if (code == CM_ERROR_NOFILES) {
2169 error = 18; /* no files in search */
2171 else if (code == CM_ERROR_RENAME_IDENTICAL) {
2173 error = 183; /* Samba uses this */
2182 osi_Log3(smb_logp, "SMB SEND code %x as SMB %d: %d", code, class, error);
2185 long smb_SendCoreBadOp(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2187 return CM_ERROR_BADOP;
2190 long smb_ReceiveCoreEcho(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2192 unsigned short EchoCount, i;
2193 char *data, *outdata;
2196 EchoCount = (unsigned short) smb_GetSMBParm(inp, 0);
2198 for (i=1; i<=EchoCount; i++) {
2199 data = smb_GetSMBData(inp, &dataSize);
2200 smb_SetSMBParm(outp, 0, i);
2201 smb_SetSMBDataLength(outp, dataSize);
2202 outdata = smb_GetSMBData(outp, NULL);
2203 memcpy(outdata, data, dataSize);
2204 smb_SendPacket(vcp, outp);
2210 long smb_ReceiveCoreReadRaw(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2213 long count, minCount, finalCount;
2217 cm_user_t *userp = NULL;
2221 char *rawBuf = NULL;
2223 dos_ptr rawBuf = NULL;
2230 fd = smb_GetSMBParm(inp, 0);
2231 count = smb_GetSMBParm(inp, 3);
2232 minCount = smb_GetSMBParm(inp, 4);
2233 offset.HighPart = 0; /* too bad */
2234 offset.LowPart = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
2236 osi_Log3(smb_logp, "smb_ReceieveCoreReadRaw fd %d, off 0x%x, size 0x%x",
2237 fd, offset.LowPart, count);
2239 fidp = smb_FindFID(vcp, fd, 0);
2243 lock_ObtainMutex(&smb_RawBufLock);
2245 /* Get a raw buf, from head of list */
2246 rawBuf = smb_RawBufs;
2248 smb_RawBufs = *(char **)smb_RawBufs;
2250 smb_RawBufs = _farpeekl(_dos_ds, smb_RawBufs);
2253 lock_ReleaseMutex(&smb_RawBufLock);
2257 if (fidp->flags & SMB_FID_IOCTL)
2260 rc = smb_IoctlReadRaw(fidp, vcp, inp, outp);
2262 rc = smb_IoctlReadRaw(fidp, vcp, inp, outp, rawBuf);
2265 /* Give back raw buffer */
2266 lock_ObtainMutex(&smb_RawBufLock);
2268 *((char **) rawBuf) = smb_RawBufs;
2270 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
2273 smb_RawBufs = rawBuf;
2274 lock_ReleaseMutex(&smb_RawBufLock);
2277 smb_ReleaseFID(fidp);
2281 userp = smb_GetUser(vcp, inp);
2284 code = smb_ReadData(fidp, &offset, count, rawBuf, userp, &finalCount);
2286 /* have to give ReadData flag so it will treat buffer as DOS mem. */
2287 code = smb_ReadData(fidp, &offset, count, (unsigned char *)rawBuf,
2288 userp, &finalCount, TRUE /* rawFlag */);
2295 cm_ReleaseUser(userp);
2298 smb_ReleaseFID(fidp);
2303 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
2305 memset((char *)ncbp, 0, sizeof(NCB));
2307 ncbp->ncb_length = (unsigned short) finalCount;
2308 ncbp->ncb_lsn = (unsigned char) vcp->lsn;
2309 ncbp->ncb_lana_num = vcp->lana;
2310 ncbp->ncb_command = NCBSEND;
2311 ncbp->ncb_buffer = rawBuf;
2314 code = Netbios(ncbp);
2316 code = Netbios(ncbp, dos_ncb);
2319 osi_Log1(smb_logp, "ReadRaw send failure code %d", code);
2322 /* Give back raw buffer */
2323 lock_ObtainMutex(&smb_RawBufLock);
2325 *((char **) rawBuf) = smb_RawBufs;
2327 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
2330 smb_RawBufs = rawBuf;
2331 lock_ReleaseMutex(&smb_RawBufLock);
2337 long smb_ReceiveCoreLockRecord(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2342 long smb_ReceiveCoreUnlockRecord(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2347 long smb_ReceiveNegotiate(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2353 int protoIndex; /* index we're using */
2358 char protocol_array[10][1024]; /* protocol signature of the client */
2361 osi_Log1(smb_logp, "SMB receive negotiate; %d + 1 ongoing ops",
2365 DWORD now = GetCurrentTime();
2366 if (now - last_msg_time >= 30000
2367 && now - last_msg_time <= 90000) {
2369 "Setting dead_vcp %x", active_vcp);
2370 dead_vcp = active_vcp;
2371 dead_vcp->flags |= SMB_VCFLAG_ALREADYDEAD;
2376 inp->flags |= SMB_PACKETFLAG_PROFILE_UPDATE_OK;
2378 namep = smb_GetSMBData(inp, &dbytes);
2381 coreProtoIndex = -1; /* not found */
2384 while(namex < dbytes) {
2385 osi_Log1(smb_logp, "Protocol %s",
2386 osi_LogSaveString(smb_logp, namep+1));
2387 strcpy(protocol_array[tcounter], namep+1);
2389 /* namep points at the first protocol, or really, a 0x02
2390 * byte preceding the null-terminated ASCII name.
2392 if (strcmp("PC NETWORK PROGRAM 1.0", namep+1) == 0) {
2393 coreProtoIndex = tcounter;
2395 else if (smb_useV3 && strcmp("LM1.2X002", namep+1) == 0) {
2396 v3ProtoIndex = tcounter;
2398 else if (smb_useV3 && strcmp("NT LM 0.12", namep+1) == 0) {
2399 NTProtoIndex = tcounter;
2402 /* compute size of protocol entry */
2403 entryLength = strlen(namep+1);
2404 entryLength += 2; /* 0x02 bytes and null termination */
2406 /* advance over this protocol entry */
2407 namex += entryLength;
2408 namep += entryLength;
2409 tcounter++; /* which proto entry we're looking at */
2411 #ifndef NOMOREFILESFIX
2413 * NOTE: We can determine what OS (NT4.0, W2K, W9X, etc)
2414 * the client is running by reading the protocol signature.
2415 * ie. the order in which it sends us the protocol list.
2417 * Special handling for Windows 2000 clients (defect 11765 )
2418 * <asanka:11Jun03> Proto signature is the same for Win XP. </>
2420 if (tcounter == 6) {
2422 smb_t *ip = (smb_t *) inp;
2423 smb_t *op = (smb_t *) outp;
2425 if ((strcmp("PC NETWORK PROGRAM 1.0", protocol_array[0]) == 0) &&
2426 (strcmp("LANMAN1.0", protocol_array[1]) == 0) &&
2427 (strcmp("Windows for Workgroups 3.1a", protocol_array[2]) == 0) &&
2428 (strcmp("LM1.2X002", protocol_array[3]) == 0) &&
2429 (strcmp("LANMAN2.1", protocol_array[4]) == 0) &&
2430 (strcmp("NT LM 0.12", protocol_array[5]) == 0)) {
2431 isWindows2000 = TRUE;
2432 osi_Log0(smb_logp, "Looks like a Windows 2000 client");
2434 * HACK: for now - just negotiate a lower protocol till we
2435 * figure out which flag/flag2 or some other field
2436 * (capabilities maybe?) to set in order for this to work
2437 * correctly with Windows 2000 clients (defect 11765)
2440 /* Things to try (after looking at tcpdump output could be
2441 * setting flags and flags2 to 0x98 and 0xc853 like this
2442 * op->reb = 0x98; op->flg2 = 0xc853;
2443 * osi_Log2(smb_logp, "Flags:0x%x Flags2:0x%x", ip->reb, ip->flg2);
2447 #endif /* NOMOREFILESFIX */
2449 if (NTProtoIndex != -1) {
2450 protoIndex = NTProtoIndex;
2451 vcp->flags |= (SMB_VCFLAG_USENT | SMB_VCFLAG_USEV3);
2453 else if (v3ProtoIndex != -1) {
2454 protoIndex = v3ProtoIndex;
2455 vcp->flags |= SMB_VCFLAG_USEV3;
2457 else if (coreProtoIndex != -1) {
2458 protoIndex = coreProtoIndex;
2459 vcp->flags |= SMB_VCFLAG_USECORE;
2461 else protoIndex = -1;
2463 if (protoIndex == -1)
2464 return CM_ERROR_INVAL;
2465 else if (NTProtoIndex != -1) {
2466 smb_SetSMBParm(outp, 0, protoIndex);
2467 smb_SetSMBParmByte(outp, 1, 0); /* share level security, no passwd encrypt */
2468 smb_SetSMBParm(outp, 1, smb_maxMpxRequests); /* max multiplexed requests */
2469 smb_SetSMBParm(outp, 2, smb_maxVCPerServer); /* max VCs per consumer/server connection */
2470 smb_SetSMBParmLong(outp, 3, SMB_PACKETSIZE); /* xmit buffer size */
2471 smb_SetSMBParmLong(outp, 5, 65536); /* raw buffer size */
2472 smb_SetSMBParm(outp, 7, 1); /* next 2: session key */
2473 smb_SetSMBParm(outp, 8, 1);
2475 * Tried changing the capabilities to support for W2K - defect 117695
2476 * Maybe something else needs to be changed here?
2480 smb_SetSMBParmLong(outp, 9, 0x43fd);
2482 smb_SetSMBParmLong(outp, 9, 0x251);
2485 * 32-bit error codes *
2489 smb_SetSMBParmLong(outp, 9, 0x251);
2490 smb_SetSMBParmLong(outp, 11, 0);/* XXX server time: do we need? */
2491 smb_SetSMBParmLong(outp, 13, 0);/* XXX server date: do we need? */
2492 smb_SetSMBParm(outp, 15, 0); /* XXX server tzone: do we need? */
2493 smb_SetSMBParmByte(outp, 16, 0);/* Encryption key length */
2494 smb_SetSMBDataLength(outp, 0); /* perhaps should specify 8 bytes anyway */
2496 else if (v3ProtoIndex != -1) {
2497 smb_SetSMBParm(outp, 0, protoIndex);
2498 smb_SetSMBParm(outp, 1, 0); /* share level security, no passwd encrypt */
2499 smb_SetSMBParm(outp, 2, SMB_PACKETSIZE);
2500 smb_SetSMBParm(outp, 3, smb_maxMpxRequests); /* max multiplexed requests */
2501 smb_SetSMBParm(outp, 4, smb_maxVCPerServer); /* max VCs per consumer/server connection */
2502 smb_SetSMBParm(outp, 5, 0); /* no support of block mode for read or write */
2503 smb_SetSMBParm(outp, 6, 1); /* next 2: session key */
2504 smb_SetSMBParm(outp, 7, 1);
2505 smb_SetSMBParm(outp, 8, 0); /* XXX server time: do we need? */
2506 smb_SetSMBParm(outp, 9, 0); /* XXX server date: do we need? */
2507 smb_SetSMBParm(outp, 10, 0); /* XXX server tzone: do we need? */
2508 smb_SetSMBParm(outp, 11, 0); /* resvd */
2509 smb_SetSMBParm(outp, 12, 0); /* resvd */
2510 smb_SetSMBDataLength(outp, 0); /* perhaps should specify 8 bytes anyway */
2512 else if (coreProtoIndex != -1) {
2513 smb_SetSMBParm(outp, 0, protoIndex);
2514 smb_SetSMBDataLength(outp, 0);
2519 void smb_Daemon(void *parmp)
2526 if ((count % 360) == 0) /* every hour */
2527 smb_CalculateNowTZ();
2528 /* XXX GC dir search entries */
2532 void smb_WaitingLocksDaemon()
2534 smb_waitingLock_t *wL, *nwL;
2537 smb_packet_t *inp, *outp;
2542 lock_ObtainWrite(&smb_globalLock);
2543 nwL = smb_allWaitingLocks;
2545 osi_SleepW((long)&smb_allWaitingLocks, &smb_globalLock);
2554 lock_ObtainWrite(&smb_globalLock);
2556 nwL = (smb_waitingLock_t *) osi_QNext(&wL->q);
2557 lock_ReleaseWrite(&smb_globalLock);
2558 code = cm_RetryLock((cm_file_lock_t *) wL->lockp,
2559 wL->vcp->flags & SMB_VCFLAG_ALREADYDEAD);
2560 if (code == CM_ERROR_WOULDBLOCK) {
2562 if (wL->timeRemaining != 0xffffffff
2563 && (wL->timeRemaining -= 1000) < 0)
2572 ncbp->ncb_length = inp->ncb_length;
2573 inp->spacep = cm_GetSpace();
2575 /* Remove waitingLock from list */
2576 lock_ObtainWrite(&smb_globalLock);
2577 osi_QRemove((osi_queue_t **)&smb_allWaitingLocks,
2579 lock_ReleaseWrite(&smb_globalLock);
2581 /* Resume packet processing */
2583 smb_SetSMBDataLength(outp, 0);
2584 outp->flags |= SMB_PACKETFLAG_SUSPENDED;
2585 outp->resumeCode = code;
2587 smb_DispatchPacket(vcp, inp, outp, ncbp, NULL);
2590 cm_FreeSpace(inp->spacep);
2591 smb_FreePacket(inp);
2592 smb_FreePacket(outp);
2600 long smb_ReceiveCoreGetDiskAttributes(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2602 osi_Log0(smb_logp, "SMB receive get disk attributes");
2604 smb_SetSMBParm(outp, 0, 32000);
2605 smb_SetSMBParm(outp, 1, 64);
2606 smb_SetSMBParm(outp, 2, 1024);
2607 smb_SetSMBParm(outp, 3, 30000);
2608 smb_SetSMBParm(outp, 4, 0);
2609 smb_SetSMBDataLength(outp, 0);
2613 long smb_ReceiveCoreTreeConnect(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *rsp)
2616 unsigned short newTid;
2617 char shareName[256];
2625 osi_Log0(smb_logp, "SMB receive tree connect");
2627 /* parse input parameters */
2628 tp = smb_GetSMBData(inp, NULL);
2629 pathp = smb_ParseASCIIBlock(tp, &tp);
2630 passwordp = smb_ParseASCIIBlock(tp, &tp);
2631 tp = strrchr(pathp, '\\');
2633 return CM_ERROR_BADSMB;
2634 strcpy(shareName, tp+1);
2636 userp = smb_GetUser(vcp, inp);
2638 lock_ObtainMutex(&vcp->mx);
2639 newTid = vcp->tidCounter++;
2640 lock_ReleaseMutex(&vcp->mx);
2642 tidp = smb_FindTID(vcp, newTid, SMB_FLAG_CREATE);
2643 shareFound = smb_FindShare(vcp, inp, shareName, &sharePath);
2645 smb_ReleaseTID(tidp);
2646 return CM_ERROR_BADSHARENAME;
2648 lock_ObtainMutex(&tidp->mx);
2649 tidp->userp = userp;
2650 tidp->pathname = sharePath;
2651 lock_ReleaseMutex(&tidp->mx);
2652 smb_ReleaseTID(tidp);
2654 smb_SetSMBParm(rsp, 0, SMB_PACKETSIZE);
2655 smb_SetSMBParm(rsp, 1, newTid);
2656 smb_SetSMBDataLength(rsp, 0);
2658 osi_Log1(smb_logp, "SMB tree connect created ID %d", newTid);
2662 unsigned char *smb_ParseDataBlock(unsigned char *inp, char **chainpp, int *lengthp)
2666 if (*inp++ != 0x1) return NULL;
2667 tlen = inp[0] + (inp[1]<<8);
2668 inp += 2; /* skip length field */
2671 *chainpp = inp + tlen;
2674 if (lengthp) *lengthp = tlen;
2679 /* set maskp to the mask part of the incoming path.
2680 * Mask is 11 bytes long (8.3 with the dot elided).
2681 * Returns true if succeeds with a valid name, otherwise it does
2682 * its best, but returns false.
2684 int smb_Get8Dot3MaskFromPath(unsigned char *maskp, unsigned char *pathp)
2692 /* starts off valid */
2695 /* mask starts out all blanks */
2696 memset(maskp, ' ', 11);
2698 /* find last backslash, or use whole thing if there is none */
2699 tp = strrchr(pathp, '\\');
2700 if (!tp) tp = pathp;
2701 else tp++; /* skip slash */
2705 /* names starting with a dot are illegal */
2706 if (*tp == '.') valid8Dot3 = 0;
2710 if (tc == 0) return valid8Dot3;
2711 if (tc == '.' || tc == '"') break;
2712 if (i < 8) *up++ = tc;
2713 else valid8Dot3 = 0;
2716 /* if we get here, tp point after the dot */
2717 up = maskp+8; /* ext goes here */
2724 if (tc == '.' || tc == '"')
2727 /* copy extension if not too long */
2737 int smb_Match8Dot3Mask(char *unixNamep, char *maskp)
2747 /* XXX redo this, calling smb_V3MatchMask with a converted mask */
2749 valid = smb_Get8Dot3MaskFromPath(umask, unixNamep);
2753 /* otherwise, we have a valid 8.3 name; see if we have a match,
2754 * treating '?' as a wildcard in maskp (but not in the file name).
2756 tp1 = umask; /* real name, in mask format */
2757 tp2 = maskp; /* mask, in mask format */
2758 for(i=0; i<11; i++) {
2759 tc1 = *tp1++; /* char from real name */
2760 tc2 = *tp2++; /* char from mask */
2761 tc1 = (char) cm_foldUpper[(unsigned char)tc1];
2762 tc2 = (char) cm_foldUpper[(unsigned char)tc2];
2765 if (tc2 == '?' && tc1 != ' ')
2772 /* we got a match */
2776 char *smb_FindMask(char *pathp)
2780 tp = strrchr(pathp, '\\'); /* find last slash */
2783 return tp+1; /* skip the slash */
2785 return pathp; /* no slash, return the entire path */
2788 long smb_ReceiveCoreSearchVolume(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2790 unsigned char *pathp;
2792 unsigned char mask[11];
2793 unsigned char *statBlockp;
2794 unsigned char initStatBlock[21];
2797 osi_Log0(smb_logp, "SMB receive search volume");
2799 /* pull pathname and stat block out of request */
2800 tp = smb_GetSMBData(inp, NULL);
2801 pathp = smb_ParseASCIIBlock(tp, (char **) &tp);
2802 osi_assert(pathp != NULL);
2803 statBlockp = smb_ParseVblBlock(tp, (char **) &tp, &statLen);
2804 osi_assert(statBlockp != NULL);
2806 statBlockp = initStatBlock;
2810 /* for returning to caller */
2811 smb_Get8Dot3MaskFromPath(mask, pathp);
2813 smb_SetSMBParm(outp, 0, 1); /* we're returning one entry */
2814 tp = smb_GetSMBData(outp, NULL);
2816 *tp++ = 43; /* bytes in a dir entry */
2817 *tp++ = 0; /* high byte in counter */
2819 /* now marshall the dir entry, starting with the search status */
2820 *tp++ = statBlockp[0]; /* Reserved */
2821 memcpy(tp, mask, 11); tp += 11; /* FileName */
2823 /* now pass back server use info, with 1st byte non-zero */
2825 memset(tp, 0, 4); tp += 4; /* reserved for server use */
2827 memcpy(tp, statBlockp+17, 4); tp += 4; /* reserved for consumer */
2829 *tp++ = 0x8; /* attribute: volume */
2839 /* 4 byte file size */
2845 /* finally, null-terminated 8.3 pathname, which we set to AFS */
2846 memset(tp, ' ', 13);
2849 /* set the length of the data part of the packet to 43 + 3, for the dir
2850 * entry plus the 5 and the length fields.
2852 smb_SetSMBDataLength(outp, 46);
2856 long smb_ApplyDirListPatches(smb_dirListPatch_t **dirPatchespp,
2857 cm_user_t *userp, cm_req_t *reqp)
2865 smb_dirListPatch_t *patchp;
2866 smb_dirListPatch_t *npatchp;
2868 for(patchp = *dirPatchespp; patchp; patchp =
2869 (smb_dirListPatch_t *) osi_QNext(&patchp->q)) {
2870 code = cm_GetSCache(&patchp->fid, &scp, userp, reqp);
2872 lock_ObtainMutex(&scp->mx);
2873 code = cm_SyncOp(scp, NULL, userp, reqp, 0,
2874 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2876 lock_ReleaseMutex(&scp->mx);
2877 cm_ReleaseSCache(scp);
2880 dptr = patchp->dptr;
2882 attr = smb_Attributes(scp);
2883 /* check hidden attribute (the flag is only ON when dot file hiding is on ) */
2884 if( patchp->flags & SMB_DIRLISTPATCH_DOTFILE )
2885 attr |= SMB_ATTR_HIDDEN;
2889 smb_SearchTimeFromUnixTime(&dosTime, scp->clientModTime);
2892 shortTemp = dosTime & 0xffff;
2893 *((u_short *)dptr) = shortTemp;
2896 /* and copy out date */
2897 shortTemp = (dosTime>>16) & 0xffff;
2898 *((u_short *)dptr) = shortTemp;
2901 /* copy out file length */
2902 *((u_long *)dptr) = scp->length.LowPart;
2904 lock_ReleaseMutex(&scp->mx);
2905 cm_ReleaseSCache(scp);
2908 /* now free the patches */
2909 for(patchp = *dirPatchespp; patchp; patchp = npatchp) {
2910 npatchp = (smb_dirListPatch_t *) osi_QNext(&patchp->q);
2914 /* and mark the list as empty */
2915 *dirPatchespp = NULL;
2920 long smb_ReceiveCoreSearchDir(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2929 smb_dirListPatch_t *dirListPatchesp;
2930 smb_dirListPatch_t *curPatchp;
2934 osi_hyper_t dirLength;
2935 osi_hyper_t bufferOffset;
2936 osi_hyper_t curOffset;
2938 unsigned char *inCookiep;
2939 smb_dirSearch_t *dsp;
2943 unsigned long clientCookie;
2944 cm_pageHeader_t *pageHeaderp;
2945 cm_user_t *userp = NULL;
2952 long nextEntryCookie;
2953 int numDirChunks; /* # of 32 byte dir chunks in this entry */
2954 char resByte; /* reserved byte from the cookie */
2955 char *op; /* output data ptr */
2956 char *origOp; /* original value of op */
2957 cm_space_t *spacep; /* for pathname buffer */
2968 maxCount = smb_GetSMBParm(inp, 0);
2970 dirListPatchesp = NULL;
2972 caseFold = CM_FLAG_CASEFOLD;
2974 tp = smb_GetSMBData(inp, NULL);
2975 pathp = smb_ParseASCIIBlock(tp, &tp);
2976 inCookiep = smb_ParseVblBlock(tp, &tp, &dataLength);
2978 /* bail out if request looks bad */
2979 if (!tp || !pathp) {
2980 return CM_ERROR_BADSMB;
2983 /* We can handle long names */
2984 if (vcp->flags & SMB_VCFLAG_USENT)
2985 ((smb_t *)outp)->flg2 |= 0x40; /* IS_LONG_NAME */
2987 /* make sure we got a whole search status */
2988 if (dataLength < 21) {
2989 nextCookie = 0; /* start at the beginning of the dir */
2992 attribute = smb_GetSMBParm(inp, 1);
2994 /* handle volume info in another function */
2995 if (attribute & 0x8)
2996 return smb_ReceiveCoreSearchVolume(vcp, inp, outp);
2998 osi_Log2(smb_logp, "SMB receive search dir count %d [%s]",
2999 maxCount, osi_LogSaveString(smb_logp, pathp));
3001 if (*pathp == 0) { /* null pathp, treat as root dir */
3002 if (!(attribute & SMB_ATTR_DIRECTORY)) /* exclude dirs */
3003 return CM_ERROR_NOFILES;
3007 dsp = smb_NewDirSearch(0);
3008 dsp->attribute = attribute;
3009 smb_Get8Dot3MaskFromPath(mask, pathp);
3010 memcpy(dsp->mask, mask, 11);
3012 /* track if this is likely to match a lot of entries */
3013 if (smb_IsStarMask(mask)) starPattern = 1;
3014 else starPattern = 0;
3017 /* pull the next cookie value out of the search status block */
3018 nextCookie = inCookiep[13] + (inCookiep[14]<<8) + (inCookiep[15]<<16)
3019 + (inCookiep[16]<<24);
3020 dsp = smb_FindDirSearch(inCookiep[12]);
3022 /* can't find dir search status; fatal error */
3023 return CM_ERROR_BADFD;
3025 attribute = dsp->attribute;
3026 resByte = inCookiep[0];
3028 /* copy out client cookie, in host byte order. Don't bother
3029 * interpreting it, since we're just passing it through, anyway.
3031 memcpy(&clientCookie, &inCookiep[17], 4);
3033 memcpy(mask, dsp->mask, 11);
3035 /* assume we're doing a star match if it has continued for more
3041 osi_Log3(smb_logp, "SMB dir search cookie 0x%x, connection %d, attr 0x%x",
3042 nextCookie, dsp->cookie, attribute);
3044 userp = smb_GetUser(vcp, inp);
3046 /* try to get the vnode for the path name next */
3047 lock_ObtainMutex(&dsp->mx);
3054 spacep = inp->spacep;
3055 smb_StripLastComponent(spacep->data, NULL, pathp);
3056 lock_ReleaseMutex(&dsp->mx);
3057 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3058 code = cm_NameI(cm_rootSCachep, spacep->data,
3059 caseFold | CM_FLAG_FOLLOW, userp, tidPathp, &req, &scp);
3060 lock_ObtainMutex(&dsp->mx);
3062 if (dsp->scp != 0) cm_ReleaseSCache(dsp->scp);
3064 /* we need one hold for the entry we just stored into,
3065 * and one for our own processing. When we're done with this
3066 * function, we'll drop the one for our own processing.
3067 * We held it once from the namei call, and so we do another hold
3071 lock_ObtainMutex(&scp->mx);
3072 if ((scp->flags & CM_SCACHEFLAG_BULKSTATTING) == 0
3073 && LargeIntegerGreaterOrEqualToZero(scp->bulkStatProgress)) {
3074 scp->flags |= CM_SCACHEFLAG_BULKSTATTING;
3075 dsp->flags |= SMB_DIRSEARCH_BULKST;
3077 lock_ReleaseMutex(&scp->mx);
3080 lock_ReleaseMutex(&dsp->mx);
3082 cm_ReleaseUser(userp);
3083 smb_DeleteDirSearch(dsp);
3084 smb_ReleaseDirSearch(dsp);
3088 /* reserves space for parameter; we'll adjust it again later to the
3089 * real count of the # of entries we returned once we've actually
3090 * assembled the directory listing.
3092 smb_SetSMBParm(outp, 0, 0);
3094 /* get the directory size */
3095 lock_ObtainMutex(&scp->mx);
3096 code = cm_SyncOp(scp, NULL, userp, &req, 0,
3097 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3099 lock_ReleaseMutex(&scp->mx);
3100 cm_ReleaseSCache(scp);
3101 cm_ReleaseUser(userp);
3102 smb_DeleteDirSearch(dsp);
3103 smb_ReleaseDirSearch(dsp);
3107 dirLength = scp->length;
3109 bufferOffset.LowPart = bufferOffset.HighPart = 0;
3110 curOffset.HighPart = 0;
3111 curOffset.LowPart = nextCookie;
3112 origOp = op = smb_GetSMBData(outp, NULL);
3113 /* and write out the basic header */
3114 *op++ = 5; /* variable block */
3115 op += 2; /* skip vbl block length; we'll fill it in later */
3119 /* make sure that curOffset.LowPart doesn't point to the first
3120 * 32 bytes in the 2nd through last dir page, and that it doesn't
3121 * point at the first 13 32-byte chunks in the first dir page,
3122 * since those are dir and page headers, and don't contain useful
3125 temp = curOffset.LowPart & (2048-1);
3126 if (curOffset.HighPart == 0 && curOffset.LowPart < 2048) {
3127 /* we're in the first page */
3128 if (temp < 13*32) temp = 13*32;
3131 /* we're in a later dir page */
3132 if (temp < 32) temp = 32;
3135 /* make sure the low order 5 bits are zero */
3138 /* now put temp bits back ito curOffset.LowPart */
3139 curOffset.LowPart &= ~(2048-1);
3140 curOffset.LowPart |= temp;
3142 /* check if we've returned all the names that will fit in the
3145 if (returnedNames >= maxCount)
3148 /* check if we've passed the dir's EOF */
3149 if (LargeIntegerGreaterThanOrEqualTo(curOffset, dirLength)) break;
3151 /* see if we can use the bufferp we have now; compute in which page
3152 * the current offset would be, and check whether that's the offset
3153 * of the buffer we have. If not, get the buffer.
3155 thyper.HighPart = curOffset.HighPart;
3156 thyper.LowPart = curOffset.LowPart & ~(buf_bufferSize-1);
3157 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
3160 buf_Release(bufferp);
3163 lock_ReleaseMutex(&scp->mx);
3164 lock_ObtainRead(&scp->bufCreateLock);
3165 code = buf_Get(scp, &thyper, &bufferp);
3166 lock_ReleaseRead(&scp->bufCreateLock);
3168 /* now, if we're doing a star match, do bulk fetching of all of
3169 * the status info for files in the dir.
3172 smb_ApplyDirListPatches(&dirListPatchesp, userp,
3174 if ((dsp->flags & SMB_DIRSEARCH_BULKST)
3175 && LargeIntegerGreaterThanOrEqualTo(thyper,
3176 scp->bulkStatProgress)) {
3177 /* Don't bulk stat if risking timeout */
3178 int now = GetCurrentTime();
3179 if (now - req.startTime > 5000) {
3180 scp->bulkStatProgress = thyper;
3181 scp->flags &= ~CM_SCACHEFLAG_BULKSTATTING;
3182 dsp->flags &= ~SMB_DIRSEARCH_BULKST;
3184 cm_TryBulkStat(scp, &thyper, userp, &req);
3188 lock_ObtainMutex(&scp->mx);
3191 bufferOffset = thyper;
3193 /* now get the data in the cache */
3195 code = cm_SyncOp(scp, bufferp, userp, &req,
3197 CM_SCACHESYNC_NEEDCALLBACK
3198 | CM_SCACHESYNC_READ);
3201 if (cm_HaveBuffer(scp, bufferp, 0)) break;
3203 /* otherwise, load the buffer and try again */
3204 code = cm_GetBuffer(scp, bufferp, NULL, userp,
3209 buf_Release(bufferp);
3213 } /* if (wrong buffer) ... */
3215 /* now we have the buffer containing the entry we're interested in; copy
3216 * it out if it represents a non-deleted entry.
3218 entryInDir = curOffset.LowPart & (2048-1);
3219 entryInBuffer = curOffset.LowPart & (buf_bufferSize - 1);
3221 /* page header will help tell us which entries are free. Page header
3222 * can change more often than once per buffer, since AFS 3 dir page size
3223 * may be less than (but not more than a buffer package buffer.
3225 temp = curOffset.LowPart & (buf_bufferSize - 1); /* only look intra-buffer */
3226 temp &= ~(2048 - 1); /* turn off intra-page bits */
3227 pageHeaderp = (cm_pageHeader_t *) (bufferp->datap + temp);
3229 /* now determine which entry we're looking at in the page. If it is
3230 * free (there's a free bitmap at the start of the dir), we should
3231 * skip these 32 bytes.
3233 slotInPage = (entryInDir & 0x7e0) >> 5;
3234 if (!(pageHeaderp->freeBitmap[slotInPage>>3] & (1 << (slotInPage & 0x7)))) {
3235 /* this entry is free */
3236 numDirChunks = 1; /* only skip this guy */
3240 tp = bufferp->datap + entryInBuffer;
3241 dep = (cm_dirEntry_t *) tp; /* now points to AFS3 dir entry */
3243 /* while we're here, compute the next entry's location, too,
3244 * since we'll need it when writing out the cookie into the dir
3247 * XXXX Probably should do more sanity checking.
3249 numDirChunks = cm_NameEntries(dep->name, NULL);
3251 /* compute the offset of the cookie representing the next entry */
3252 nextEntryCookie = curOffset.LowPart + (CM_DIR_CHUNKSIZE * numDirChunks);
3254 /* Compute 8.3 name if necessary */
3255 actualName = dep->name;
3256 if (dep->fid.vnode != 0 && !cm_Is8Dot3(actualName)) {
3257 cm_Gen8Dot3Name(dep, shortName, &shortNameEnd);
3258 actualName = shortName;
3261 if (dep->fid.vnode != 0 && smb_Match8Dot3Mask(actualName, mask)) {
3262 /* this is one of the entries to use: it is not deleted
3263 * and it matches the star pattern we're looking for.
3266 /* Eliminate entries that don't match requested
3269 /* no hidden files */
3270 if(smb_hideDotFiles && !(dsp->attribute & SMB_ATTR_HIDDEN) && smb_IsDotFile(actualName))
3273 if (!(dsp->attribute & SMB_ATTR_DIRECTORY)) /* no directories */
3275 /* We have already done the cm_TryBulkStat above */
3276 fid.cell = scp->fid.cell;
3277 fid.volume = scp->fid.volume;
3278 fid.vnode = ntohl(dep->fid.vnode);
3279 fid.unique = ntohl(dep->fid.unique);
3280 fileType = cm_FindFileType(&fid);
3281 osi_Log2(smb_logp, "smb_ReceiveCoreSearchDir: file %s "
3282 "has filetype %d", dep->name,
3284 if (fileType == CM_SCACHETYPE_DIRECTORY)
3289 memcpy(op, mask, 11); op += 11;
3290 *op++ = (char) dsp->cookie; /* they say it must be non-zero */
3291 *op++ = nextEntryCookie & 0xff;
3292 *op++ = (nextEntryCookie>>8) & 0xff;
3293 *op++ = (nextEntryCookie>>16) & 0xff;
3294 *op++ = (nextEntryCookie>>24) & 0xff;
3295 memcpy(op, &clientCookie, 4); op += 4;
3297 /* now we emit the attribute. This is sort of tricky,
3298 * since we need to really stat the file to find out
3299 * what type of entry we've got. Right now, we're
3300 * copying out data from a buffer, while holding the
3301 * scp locked, so it isn't really convenient to stat
3302 * something now. We'll put in a place holder now,
3303 * and make a second pass before returning this to get
3304 * the real attributes. So, we just skip the data for
3305 * now, and adjust it later. We allocate a patch
3306 * record to make it easy to find this point later.
3307 * The replay will happen at a time when it is safe to
3308 * unlock the directory.
3310 curPatchp = malloc(sizeof(*curPatchp));
3311 osi_QAdd((osi_queue_t **) &dirListPatchesp, &curPatchp->q);
3312 curPatchp->dptr = op;
3313 curPatchp->fid.cell = scp->fid.cell;
3314 curPatchp->fid.volume = scp->fid.volume;
3315 curPatchp->fid.vnode = ntohl(dep->fid.vnode);
3316 curPatchp->fid.unique = ntohl(dep->fid.unique);
3318 /* do hidden attribute here since name won't be around when applying
3322 if ( smb_hideDotFiles && smb_IsDotFile(actualName) )
3323 curPatchp->flags = SMB_DIRLISTPATCH_DOTFILE;
3325 curPatchp->flags = 0;
3327 op += 9; /* skip attr, time, date and size */
3329 /* zero out name area. The spec says to pad with
3330 * spaces, but Samba doesn't, and neither do we.
3334 /* finally, we get to copy out the name; we know that
3335 * it fits in 8.3 or the pattern wouldn't match, but it
3336 * never hurts to be sure.
3338 strncpy(op, actualName, 13);
3340 /* Uppercase if requested by client */
3341 if ((((smb_t *)inp)->flg2 & 1) == 0)
3346 /* now, adjust the # of entries copied */
3348 } /* if we're including this name */
3351 /* and adjust curOffset to be where the new cookie is */
3352 thyper.HighPart = 0;
3353 thyper.LowPart = CM_DIR_CHUNKSIZE * numDirChunks;
3354 curOffset = LargeIntegerAdd(thyper, curOffset);
3355 } /* while copying data for dir listing */
3357 /* release the mutex */
3358 lock_ReleaseMutex(&scp->mx);
3359 if (bufferp) buf_Release(bufferp);
3361 /* apply and free last set of patches; if not doing a star match, this
3362 * will be empty, but better safe (and freeing everything) than sorry.
3364 smb_ApplyDirListPatches(&dirListPatchesp, userp, &req);
3366 /* special return code for unsuccessful search */
3367 if (code == 0 && dataLength < 21 && returnedNames == 0)
3368 code = CM_ERROR_NOFILES;
3370 osi_Log2(smb_logp, "SMB search dir done, %d names, code %d",
3371 returnedNames, code);
3374 smb_DeleteDirSearch(dsp);
3375 smb_ReleaseDirSearch(dsp);
3376 cm_ReleaseSCache(scp);
3377 cm_ReleaseUser(userp);
3381 /* finalize the output buffer */
3382 smb_SetSMBParm(outp, 0, returnedNames);
3383 temp = (long) (op - origOp);
3384 smb_SetSMBDataLength(outp, temp);
3386 /* the data area is a variable block, which has a 5 (already there)
3387 * followed by the length of the # of data bytes. We now know this to
3388 * be "temp," although that includes the 3 bytes of vbl block header.
3389 * Deduct for them and fill in the length field.
3391 temp -= 3; /* deduct vbl block info */
3392 osi_assert(temp == (43 * returnedNames));
3393 origOp[1] = temp & 0xff;
3394 origOp[2] = (temp>>8) & 0xff;
3395 if (returnedNames == 0) smb_DeleteDirSearch(dsp);
3396 smb_ReleaseDirSearch(dsp);
3397 cm_ReleaseSCache(scp);
3398 cm_ReleaseUser(userp);
3402 /* verify that this is a valid path to a directory. I don't know why they
3403 * don't use the get file attributes call.
3405 long smb_ReceiveCoreCheckPath(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3409 cm_scache_t *rootScp;
3410 cm_scache_t *newScp;
3419 pathp = smb_GetSMBData(inp, NULL);
3420 pathp = smb_ParseASCIIBlock(pathp, NULL);
3421 osi_Log1(smb_logp, "SMB receive check path %s",
3422 osi_LogSaveString(smb_logp, pathp));
3425 return CM_ERROR_BADFD;
3428 rootScp = cm_rootSCachep;
3430 userp = smb_GetUser(vcp, inp);
3432 caseFold = CM_FLAG_CASEFOLD;
3434 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3435 code = cm_NameI(rootScp, pathp,
3436 caseFold | CM_FLAG_FOLLOW | CM_FLAG_CHECKPATH,
3437 userp, tidPathp, &req, &newScp);
3440 cm_ReleaseUser(userp);
3444 /* now lock the vnode with a callback; returns with newScp locked */
3445 lock_ObtainMutex(&newScp->mx);
3446 code = cm_SyncOp(newScp, NULL, userp, &req, PRSFS_LOOKUP,
3447 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
3448 if (code && code != CM_ERROR_NOACCESS) {
3449 lock_ReleaseMutex(&newScp->mx);
3450 cm_ReleaseSCache(newScp);
3451 cm_ReleaseUser(userp);
3455 attrs = smb_Attributes(newScp);
3457 if (!(attrs & 0x10))
3458 code = CM_ERROR_NOTDIR;
3460 lock_ReleaseMutex(&newScp->mx);
3462 cm_ReleaseSCache(newScp);
3463 cm_ReleaseUser(userp);
3467 long smb_ReceiveCoreSetFileAttributes(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3471 cm_scache_t *rootScp;
3472 unsigned short attribute;
3474 cm_scache_t *newScp;
3483 /* decode basic attributes we're passed */
3484 attribute = smb_GetSMBParm(inp, 0);
3485 dosTime = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
3487 pathp = smb_GetSMBData(inp, NULL);
3488 pathp = smb_ParseASCIIBlock(pathp, NULL);
3491 return CM_ERROR_BADSMB;
3494 osi_Log2(smb_logp, "SMB receive setfile attributes time %d, attr 0x%x",
3495 dosTime, attribute);
3497 rootScp = cm_rootSCachep;
3499 userp = smb_GetUser(vcp, inp);
3501 caseFold = CM_FLAG_CASEFOLD;
3503 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3504 code = cm_NameI(rootScp, pathp, caseFold | CM_FLAG_FOLLOW, userp,
3505 tidPathp, &req, &newScp);
3508 cm_ReleaseUser(userp);
3512 /* now lock the vnode with a callback; returns with newScp locked; we
3513 * need the current status to determine what the new status is, in some
3516 lock_ObtainMutex(&newScp->mx);
3517 code = cm_SyncOp(newScp, NULL, userp, &req, 0,
3518 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
3520 lock_ReleaseMutex(&newScp->mx);
3521 cm_ReleaseSCache(newScp);
3522 cm_ReleaseUser(userp);
3526 /* Check for RO volume */
3527 if (newScp->flags & CM_SCACHEFLAG_RO) {
3528 lock_ReleaseMutex(&newScp->mx);
3529 cm_ReleaseSCache(newScp);
3530 cm_ReleaseUser(userp);
3531 return CM_ERROR_READONLY;
3534 /* prepare for setattr call */
3537 attr.mask |= CM_ATTRMASK_CLIENTMODTIME;
3538 smb_UnixTimeFromDosUTime(&attr.clientModTime, dosTime);
3540 if ((newScp->unixModeBits & 0222) && (attribute & 1) != 0) {
3541 /* we're told to make a writable file read-only */
3542 attr.unixModeBits = newScp->unixModeBits & ~0222;
3543 attr.mask |= CM_ATTRMASK_UNIXMODEBITS;
3545 else if ((newScp->unixModeBits & 0222) == 0 && (attribute & 1) == 0) {
3546 /* we're told to make a read-only file writable */
3547 attr.unixModeBits = newScp->unixModeBits | 0222;
3548 attr.mask |= CM_ATTRMASK_UNIXMODEBITS;
3550 lock_ReleaseMutex(&newScp->mx);
3552 /* now call setattr */
3554 code = cm_SetAttr(newScp, &attr, userp, &req);
3558 cm_ReleaseSCache(newScp);
3559 cm_ReleaseUser(userp);
3564 long smb_ReceiveCoreGetFileAttributes(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3568 cm_scache_t *rootScp;
3569 cm_scache_t *newScp, *dscp;
3581 pathp = smb_GetSMBData(inp, NULL);
3582 pathp = smb_ParseASCIIBlock(pathp, NULL);
3585 return CM_ERROR_BADSMB;
3588 if (*pathp == 0) /* null path */
3591 osi_Log1(smb_logp, "SMB receive getfile attributes path %s",
3592 osi_LogSaveString(smb_logp, pathp));
3594 rootScp = cm_rootSCachep;
3596 userp = smb_GetUser(vcp, inp);
3598 /* we shouldn't need this for V3 requests, but we seem to */
3599 caseFold = CM_FLAG_CASEFOLD;
3601 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3604 * XXX Strange hack XXX
3606 * As of Patch 5 (16 July 97), we are having the following problem:
3607 * In NT Explorer 4.0, whenever we click on a directory, AFS gets
3608 * requests to look up "desktop.ini" in all the subdirectories.
3609 * This can cause zillions of timeouts looking up non-existent cells
3610 * and volumes, especially in the top-level directory.
3612 * We have not found any way to avoid this or work around it except
3613 * to explicitly ignore the requests for mount points that haven't
3614 * yet been evaluated and for directories that haven't yet been
3617 * We should modify this hack to provide a fake desktop.ini file
3618 * http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/custom.asp
3620 spacep = inp->spacep;
3621 smb_StripLastComponent(spacep->data, &lastComp, pathp);
3622 if (lastComp && stricmp(lastComp, "\\desktop.ini") == 0) {
3623 code = cm_NameI(rootScp, spacep->data,
3624 caseFold | CM_FLAG_DIRSEARCH | CM_FLAG_FOLLOW,
3625 userp, tidPathp, &req, &dscp);
3627 if (dscp->fileType == CM_SCACHETYPE_MOUNTPOINT
3628 && !dscp->mountRootFidp)
3629 code = CM_ERROR_NOSUCHFILE;
3630 else if (dscp->fileType == CM_SCACHETYPE_DIRECTORY) {
3631 cm_buf_t *bp = buf_Find(dscp, &hzero);
3635 code = CM_ERROR_NOSUCHFILE;
3637 cm_ReleaseSCache(dscp);
3639 cm_ReleaseUser(userp);
3645 code = cm_NameI(rootScp, pathp, caseFold | CM_FLAG_FOLLOW, userp,
3646 tidPathp, &req, &newScp);
3649 cm_ReleaseUser(userp);
3653 /* now lock the vnode with a callback; returns with newScp locked */
3654 lock_ObtainMutex(&newScp->mx);
3655 code = cm_SyncOp(newScp, NULL, userp, &req, 0,
3656 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
3658 lock_ReleaseMutex(&newScp->mx);
3659 cm_ReleaseSCache(newScp);
3660 cm_ReleaseUser(userp);
3665 /* use smb_Attributes instead. Also the fact that a file is
3666 * in a readonly volume doesn't mean it shojuld be marked as RO
3668 if (newScp->fileType == CM_SCACHETYPE_DIRECTORY
3669 || newScp->fileType == CM_SCACHETYPE_MOUNTPOINT)
3670 attrs = SMB_ATTR_DIRECTORY;
3673 if ((newScp->unixModeBits & 0222) == 0 || (newScp->flags & CM_SCACHEFLAG_RO))
3674 attrs |= SMB_ATTR_READONLY; /* turn on read-only flag */
3676 attrs = smb_Attributes(newScp);
3679 smb_SetSMBParm(outp, 0, attrs);
3681 smb_DosUTimeFromUnixTime(&dosTime, newScp->clientModTime);
3682 smb_SetSMBParm(outp, 1, dosTime & 0xffff);
3683 smb_SetSMBParm(outp, 2, (dosTime>>16) & 0xffff);
3684 smb_SetSMBParm(outp, 3, newScp->length.LowPart & 0xffff);
3685 smb_SetSMBParm(outp, 4, (newScp->length.LowPart >> 16) & 0xffff);
3686 smb_SetSMBParm(outp, 5, 0);
3687 smb_SetSMBParm(outp, 6, 0);
3688 smb_SetSMBParm(outp, 7, 0);
3689 smb_SetSMBParm(outp, 8, 0);
3690 smb_SetSMBParm(outp, 9, 0);
3691 smb_SetSMBDataLength(outp, 0);
3692 lock_ReleaseMutex(&newScp->mx);
3694 cm_ReleaseSCache(newScp);
3695 cm_ReleaseUser(userp);
3700 long smb_ReceiveCoreTreeDisconnect(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3704 osi_Log0(smb_logp, "SMB receive tree disconnect");
3706 /* find the tree and free it */
3707 tidp = smb_FindTID(vcp, ((smb_t *)inp)->tid, 0);
3709 lock_ObtainMutex(&tidp->mx);
3710 tidp->flags |= SMB_TIDFLAG_DELETE;
3711 lock_ReleaseMutex(&tidp->mx);
3712 smb_ReleaseTID(tidp);
3718 long smb_ReceiveCoreOpen(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3736 pathp = smb_GetSMBData(inp, NULL);
3737 pathp = smb_ParseASCIIBlock(pathp, NULL);
3739 osi_Log1(smb_logp, "SMB receive open file [%s]", osi_LogSaveString(smb_logp, pathp));
3741 #ifdef DEBUG_VERBOSE
3745 hexpath = osi_HexifyString( pathp );
3746 DEBUG_EVENT2("AFS", "CoreOpen H[%s] A[%s]", hexpath, pathp);
3751 share = smb_GetSMBParm(inp, 0);
3752 attribute = smb_GetSMBParm(inp, 1);
3754 spacep = inp->spacep;
3755 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
3756 if (lastNamep && strcmp(lastNamep, SMB_IOCTL_FILENAME) == 0) {
3757 /* special case magic file name for receiving IOCTL requests
3758 * (since IOCTL calls themselves aren't getting through).
3760 fidp = smb_FindFID(vcp, 0, SMB_FLAG_CREATE);
3761 smb_SetupIoctlFid(fidp, spacep);
3762 smb_SetSMBParm(outp, 0, fidp->fid);
3763 smb_SetSMBParm(outp, 1, 0); /* attrs */
3764 smb_SetSMBParm(outp, 2, 0); /* next 2 are DOS time */
3765 smb_SetSMBParm(outp, 3, 0);
3766 smb_SetSMBParm(outp, 4, 0); /* next 2 are length */
3767 smb_SetSMBParm(outp, 5, 0x7fff);
3768 /* pass the open mode back */
3769 smb_SetSMBParm(outp, 6, (share & 0xf));
3770 smb_SetSMBDataLength(outp, 0);
3771 smb_ReleaseFID(fidp);
3775 userp = smb_GetUser(vcp, inp);
3777 caseFold = CM_FLAG_CASEFOLD;
3779 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3780 code = cm_NameI(cm_rootSCachep, pathp, caseFold | CM_FLAG_FOLLOW, userp,
3781 tidPathp, &req, &scp);
3784 cm_ReleaseUser(userp);
3788 code = cm_CheckOpen(scp, share & 0x7, 0, userp, &req);
3790 cm_ReleaseSCache(scp);
3791 cm_ReleaseUser(userp);
3795 /* don't need callback to check file type, since file types never
3796 * change, and namei and cm_Lookup all stat the object at least once on
3797 * a successful return.
3799 if (scp->fileType != CM_SCACHETYPE_FILE) {
3800 cm_ReleaseSCache(scp);
3801 cm_ReleaseUser(userp);
3802 return CM_ERROR_ISDIR;
3805 fidp = smb_FindFID(vcp, 0, SMB_FLAG_CREATE);
3808 /* save a pointer to the vnode */
3811 if ((share & 0xf) == 0)
3812 fidp->flags |= SMB_FID_OPENREAD;
3813 else if ((share & 0xf) == 1)
3814 fidp->flags |= SMB_FID_OPENWRITE;
3816 fidp->flags |= (SMB_FID_OPENREAD | SMB_FID_OPENWRITE);
3818 lock_ObtainMutex(&scp->mx);
3819 smb_SetSMBParm(outp, 0, fidp->fid);
3820 smb_SetSMBParm(outp, 1, smb_Attributes(scp));
3821 smb_DosUTimeFromUnixTime(&dosTime, scp->clientModTime);
3822 smb_SetSMBParm(outp, 2, dosTime & 0xffff);
3823 smb_SetSMBParm(outp, 3, (dosTime >> 16) & 0xffff);
3824 smb_SetSMBParm(outp, 4, scp->length.LowPart & 0xffff);
3825 smb_SetSMBParm(outp, 5, (scp->length.LowPart >> 16) & 0xffff);
3826 /* pass the open mode back; XXXX add access checks */
3827 smb_SetSMBParm(outp, 6, (share & 0xf));
3828 smb_SetSMBDataLength(outp, 0);
3829 lock_ReleaseMutex(&scp->mx);
3832 cm_Open(scp, 0, userp);
3834 /* send and free packet */
3835 smb_ReleaseFID(fidp);
3836 cm_ReleaseUser(userp);
3837 /* don't release scp, since we've squirreled away the pointer in the fid struct */
3841 typedef struct smb_unlinkRock {
3846 char *maskp; /* pointer to the star pattern */
3851 int smb_UnlinkProc(cm_scache_t *dscp, cm_dirEntry_t *dep, void *vrockp, osi_hyper_t *offp)
3854 smb_unlinkRock_t *rockp;
3862 if (rockp->vcp->flags & SMB_VCFLAG_USEV3)
3863 caseFold = CM_FLAG_CASEFOLD;
3865 caseFold = CM_FLAG_CASEFOLD | CM_FLAG_8DOT3;
3867 matchName = dep->name;
3868 match = smb_V3MatchMask(matchName, rockp->maskp, caseFold);
3871 && !cm_Is8Dot3(dep->name)) {
3872 cm_Gen8Dot3Name(dep, shortName, NULL);
3873 matchName = shortName;
3874 match = smb_V3MatchMask(matchName, rockp->maskp, caseFold);
3877 osi_Log1(smb_logp, "Unlinking %s",
3878 osi_LogSaveString(smb_logp, matchName));
3879 code = cm_Unlink(dscp, dep->name, rockp->userp, rockp->reqp);
3880 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
3881 smb_NotifyChange(FILE_ACTION_REMOVED,
3882 FILE_NOTIFY_CHANGE_FILE_NAME,
3883 dscp, dep->name, NULL, TRUE);
3892 long smb_ReceiveCoreUnlink(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3901 smb_unlinkRock_t rock;
3910 attribute = smb_GetSMBParm(inp, 0);
3912 tp = smb_GetSMBData(inp, NULL);
3913 pathp = smb_ParseASCIIBlock(tp, &tp);
3915 osi_Log1(smb_logp, "SMB receive unlink %s",
3916 osi_LogSaveString(smb_logp, pathp));
3918 spacep = inp->spacep;
3919 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
3921 userp = smb_GetUser(vcp, inp);
3923 caseFold = CM_FLAG_FOLLOW | CM_FLAG_CASEFOLD;
3925 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3926 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold, userp, tidPathp,
3930 cm_ReleaseUser(userp);
3934 /* otherwise, scp points to the parent directory. */
3941 rock.maskp = smb_FindMask(pathp);
3942 rock.hasTilde = ((strchr(rock.maskp, '~') != NULL) ? 1 : 0);
3945 thyper.HighPart = 0;
3950 code = cm_ApplyDir(dscp, smb_UnlinkProc, &rock, &thyper, userp, &req, NULL);
3952 cm_ReleaseUser(userp);
3954 cm_ReleaseSCache(dscp);
3956 if (code == 0 && !rock.any)
3957 code = CM_ERROR_NOSUCHFILE;
3961 typedef struct smb_renameRock {
3962 cm_scache_t *odscp; /* old dir */
3963 cm_scache_t *ndscp; /* new dir */
3964 cm_user_t *userp; /* user */
3965 cm_req_t *reqp; /* request struct */
3966 smb_vc_t *vcp; /* virtual circuit */
3967 char *maskp; /* pointer to star pattern of old file name */
3968 int hasTilde; /* star pattern might be shortname? */
3969 char *newNamep; /* ptr to the new file's name */
3972 int smb_RenameProc(cm_scache_t *dscp, cm_dirEntry_t *dep, void *vrockp, osi_hyper_t *offp)
3975 smb_renameRock_t *rockp;
3980 rockp = (smb_renameRock_t *) vrockp;
3982 if (rockp->vcp->flags & SMB_VCFLAG_USEV3)
3983 caseFold = CM_FLAG_CASEFOLD;
3985 caseFold = CM_FLAG_CASEFOLD | CM_FLAG_8DOT3;
3987 match = smb_V3MatchMask(dep->name, rockp->maskp, caseFold);
3990 && !cm_Is8Dot3(dep->name)) {
3991 cm_Gen8Dot3Name(dep, shortName, NULL);
3992 match = smb_V3MatchMask(shortName, rockp->maskp, caseFold);
3995 code = cm_Rename(rockp->odscp, dep->name,
3996 rockp->ndscp, rockp->newNamep, rockp->userp,
3998 /* if the call worked, stop doing the search now, since we
3999 * really only want to rename one file.
4002 code = CM_ERROR_STOPNOW;
4009 long smb_ReceiveCoreRename(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4016 smb_renameRock_t rock;
4017 cm_scache_t *oldDscp;
4018 cm_scache_t *newDscp;
4019 cm_scache_t *tmpscp;
4031 tp = smb_GetSMBData(inp, NULL);
4032 oldPathp = smb_ParseASCIIBlock(tp, &tp);
4033 newPathp = smb_ParseASCIIBlock(tp, &tp);
4035 osi_Log2(smb_logp, "smb rename %s to %s",
4036 osi_LogSaveString(smb_logp, oldPathp),
4037 osi_LogSaveString(smb_logp, newPathp));
4039 spacep = inp->spacep;
4040 smb_StripLastComponent(spacep->data, &oldLastNamep, oldPathp);
4042 userp = smb_GetUser(vcp, inp);
4045 * Changed to use CASEFOLD always. This enables us to rename Foo/baz when
4046 * what actually exists is foo/baz. I don't know why the code used to be
4047 * the way it was. 1/29/96
4049 * caseFold = ((vcp->flags & SMB_VCFLAG_USEV3) ? 0: CM_FLAG_CASEFOLD);
4051 * Changed to use CM_FLAG_FOLLOW. 7/24/96
4053 * caseFold = CM_FLAG_CASEFOLD;
4055 caseFold = CM_FLAG_FOLLOW | CM_FLAG_CASEFOLD;
4057 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
4058 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold,
4059 userp, tidPathp, &req, &oldDscp);
4062 cm_ReleaseUser(userp);
4066 smb_StripLastComponent(spacep->data, &newLastNamep, newPathp);
4067 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold,
4068 userp, tidPathp, &req, &newDscp);
4071 cm_ReleaseSCache(oldDscp);
4072 cm_ReleaseUser(userp);
4076 /* otherwise, oldDscp and newDscp point to the corresponding directories.
4077 * next, get the component names, and lower case them.
4080 /* handle the old name first */
4082 oldLastNamep = oldPathp;
4086 /* and handle the new name, too */
4088 newLastNamep = newPathp;
4092 /* do the vnode call */
4093 rock.odscp = oldDscp;
4094 rock.ndscp = newDscp;
4098 rock.maskp = oldLastNamep;
4099 rock.hasTilde = ((strchr(oldLastNamep, '~') != NULL) ? 1 : 0);
4100 rock.newNamep = newLastNamep;
4102 /* Check if the file already exists; if so return error */
4103 code = cm_Lookup(newDscp,newLastNamep,CM_FLAG_CHECKPATH,userp,&req,&tmpscp);
4104 if((code != CM_ERROR_NOSUCHFILE) && (code != CM_ERROR_NOSUCHPATH) && (code != CM_ERROR_NOSUCHVOLUME) ) {
4105 cm_ReleaseSCache(newDscp);
4106 cm_ReleaseSCache(oldDscp);
4107 cm_ReleaseUser(userp);
4109 cm_ReleaseSCache(tmpscp);
4110 /* Check if the old and the new names differ only in case. If so return
4111 * success, else return CM_ERROR_EXISTS
4113 if(oldDscp == newDscp && !stricmp(oldLastNamep, newLastNamep)) {
4114 osi_Log0(afsd_logp, "Rename: Old and new names are the same");
4117 /* file exist, do not rename, also fixes move */
4118 osi_Log0(afsd_logp, "Can't rename. Target already exists");
4119 code = CM_ERROR_EXISTS;
4124 /* Now search the directory for the pattern, and do the appropriate rename when found */
4125 thyper.LowPart = 0; /* search dir from here */
4126 thyper.HighPart = 0;
4128 code = cm_ApplyDir(oldDscp, smb_RenameProc, &rock, &thyper, userp, &req, NULL);
4130 if (code == CM_ERROR_STOPNOW)
4133 code = CM_ERROR_NOSUCHFILE;
4135 /* Handle Change Notification */
4137 * Being lazy, not distinguishing between files and dirs in this
4138 * filter, since we'd have to do a lookup.
4140 filter = FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME;
4141 if (oldDscp == newDscp) {
4142 if (oldDscp->flags & CM_SCACHEFLAG_ANYWATCH)
4143 smb_NotifyChange(FILE_ACTION_RENAMED_OLD_NAME,
4144 filter, oldDscp, oldLastNamep,
4145 newLastNamep, TRUE);
4147 if (oldDscp->flags & CM_SCACHEFLAG_ANYWATCH)
4148 smb_NotifyChange(FILE_ACTION_RENAMED_OLD_NAME,
4149 filter, oldDscp, oldLastNamep,
4151 if (newDscp->flags & CM_SCACHEFLAG_ANYWATCH)
4152 smb_NotifyChange(FILE_ACTION_RENAMED_NEW_NAME,
4153 filter, newDscp, newLastNamep,
4157 cm_ReleaseUser(userp);
4158 cm_ReleaseSCache(oldDscp);
4159 cm_ReleaseSCache(newDscp);
4163 typedef struct smb_rmdirRock {
4167 char *maskp; /* pointer to the star pattern */
4172 int smb_RmdirProc(cm_scache_t *dscp, cm_dirEntry_t *dep, void *vrockp, osi_hyper_t *offp)
4175 smb_rmdirRock_t *rockp;
4182 matchName = dep->name;
4183 match = (cm_stricmp(matchName, rockp->maskp) == 0);
4186 && !cm_Is8Dot3(dep->name)) {
4187 cm_Gen8Dot3Name(dep, shortName, NULL);
4188 matchName = shortName;
4189 match = (cm_stricmp(matchName, rockp->maskp) == 0);
4192 osi_Log1(smb_logp, "Removing directory %s",
4193 osi_LogSaveString(smb_logp, matchName));
4194 code = cm_RemoveDir(dscp, dep->name, rockp->userp, rockp->reqp);
4195 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4196 smb_NotifyChange(FILE_ACTION_REMOVED,
4197 FILE_NOTIFY_CHANGE_DIR_NAME,
4198 dscp, dep->name, NULL, TRUE);
4207 long smb_ReceiveCoreRemoveDir(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4215 smb_rmdirRock_t rock;
4224 tp = smb_GetSMBData(inp, NULL);
4225 pathp = smb_ParseASCIIBlock(tp, &tp);
4227 spacep = inp->spacep;
4228 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
4230 userp = smb_GetUser(vcp, inp);
4232 caseFold = CM_FLAG_CASEFOLD;
4234 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
4235 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold | CM_FLAG_FOLLOW,
4236 userp, tidPathp, &req, &dscp);
4239 cm_ReleaseUser(userp);
4243 /* otherwise, scp points to the parent directory. */
4250 rock.maskp = lastNamep;
4251 rock.hasTilde = ((strchr(rock.maskp, '~') != NULL) ? 1 : 0);
4254 thyper.HighPart = 0;
4258 code = cm_ApplyDir(dscp, smb_RmdirProc, &rock, &thyper, userp, &req, NULL);
4260 cm_ReleaseUser(userp);
4262 cm_ReleaseSCache(dscp);
4264 if (code == 0 && !rock.any)
4265 code = CM_ERROR_NOSUCHFILE;
4269 long smb_ReceiveCoreFlush(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4279 fid = smb_GetSMBParm(inp, 0);
4281 osi_Log1(smb_logp, "SMB flush fid %d", fid);
4283 fid = smb_ChainFID(fid, inp);
4284 fidp = smb_FindFID(vcp, fid, 0);
4285 if (!fidp || (fidp->flags & SMB_FID_IOCTL)) {
4287 smb_ReleaseFID(fidp);
4288 return CM_ERROR_BADFD;
4291 userp = smb_GetUser(vcp, inp);
4293 lock_ObtainMutex(&fidp->mx);
4294 if (fidp->flags & SMB_FID_OPENWRITE)
4295 code = cm_FSync(fidp->scp, userp, &req);
4298 lock_ReleaseMutex(&fidp->mx);
4300 smb_ReleaseFID(fidp);
4302 cm_ReleaseUser(userp);
4307 struct smb_FullNameRock {
4313 int smb_FullNameProc(cm_scache_t *scp, cm_dirEntry_t *dep, void *rockp,
4317 struct smb_FullNameRock *vrockp;
4321 if (!cm_Is8Dot3(dep->name)) {
4322 cm_Gen8Dot3Name(dep, shortName, NULL);
4324 if (strcmp(shortName, vrockp->name) == 0) {
4325 vrockp->fullName = strdup(dep->name);
4326 return CM_ERROR_STOPNOW;
4329 if (stricmp(dep->name, vrockp->name) == 0
4330 && ntohl(dep->fid.vnode) == vrockp->vnode->fid.vnode
4331 && ntohl(dep->fid.unique) == vrockp->vnode->fid.unique) {
4332 vrockp->fullName = strdup(dep->name);
4333 return CM_ERROR_STOPNOW;
4338 void smb_FullName(cm_scache_t *dscp, cm_scache_t *scp, char *pathp,
4339 char **newPathp, cm_user_t *userp, cm_req_t *reqp)
4341 struct smb_FullNameRock rock;
4347 code = cm_ApplyDir(dscp, smb_FullNameProc, &rock, NULL,
4349 if (code == CM_ERROR_STOPNOW)
4350 *newPathp = rock.fullName;
4352 *newPathp = strdup(pathp);
4355 long smb_ReceiveCoreClose(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4366 fid = smb_GetSMBParm(inp, 0);
4367 dosTime = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
4369 osi_Log1(smb_logp, "SMB close fid %d", fid);
4371 fid = smb_ChainFID(fid, inp);
4372 fidp = smb_FindFID(vcp, fid, 0);
4374 return CM_ERROR_BADFD;
4377 userp = smb_GetUser(vcp, inp);
4379 lock_ObtainMutex(&fidp->mx);
4381 /* Don't jump the gun on an async raw write */
4382 while (fidp->raw_writers) {
4383 lock_ReleaseMutex(&fidp->mx);
4384 thrd_WaitForSingleObject_Event(fidp->raw_write_event, RAWTIMEOUT);
4385 lock_ObtainMutex(&fidp->mx);
4388 fidp->flags |= SMB_FID_DELETE;
4390 /* watch for ioctl closes, and read-only opens */
4391 if (fidp->scp != NULL
4392 && (fidp->flags & (SMB_FID_OPENWRITE | SMB_FID_DELONCLOSE))
4393 == SMB_FID_OPENWRITE) {
4394 if (dosTime != 0 && dosTime != -1) {
4395 fidp->scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
4396 /* This fixes defect 10958 */
4397 CompensateForSmbClientLastWriteTimeBugs(&dosTime);
4398 smb_UnixTimeFromDosUTime(&fidp->scp->clientModTime, dosTime);
4400 code = cm_FSync(fidp->scp, userp, &req);
4405 if (fidp->flags & SMB_FID_DELONCLOSE) {
4406 cm_scache_t *dscp = fidp->NTopen_dscp;
4407 char *pathp = fidp->NTopen_pathp;
4410 smb_FullName(dscp, fidp->scp, pathp, &fullPathp, userp, &req);
4411 if (fidp->scp->fileType == CM_SCACHETYPE_DIRECTORY) {
4412 code = cm_RemoveDir(dscp, fullPathp, userp, &req);
4413 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4414 smb_NotifyChange(FILE_ACTION_REMOVED,
4415 FILE_NOTIFY_CHANGE_DIR_NAME,
4416 dscp, fullPathp, NULL, TRUE);
4420 code = cm_Unlink(dscp, fullPathp, userp, &req);
4421 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4422 smb_NotifyChange(FILE_ACTION_REMOVED,
4423 FILE_NOTIFY_CHANGE_FILE_NAME,
4424 dscp, fullPathp, NULL, TRUE);
4428 lock_ReleaseMutex(&fidp->mx);
4430 if (fidp->flags & SMB_FID_NTOPEN) {
4431 cm_ReleaseSCache(fidp->NTopen_dscp);
4432 free(fidp->NTopen_pathp);
4434 if (fidp->NTopen_wholepathp)
4435 free(fidp->NTopen_wholepathp);
4437 smb_ReleaseFID(fidp);
4438 cm_ReleaseUser(userp);
4443 * smb_ReadData -- common code for Read, Read And X, and Raw Read
4446 long smb_ReadData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4447 cm_user_t *userp, long *readp)
4449 long smb_ReadData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4450 cm_user_t *userp, long *readp, int dosflag)
4457 osi_hyper_t fileLength;
4459 osi_hyper_t lastByte;
4460 osi_hyper_t bufferOffset;
4461 long bufIndex, nbytes;
4471 lock_ObtainMutex(&fidp->mx);
4473 lock_ObtainMutex(&scp->mx);
4475 if (offset.HighPart == 0) {
4476 chunk = offset.LowPart >> cm_logChunkSize;
4477 if (chunk != fidp->curr_chunk) {
4478 fidp->prev_chunk = fidp->curr_chunk;
4479 fidp->curr_chunk = chunk;
4481 if (fidp->curr_chunk == fidp->prev_chunk + 1)
4485 /* start by looking up the file's end */
4486 code = cm_SyncOp(scp, NULL, userp, &req, 0,
4487 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
4488 if (code) goto done;
4490 /* now we have the entry locked, look up the length */
4491 fileLength = scp->length;
4493 /* adjust count down so that it won't go past EOF */
4494 thyper.LowPart = count;
4495 thyper.HighPart = 0;
4496 thyper = LargeIntegerAdd(offset, thyper); /* where read should end */
4498 if (LargeIntegerGreaterThan(thyper, fileLength)) {
4499 /* we'd read past EOF, so just stop at fileLength bytes.
4500 * Start by computing how many bytes remain in the file.
4502 thyper = LargeIntegerSubtract(fileLength, offset);
4504 /* if we are past EOF, read 0 bytes */
4505 if (LargeIntegerLessThanZero(thyper))
4508 count = thyper.LowPart;
4513 /* now, copy the data one buffer at a time,
4514 * until we've filled the request packet
4517 /* if we've copied all the data requested, we're done */
4518 if (count <= 0) break;
4520 /* otherwise, load up a buffer of data */
4521 thyper.HighPart = offset.HighPart;
4522 thyper.LowPart = offset.LowPart & ~(buf_bufferSize-1);
4523 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
4526 buf_Release(bufferp);
4529 lock_ReleaseMutex(&scp->mx);
4531 lock_ObtainRead(&scp->bufCreateLock);
4532 code = buf_Get(scp, &thyper, &bufferp);
4533 lock_ReleaseRead(&scp->bufCreateLock);
4535 lock_ObtainMutex(&scp->mx);
4536 if (code) goto done;
4537 bufferOffset = thyper;
4539 /* now get the data in the cache */
4541 code = cm_SyncOp(scp, bufferp, userp, &req, 0,
4542 CM_SCACHESYNC_NEEDCALLBACK
4543 | CM_SCACHESYNC_READ);
4544 if (code) goto done;
4546 if (cm_HaveBuffer(scp, bufferp, 0)) break;
4548 /* otherwise, load the buffer and try again */
4549 code = cm_GetBuffer(scp, bufferp, NULL, userp, &req);
4553 buf_Release(bufferp);
4557 } /* if (wrong buffer) ... */
4559 /* now we have the right buffer loaded. Copy out the
4560 * data from here to the user's buffer.
4562 bufIndex = offset.LowPart & (buf_bufferSize - 1);
4564 /* and figure out how many bytes we want from this buffer */
4565 nbytes = buf_bufferSize - bufIndex; /* what remains in buffer */
4566 if (nbytes > count) nbytes = count; /* don't go past EOF */
4568 /* now copy the data */
4571 dosmemput(bufferp->datap + bufIndex, nbytes, (dos_ptr)op);
4574 memcpy(op, bufferp->datap + bufIndex, nbytes);
4576 /* adjust counters, pointers, etc. */
4579 thyper.LowPart = nbytes;
4580 thyper.HighPart = 0;
4581 offset = LargeIntegerAdd(thyper, offset);
4585 lock_ReleaseMutex(&scp->mx);
4586 lock_ReleaseMutex(&fidp->mx);
4588 buf_Release(bufferp);
4590 if (code == 0 && sequential)
4591 cm_ConsiderPrefetch(scp, &lastByte, userp, &req);
4597 * smb_WriteData -- common code for Write and Raw Write
4600 long smb_WriteData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4601 cm_user_t *userp, long *writtenp)
4603 long smb_WriteData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4604 cm_user_t *userp, long *writtenp, int dosflag)
4611 osi_hyper_t fileLength; /* file's length at start of write */
4612 osi_hyper_t minLength; /* don't read past this */
4613 long nbytes; /* # of bytes to transfer this iteration */
4615 osi_hyper_t thyper; /* hyper tmp variable */
4616 osi_hyper_t bufferOffset;
4617 long bufIndex; /* index in buffer where our data is */
4619 osi_hyper_t writeBackOffset; /* offset of region to write back when
4630 lock_ObtainMutex(&fidp->mx);
4632 lock_ObtainMutex(&scp->mx);
4634 /* start by looking up the file's end */
4635 code = cm_SyncOp(scp, NULL, userp, &req, 0,
4636 CM_SCACHESYNC_NEEDCALLBACK
4637 | CM_SCACHESYNC_SETSTATUS
4638 | CM_SCACHESYNC_GETSTATUS);
4642 /* make sure we have a writable FD */
4643 if (!(fidp->flags & SMB_FID_OPENWRITE)) {
4644 code = CM_ERROR_BADFDOP;
4648 /* now we have the entry locked, look up the length */
4649 fileLength = scp->length;
4650 minLength = fileLength;
4651 if (LargeIntegerGreaterThan(minLength, scp->serverLength))
4652 minLength = scp->serverLength;
4654 /* adjust file length if we extend past EOF */
4655 thyper.LowPart = count;
4656 thyper.HighPart = 0;
4657 thyper = LargeIntegerAdd(offset, thyper); /* where write should end */
4658 if (LargeIntegerGreaterThan(thyper, fileLength)) {
4659 /* we'd write past EOF, so extend the file */
4660 scp->mask |= CM_SCACHEMASK_LENGTH;
4661 scp->length = thyper;
4662 filter |= (FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE);
4664 filter |= FILE_NOTIFY_CHANGE_LAST_WRITE;
4666 /* now, if the new position (thyper) and the old (offset) are in
4667 * different storeback windows, remember to store back the previous
4668 * storeback window when we're done with the write.
4670 if ((thyper.LowPart & (-cm_chunkSize)) !=
4671 (offset.LowPart & (-cm_chunkSize))) {
4672 /* they're different */
4674 writeBackOffset.HighPart = offset.HighPart;
4675 writeBackOffset.LowPart = offset.LowPart & (-cm_chunkSize);
4680 /* now, copy the data one buffer at a time, until we've filled the
4683 /* if we've copied all the data requested, we're done */
4684 if (count <= 0) break;
4686 /* handle over quota or out of space */
4687 if (scp->flags & (CM_SCACHEFLAG_OVERQUOTA | CM_SCACHEFLAG_OUTOFSPACE)) {
4688 *writtenp = written;
4692 /* otherwise, load up a buffer of data */
4693 thyper.HighPart = offset.HighPart;
4694 thyper.LowPart = offset.LowPart & ~(buf_bufferSize-1);
4695 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
4698 lock_ReleaseMutex(&bufferp->mx);
4699 buf_Release(bufferp);
4702 lock_ReleaseMutex(&scp->mx);
4704 lock_ObtainRead(&scp->bufCreateLock);
4705 code = buf_Get(scp, &thyper, &bufferp);
4706 lock_ReleaseRead(&scp->bufCreateLock);
4708 lock_ObtainMutex(&bufferp->mx);
4709 lock_ObtainMutex(&scp->mx);
4710 if (code) goto done;
4712 bufferOffset = thyper;
4714 /* now get the data in the cache */
4716 code = cm_SyncOp(scp, bufferp, userp, &req, 0,
4717 CM_SCACHESYNC_NEEDCALLBACK
4718 | CM_SCACHESYNC_WRITE
4719 | CM_SCACHESYNC_BUFLOCKED);
4723 /* If we're overwriting the entire buffer, or
4724 * if we're writing at or past EOF, mark the
4725 * buffer as current so we don't call
4726 * cm_GetBuffer. This skips the fetch from the
4727 * server in those cases where we're going to
4728 * obliterate all the data in the buffer anyway,
4729 * or in those cases where there is no useful
4730 * data at the server to start with.
4732 * Use minLength instead of scp->length, since
4733 * the latter has already been updated by this
4736 if (LargeIntegerGreaterThanOrEqualTo(
4737 bufferp->offset, minLength)
4738 || LargeIntegerEqualTo(offset, bufferp->offset)
4739 && (count >= buf_bufferSize
4740 || LargeIntegerGreaterThanOrEqualTo(
4741 LargeIntegerAdd(offset,
4742 ConvertLongToLargeInteger(count)),
4744 if (count < buf_bufferSize
4745 && bufferp->dataVersion == -1)
4746 memset(bufferp->datap, 0,
4748 bufferp->dataVersion = scp->dataVersion;
4751 if (cm_HaveBuffer(scp, bufferp, 1)) break;
4753 /* otherwise, load the buffer and try again */
4754 lock_ReleaseMutex(&bufferp->mx);
4755 code = cm_GetBuffer(scp, bufferp, NULL, userp,
4757 lock_ReleaseMutex(&scp->mx);
4758 lock_ObtainMutex(&bufferp->mx);
4759 lock_ObtainMutex(&scp->mx);
4763 lock_ReleaseMutex(&bufferp->mx);
4764 buf_Release(bufferp);
4768 } /* if (wrong buffer) ... */
4770 /* now we have the right buffer loaded. Copy out the
4771 * data from here to the user's buffer.
4773 bufIndex = offset.LowPart & (buf_bufferSize - 1);
4775 /* and figure out how many bytes we want from this buffer */
4776 nbytes = buf_bufferSize - bufIndex; /* what remains in buffer */
4778 nbytes = count; /* don't go past end of request */
4780 /* now copy the data */
4783 dosmemget((dos_ptr)op, nbytes, bufferp->datap + bufIndex);
4786 memcpy(bufferp->datap + bufIndex, op, nbytes);
4787 buf_SetDirty(bufferp);
4789 /* and record the last writer */
4790 if (bufferp->userp != userp) {
4793 cm_ReleaseUser(bufferp->userp);
4794 bufferp->userp = userp;
4797 /* adjust counters, pointers, etc. */
4801 thyper.LowPart = nbytes;
4802 thyper.HighPart = 0;
4803 offset = LargeIntegerAdd(thyper, offset);
4807 lock_ReleaseMutex(&scp->mx);
4808 lock_ReleaseMutex(&fidp->mx);
4810 lock_ReleaseMutex(&bufferp->mx);
4811 buf_Release(bufferp);
4814 if (code == 0 && filter != 0 && (fidp->flags & SMB_FID_NTOPEN)
4815 && (fidp->NTopen_dscp->flags & CM_SCACHEFLAG_ANYWATCH)) {
4816 smb_NotifyChange(FILE_ACTION_MODIFIED, filter,
4817 fidp->NTopen_dscp, fidp->NTopen_pathp,
4821 if (code == 0 && doWriteBack) {
4822 lock_ObtainMutex(&scp->mx);
4823 cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_ASYNCSTORE);
4824 lock_ReleaseMutex(&scp->mx);
4825 cm_QueueBKGRequest(scp, cm_BkgStore, writeBackOffset.LowPart,
4826 writeBackOffset.HighPart, cm_chunkSize, 0, userp);
4832 long smb_ReceiveCoreWrite(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4835 long count, written = 0;
4840 cm_attr_t truncAttr; /* attribute struct used for truncating file */
4842 int inDataBlockCount;
4844 fd = smb_GetSMBParm(inp, 0);
4845 count = smb_GetSMBParm(inp, 1);
4846 offset.HighPart = 0; /* too bad */
4847 offset.LowPart = smb_GetSMBParm(inp, 2) | (smb_GetSMBParm(inp, 3) << 16);
4849 op = smb_GetSMBData(inp, NULL);
4850 op = smb_ParseDataBlock(op, NULL, &inDataBlockCount);
4852 osi_Log3(smb_logp, "smb_ReceiveCoreWrite fd %d, off 0x%x, size 0x%x",
4853 fd, offset.LowPart, count);
4855 fd = smb_ChainFID(fd, inp);
4856 fidp = smb_FindFID(vcp, fd, 0);
4858 return CM_ERROR_BADFD;
4861 if (fidp->flags & SMB_FID_IOCTL)
4862 return smb_IoctlWrite(fidp, vcp, inp, outp);
4864 userp = smb_GetUser(vcp, inp);
4866 /* special case: 0 bytes transferred means truncate to this position */
4872 truncAttr.mask = CM_ATTRMASK_LENGTH;
4873 truncAttr.length.LowPart = offset.LowPart;
4874 truncAttr.length.HighPart = 0;
4875 lock_ObtainMutex(&fidp->mx);
4876 code = cm_SetAttr(fidp->scp, &truncAttr, userp, &req);
4877 lock_ReleaseMutex(&fidp->mx);
4878 smb_SetSMBParm(outp, 0, /* count */ 0);
4879 smb_SetSMBDataLength(outp, 0);
4880 fidp->flags |= SMB_FID_LENGTHSETDONE;
4885 * Work around bug in NT client
4887 * When copying a file, the NT client should first copy the data,
4888 * then copy the last write time. But sometimes the NT client does
4889 * these in the wrong order, so the data copies would inadvertently
4890 * cause the last write time to be overwritten. We try to detect this,
4891 * and don't set client mod time if we think that would go against the
4894 if ((fidp->flags & SMB_FID_MTIMESETDONE) != SMB_FID_MTIMESETDONE) {
4895 fidp->scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
4896 fidp->scp->clientModTime = time(NULL);
4900 code = smb_WriteData(fidp, &offset, count, op, userp, &written);
4902 code = smb_WriteData(fidp, &offset, count, op, userp, &written, FALSE);
4904 if (code == 0 && written < count)
4905 code = CM_ERROR_PARTIALWRITE;
4907 /* set the packet data length to 3 bytes for the data block header,
4908 * plus the size of the data.
4910 smb_SetSMBParm(outp, 0, written);
4911 smb_SetSMBDataLength(outp, 0);
4914 smb_ReleaseFID(fidp);
4915 cm_ReleaseUser(userp);
4920 void smb_CompleteWriteRaw(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp,
4921 NCB *ncbp, raw_write_cont_t *rwcp)
4934 fd = smb_GetSMBParm(inp, 0);
4935 fidp = smb_FindFID(vcp, fd, 0);
4937 osi_Log2(smb_logp, "Completing Raw Write offset %x count %x",
4938 rwcp->offset.LowPart, rwcp->count);
4940 userp = smb_GetUser(vcp, inp);
4944 code = smb_WriteData(fidp, &rwcp->offset, rwcp->count, rawBuf, userp,
4947 rawBuf = (dos_ptr) rwcp->buf;
4948 code = smb_WriteData(fidp, &rwcp->offset, rwcp->count,
4949 (unsigned char *) rawBuf, userp,
4953 if (rwcp->writeMode & 0x1) { /* synchronous */
4956 smb_FormatResponsePacket(vcp, inp, outp);
4957 op = (smb_t *) outp;
4958 op->com = 0x20; /* SMB_COM_WRITE_COMPLETE */
4959 smb_SetSMBParm(outp, 0, written + rwcp->alreadyWritten);
4960 smb_SetSMBDataLength(outp, 0);
4961 smb_SendPacket(vcp, outp);
4962 smb_FreePacket(outp);
4964 else { /* asynchronous */
4965 lock_ObtainMutex(&fidp->mx);
4966 fidp->raw_writers--;
4967 if (fidp->raw_writers == 0)
4968 thrd_SetEvent(fidp->raw_write_event);
4969 lock_ReleaseMutex(&fidp->mx);
4972 /* Give back raw buffer */
4973 lock_ObtainMutex(&smb_RawBufLock);
4975 *((char **)rawBuf) = smb_RawBufs;
4977 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
4979 smb_RawBufs = rawBuf;
4980 lock_ReleaseMutex(&smb_RawBufLock);
4982 smb_ReleaseFID(fidp);
4983 cm_ReleaseUser(userp);
4986 long smb_ReceiveCoreWriteRawDummy(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4991 long smb_ReceiveCoreWriteRaw(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp, raw_write_cont_t *rwcp)
4994 long count, written = 0;
5001 unsigned short writeMode;
5008 fd = smb_GetSMBParm(inp, 0);
5009 totalCount = smb_GetSMBParm(inp, 1);
5010 count = smb_GetSMBParm(inp, 10);
5011 offset.HighPart = 0; /* too bad */
5012 offset.LowPart = smb_GetSMBParm(inp, 3) | (smb_GetSMBParm(inp, 4) << 16);
5013 writeMode = smb_GetSMBParm(inp, 7);
5015 op = (char *) inp->data;
5016 op += smb_GetSMBParm(inp, 11);
5019 "smb_ReceiveCoreWriteRaw fd %d, off 0x%x, size 0x%x, WriteMode 0x%x",
5020 fd, offset.LowPart, count, writeMode);
5022 fd = smb_ChainFID(fd, inp);
5023 fidp = smb_FindFID(vcp, fd, 0);
5025 return CM_ERROR_BADFD;
5028 userp = smb_GetUser(vcp, inp);
5031 * Work around bug in NT client
5033 * When copying a file, the NT client should first copy the data,
5034 * then copy the last write time. But sometimes the NT client does
5035 * these in the wrong order, so the data copies would inadvertently
5036 * cause the last write time to be overwritten. We try to detect this,
5037 * and don't set client mod time if we think that would go against the
5040 if ((fidp->flags & SMB_FID_LOOKSLIKECOPY) != SMB_FID_LOOKSLIKECOPY) {
5041 fidp->scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
5042 fidp->scp->clientModTime = time(NULL);
5046 code = smb_WriteData(fidp, &offset, count, op, userp, &written);
5048 code = smb_WriteData(fidp, &offset, count, op, userp, &written, FALSE);
5050 if (code == 0 && written < count)
5051 code = CM_ERROR_PARTIALWRITE;
5053 /* Get a raw buffer */
5056 lock_ObtainMutex(&smb_RawBufLock);
5058 /* Get a raw buf, from head of list */
5059 rawBuf = smb_RawBufs;
5061 smb_RawBufs = *(char **)smb_RawBufs;
5063 smb_RawBufs = _farpeekl(_dos_ds, smb_RawBufs);
5067 code = CM_ERROR_USESTD;
5069 lock_ReleaseMutex(&smb_RawBufLock);
5072 /* Don't allow a premature Close */
5073 if (code == 0 && (writeMode & 1) == 0) {
5074 lock_ObtainMutex(&fidp->mx);
5075 fidp->raw_writers++;
5076 thrd_ResetEvent(fidp->raw_write_event);
5077 lock_ReleaseMutex(&fidp->mx);
5080 smb_ReleaseFID(fidp);
5081 cm_ReleaseUser(userp);
5084 smb_SetSMBParm(outp, 0, written);
5085 smb_SetSMBDataLength(outp, 0);
5086 ((smb_t *)outp)->com = 0x20; /* SMB_COM_WRITE_COMPLETE */
5093 rwcp->offset.HighPart = 0;
5094 rwcp->offset.LowPart = offset.LowPart + count;
5095 rwcp->count = totalCount - count;
5096 rwcp->writeMode = writeMode;
5097 rwcp->alreadyWritten = written;
5099 /* set the packet data length to 3 bytes for the data block header,
5100 * plus the size of the data.
5102 smb_SetSMBParm(outp, 0, 0xffff);
5103 smb_SetSMBDataLength(outp, 0);
5108 long smb_ReceiveCoreRead(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5111 long count, finalCount;
5118 fd = smb_GetSMBParm(inp, 0);
5119 count = smb_GetSMBParm(inp, 1);
5120 offset.HighPart = 0; /* too bad */
5121 offset.LowPart = smb_GetSMBParm(inp, 2) | (smb_GetSMBParm(inp, 3) << 16);
5123 osi_Log3(smb_logp, "smb_ReceiveCoreRead fd %d, off 0x%x, size 0x%x",
5124 fd, offset.LowPart, count);
5126 fd = smb_ChainFID(fd, inp);
5127 fidp = smb_FindFID(vcp, fd, 0);
5129 return CM_ERROR_BADFD;
5132 if (fidp->flags & SMB_FID_IOCTL) {
5133 return smb_IoctlRead(fidp, vcp, inp, outp);
5136 userp = smb_GetUser(vcp, inp);
5138 /* remember this for final results */
5139 smb_SetSMBParm(outp, 0, count);
5140 smb_SetSMBParm(outp, 1, 0);
5141 smb_SetSMBParm(outp, 2, 0);
5142 smb_SetSMBParm(outp, 3, 0);
5143 smb_SetSMBParm(outp, 4, 0);
5145 /* set the packet data length to 3 bytes for the data block header,
5146 * plus the size of the data.
5148 smb_SetSMBDataLength(outp, count+3);
5150 /* get op ptr after putting in the parms, since otherwise we don't
5151 * know where the data really is.
5153 op = smb_GetSMBData(outp, NULL);
5155 /* now emit the data block header: 1 byte of type and 2 bytes of length */
5156 *op++ = 1; /* data block marker */
5157 *op++ = (unsigned char) (count & 0xff);
5158 *op++ = (unsigned char) ((count >> 8) & 0xff);
5161 code = smb_ReadData(fidp, &offset, count, op, userp, &finalCount);
5163 code = smb_ReadData(fidp, &offset, count, op, userp, &finalCount, FALSE);
5166 /* fix some things up */
5167 smb_SetSMBParm(outp, 0, finalCount);
5168 smb_SetSMBDataLength(outp, finalCount+3);
5170 smb_ReleaseFID(fidp);
5172 cm_ReleaseUser(userp);
5176 long smb_ReceiveCoreMakeDir(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5183 cm_scache_t *dscp; /* dir we're dealing with */
5184 cm_scache_t *scp; /* file we're creating */
5186 int initialModeBits;
5196 /* compute initial mode bits based on read-only flag in attributes */
5197 initialModeBits = 0777;
5199 tp = smb_GetSMBData(inp, NULL);
5200 pathp = smb_ParseASCIIBlock(tp, &tp);
5202 if (strcmp(pathp, "\\") == 0)
5203 return CM_ERROR_EXISTS;
5205 spacep = inp->spacep;
5206 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
5208 userp = smb_GetUser(vcp, inp);
5210 caseFold = CM_FLAG_CASEFOLD;
5212 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
5214 code = cm_NameI(cm_rootSCachep, spacep->data,
5215 caseFold | CM_FLAG_FOLLOW | CM_FLAG_CHECKPATH,
5216 userp, tidPathp, &req, &dscp);
5219 cm_ReleaseUser(userp);
5223 /* otherwise, scp points to the parent directory. Do a lookup, and
5224 * fail if we find it. Otherwise, we do the create.
5230 code = cm_Lookup(dscp, lastNamep, caseFold, userp, &req, &scp);
5231 if (scp) cm_ReleaseSCache(scp);
5232 if (code != CM_ERROR_NOSUCHFILE) {
5233 if (code == 0) code = CM_ERROR_EXISTS;
5234 cm_ReleaseSCache(dscp);
5235 cm_ReleaseUser(userp);
5239 setAttr.mask = CM_ATTRMASK_CLIENTMODTIME;
5240 setAttr.clientModTime = time(NULL);
5241 code = cm_MakeDir(dscp, lastNamep, 0, &setAttr, userp, &req);
5242 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
5243 smb_NotifyChange(FILE_ACTION_ADDED,
5244 FILE_NOTIFY_CHANGE_DIR_NAME,
5245 dscp, lastNamep, NULL, TRUE);
5247 /* we don't need this any longer */
5248 cm_ReleaseSCache(dscp);
5251 /* something went wrong creating or truncating the file */
5252 cm_ReleaseUser(userp);
5256 /* otherwise we succeeded */
5257 smb_SetSMBDataLength(outp, 0);
5258 cm_ReleaseUser(userp);
5263 BOOL smb_IsLegalFilename(char *filename)
5266 * Find the longest substring of filename that does not contain
5267 * any of the chars in illegalChars. If that substring is less
5268 * than the length of the whole string, then one or more of the
5269 * illegal chars is in filename.
5271 if (strcspn(filename, illegalChars) < strlen(filename))
5277 long smb_ReceiveCoreCreate(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5285 cm_scache_t *dscp; /* dir we're dealing with */
5286 cm_scache_t *scp; /* file we're creating */
5288 int initialModeBits;
5300 excl = (inp->inCom == 0x03)? 0 : 1;
5302 attributes = smb_GetSMBParm(inp, 0);
5303 dosTime = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
5305 /* compute initial mode bits based on read-only flag in attributes */
5306 initialModeBits = 0666;
5307 if (attributes & 1) initialModeBits &= ~0222;
5309 tp = smb_GetSMBData(inp, NULL);
5310 pathp = smb_ParseASCIIBlock(tp, &tp);
5312 spacep = inp->spacep;
5313 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
5315 userp = smb_GetUser(vcp, inp);
5317 caseFold = CM_FLAG_CASEFOLD;
5319 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
5320 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold | CM_FLAG_FOLLOW,
5321 userp, tidPathp, &req, &dscp);
5324 cm_ReleaseUser(userp);
5328 /* otherwise, scp points to the parent directory. Do a lookup, and
5329 * truncate the file if we find it, otherwise we create the file.
5331 if (!lastNamep) lastNamep = pathp;
5334 if (!smb_IsLegalFilename(lastNamep))
5335 return CM_ERROR_BADNTFILENAME;
5337 osi_Log1(smb_logp, "SMB receive create [%s]", osi_LogSaveString( smb_logp, pathp ));
5338 #ifdef DEBUG_VERBOSE
5341 hexp = osi_HexifyString( lastNamep );
5342 DEBUG_EVENT2("AFS", "CoreCreate H[%s] A[%s]", hexp, lastNamep );
5347 code = cm_Lookup(dscp, lastNamep, caseFold, userp, &req, &scp);
5348 if (code && code != CM_ERROR_NOSUCHFILE) {
5349 cm_ReleaseSCache(dscp);
5350 cm_ReleaseUser(userp);
5354 /* if we get here, if code is 0, the file exists and is represented by
5355 * scp. Otherwise, we have to create it.
5359 /* oops, file shouldn't be there */
5360 cm_ReleaseSCache(dscp);
5361 cm_ReleaseSCache(scp);
5362 cm_ReleaseUser(userp);
5363 return CM_ERROR_EXISTS;
5366 setAttr.mask = CM_ATTRMASK_LENGTH;
5367 setAttr.length.LowPart = 0;
5368 setAttr.length.HighPart = 0;
5369 code = cm_SetAttr(scp, &setAttr, userp, &req);
5372 setAttr.mask = CM_ATTRMASK_CLIENTMODTIME;
5373 smb_UnixTimeFromDosUTime(&setAttr.clientModTime, dosTime);
5374 code = cm_Create(dscp, lastNamep, 0, &setAttr, &scp, userp,
5376 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
5377 smb_NotifyChange(FILE_ACTION_ADDED,
5378 FILE_NOTIFY_CHANGE_FILE_NAME,
5379 dscp, lastNamep, NULL, TRUE);
5380 if (!excl && code == CM_ERROR_EXISTS) {
5381 /* not an exclusive create, and someone else tried
5382 * creating it already, then we open it anyway. We
5383 * don't bother retrying after this, since if this next
5384 * fails, that means that the file was deleted after
5385 * we started this call.
5387 code = cm_Lookup(dscp, lastNamep, caseFold, userp,
5390 setAttr.mask = CM_ATTRMASK_LENGTH;
5391 setAttr.length.LowPart = 0;
5392 setAttr.length.HighPart = 0;
5393 code = cm_SetAttr(scp, &setAttr, userp, &req);
5398 /* we don't need this any longer */
5399 cm_ReleaseSCache(dscp);
5402 /* something went wrong creating or truncating the file */
5403 if (scp) cm_ReleaseSCache(scp);
5404 cm_ReleaseUser(userp);
5408 /* make sure we only open files */
5409 if (scp->fileType != CM_SCACHETYPE_FILE) {
5410 cm_ReleaseSCache(scp);
5411 cm_ReleaseUser(userp);
5412 return CM_ERROR_ISDIR;
5415 /* now all we have to do is open the file itself */
5416 fidp = smb_FindFID(vcp, 0, SMB_FLAG_CREATE);
5419 /* save a pointer to the vnode */
5422 /* always create it open for read/write */
5423 fidp->flags |= (SMB_FID_OPENREAD | SMB_FID_OPENWRITE);
5425 smb_ReleaseFID(fidp);
5427 smb_SetSMBParm(outp, 0, fidp->fid);
5428 smb_SetSMBDataLength(outp, 0);
5430 cm_Open(scp, 0, userp);
5432 cm_ReleaseUser(userp);
5433 /* leave scp held since we put it in fidp->scp */
5437 long smb_ReceiveCoreSeek(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5450 fd = smb_GetSMBParm(inp, 0);
5451 whence = smb_GetSMBParm(inp, 1);
5452 offset = smb_GetSMBParm(inp, 2) | (smb_GetSMBParm(inp, 3) << 16);
5454 /* try to find the file descriptor */
5455 fd = smb_ChainFID(fd, inp);
5456 fidp = smb_FindFID(vcp, fd, 0);
5457 if (!fidp || (fidp->flags & SMB_FID_IOCTL)) {
5458 return CM_ERROR_BADFD;
5461 userp = smb_GetUser(vcp, inp);
5463 lock_ObtainMutex(&fidp->mx);
5465 lock_ObtainMutex(&scp->mx);
5466 code = cm_SyncOp(scp, NULL, userp, &req, 0,
5467 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
5470 /* offset from current offset */
5471 offset += fidp->offset;
5473 else if (whence == 2) {
5474 /* offset from current EOF */
5475 offset += scp->length.LowPart;
5477 fidp->offset = offset;
5478 smb_SetSMBParm(outp, 0, offset & 0xffff);
5479 smb_SetSMBParm(outp, 1, (offset>>16) & 0xffff);
5480 smb_SetSMBDataLength(outp, 0);
5482 lock_ReleaseMutex(&scp->mx);
5483 lock_ReleaseMutex(&fidp->mx);
5484 smb_ReleaseFID(fidp);
5485 cm_ReleaseUser(userp);
5489 /* dispatch all of the requests received in a packet. Due to chaining, this may
5490 * be more than one request.
5492 void smb_DispatchPacket(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp,
5493 NCB *ncbp, raw_write_cont_t *rwcp)
5497 unsigned long code = 0;
5498 unsigned char *outWctp;
5499 int nparms; /* # of bytes of parameters */
5501 int nbytes; /* bytes of data, excluding count */
5504 unsigned short errCode;
5505 unsigned long NTStatus;
5507 unsigned char errClass;
5508 unsigned int oldGen;
5509 DWORD oldTime, newTime;
5511 /* get easy pointer to the data */
5512 smbp = (smb_t *) inp->data;
5514 if (!(outp->flags & SMB_PACKETFLAG_SUSPENDED)) {
5515 /* setup the basic parms for the initial request in the packet */
5516 inp->inCom = smbp->com;
5517 inp->wctp = &smbp->wct;
5519 inp->ncb_length = ncbp->ncb_length;
5524 if (ncbp->ncb_length < offsetof(struct smb, vdata)) {
5525 /* log it and discard it */
5530 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
5531 sprintf(s, "SMB message too short, len %d", ncbp->ncb_length);
5533 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1007, NULL,
5534 1, ncbp->ncb_length, ptbuf, inp);
5535 DeregisterEventSource(h);
5537 osi_Log1(smb_logp, "SMB message too short, len %d",
5544 /* We are an ongoing op */
5545 thrd_Increment(&ongoingOps);
5547 /* set up response packet for receiving output */
5548 if (!(outp->flags & SMB_PACKETFLAG_SUSPENDED))
5549 smb_FormatResponsePacket(vcp, inp, outp);
5550 outWctp = outp->wctp;
5552 /* Remember session generation number and time */
5553 oldGen = sessionGen;
5554 oldTime = GetCurrentTime();
5556 while(inp->inCom != 0xff) {
5557 dp = &smb_dispatchTable[inp->inCom];
5559 if (outp->flags & SMB_PACKETFLAG_SUSPENDED) {
5560 outp->flags &= ~SMB_PACKETFLAG_SUSPENDED;
5561 code = outp->resumeCode;
5565 /* process each request in the packet; inCom, wctp and inCount
5566 * are already set up.
5568 osi_Log2(smb_logp, "SMB received op 0x%x lsn %d", inp->inCom,
5571 /* now do the dispatch */
5572 /* start by formatting the response record a little, as a default */
5573 if (dp->flags & SMB_DISPATCHFLAG_CHAINED) {
5575 outWctp[1] = 0xff; /* no operation */
5576 outWctp[2] = 0; /* padding */
5581 /* not a chained request, this is a more reasonable default */
5582 outWctp[0] = 0; /* wct of zero */
5583 outWctp[1] = 0; /* and bcc (word) of zero */
5587 /* once set, stays set. Doesn't matter, since we never chain
5588 * "no response" calls.
5590 if (dp->flags & SMB_DISPATCHFLAG_NORESPONSE)
5594 /* we have a recognized operation */
5596 if (inp->inCom == 0x1d)
5598 code = smb_ReceiveCoreWriteRaw (vcp, inp, outp,
5601 osi_LogEvent("AFS Dispatch %s",(myCrt_Dispatch(inp->inCom)),"vcp[%x] lana[%d] lsn[%d]",(int)vcp,vcp->lana,vcp->lsn);
5602 osi_Log4(smb_logp,"Dispatch %s vcp[%x] lana[%d] lsn[%d]",(myCrt_Dispatch(inp->inCom)),vcp,vcp->lana,vcp->lsn);
5603 code = (*(dp->procp)) (vcp, inp, outp);
5604 osi_LogEvent("AFS Dispatch return",NULL,"Code[%d]",(code==0)?0:code-CM_ERROR_BASE);
5605 osi_Log1(smb_logp,"Dispatch return code[%d]",(code==0)?0:code-CM_ERROR_BASE);
5608 if (oldGen != sessionGen) {
5613 newTime = GetCurrentTime();
5614 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
5615 sprintf(s, "Pkt straddled session startup, took %d ms, ncb length %d",
5616 newTime - oldTime, ncbp->ncb_length);
5618 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0,
5619 1005, NULL, 1, ncbp->ncb_length, ptbuf, smbp);
5620 DeregisterEventSource(h);
5622 osi_Log1(smb_logp, "Pkt straddled session startup, "
5623 "ncb length %d", ncbp->ncb_length);
5628 /* bad opcode, fail the request, after displaying it */
5631 #endif /* NOTSERVICE */
5635 sprintf(tbuffer, "Received bad SMB req 0x%x", inp->inCom);
5636 code = (*smb_MBfunc)(NULL, tbuffer, "Cancel: don't show again",
5637 MB_OKCANCEL|MB_SERVICE_NOTIFICATION);
5638 if (code == IDCANCEL) showErrors = 0;
5641 code = CM_ERROR_BADOP;
5644 /* catastrophic failure: log as much as possible */
5645 if (code == CM_ERROR_BADSMB) {
5652 "Invalid SMB, ncb_length %d",
5655 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
5656 sprintf(s, "Invalid SMB message, length %d",
5659 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1002, NULL,
5660 1, ncbp->ncb_length, ptbuf, smbp);
5661 DeregisterEventSource(h);
5664 #endif /* NOTSERVICE */
5666 osi_Log1(smb_logp, "Invalid SMB message, length %d",
5670 code = CM_ERROR_INVAL;
5673 if (outp->flags & SMB_PACKETFLAG_NOSEND) {
5674 thrd_Decrement(&ongoingOps);
5679 /* now, if we failed, turn the current response into an empty
5680 * one, and fill in the response packet's error code.
5683 if (vcp->flags & SMB_VCFLAG_STATUS32) {
5684 smb_MapNTError(code, &NTStatus);
5685 outWctp = outp->wctp;
5686 smbp = (smb_t *) &outp->data;
5687 if (code != CM_ERROR_PARTIALWRITE
5688 && code != CM_ERROR_BUFFERTOOSMALL) {
5689 /* nuke wct and bcc. For a partial
5690 * write, assume they're OK.
5696 smbp->rcls = (unsigned char) (NTStatus & 0xff);
5697 smbp->reh = (unsigned char) ((NTStatus >> 8) & 0xff);
5698 smbp->errLow = (unsigned char) ((NTStatus >> 16) & 0xff);
5699 smbp->errHigh = (unsigned char) ((NTStatus >> 24) & 0xff);
5700 smbp->flg2 |= 0x4000;
5704 smb_MapCoreError(code, vcp, &errCode, &errClass);
5705 outWctp = outp->wctp;
5706 smbp = (smb_t *) &outp->data;
5707 if (code != CM_ERROR_PARTIALWRITE) {
5708 /* nuke wct and bcc. For a partial
5709 * write, assume they're OK.
5715 smbp->errLow = (unsigned char) (errCode & 0xff);
5716 smbp->errHigh = (unsigned char) ((errCode >> 8) & 0xff);
5717 smbp->rcls = errClass;
5720 } /* error occurred */
5722 /* if we're here, we've finished one request. Look to see if
5723 * this is a chained opcode. If it is, setup things to process
5724 * the chained request, and setup the output buffer to hold the
5725 * chained response. Start by finding the next input record.
5727 if (!(dp->flags & SMB_DISPATCHFLAG_CHAINED))
5728 break; /* not a chained req */
5729 tp = inp->wctp; /* points to start of last request */
5730 /* in a chained request, the first two
5731 * parm fields are required, and are
5732 * AndXCommand/AndXReserved and
5734 if (tp[0] < 2) break;
5735 if (tp[1] == 0xff) break; /* no more chained opcodes */
5737 inp->wctp = inp->data + tp[3] + (tp[4] << 8);
5740 /* and now append the next output request to the end of this
5741 * last request. Begin by finding out where the last response
5742 * ends, since that's where we'll put our new response.
5744 outWctp = outp->wctp; /* ptr to out parameters */
5745 osi_assert (outWctp[0] >= 2); /* need this for all chained requests */
5746 nparms = outWctp[0] << 1;
5747 tp = outWctp + nparms + 1; /* now points to bcc field */
5748 nbytes = tp[0] + (tp[1] << 8); /* # of data bytes */
5749 tp += 2 /* for the count itself */ + nbytes;
5750 /* tp now points to the new output record; go back and patch the
5751 * second parameter (off2) to point to the new record.
5753 temp = (unsigned int)tp - ((unsigned int) outp->data);
5754 outWctp[3] = (unsigned char) (temp & 0xff);
5755 outWctp[4] = (unsigned char) ((temp >> 8) & 0xff);
5756 outWctp[2] = 0; /* padding */
5757 outWctp[1] = inp->inCom; /* next opcode */
5759 /* finally, setup for the next iteration */
5762 } /* while loop over all requests in the packet */
5764 /* done logging out, turn off logging-out flag */
5765 if (!(inp->flags & SMB_PACKETFLAG_PROFILE_UPDATE_OK)) {
5766 vcp->justLoggedOut = NULL;
5769 free(loggedOutName);
5770 loggedOutName = NULL;
5771 smb_ReleaseUID(loggedOutUserp);
5772 loggedOutUserp = NULL;
5776 /* now send the output packet, and return */
5778 smb_SendPacket(vcp, outp);
5779 thrd_Decrement(&ongoingOps);
5781 if (!(vcp->flags & SMB_VCFLAG_ALREADYDEAD)) {
5783 last_msg_time = GetCurrentTime();
5785 else if (active_vcp == vcp)
5792 /* Wait for Netbios() calls to return, and make the results available to server
5793 * threads. Note that server threads can't wait on the NCBevents array
5794 * themselves, because NCB events are manual-reset, and the servers would race
5795 * each other to reset them.
5797 void smb_ClientWaiter(void *parmp)
5803 code = thrd_WaitForMultipleObjects_Event(numNCBs, NCBevents,
5805 if (code == WAIT_OBJECT_0)
5808 /* error checking */
5809 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numNCBs))
5811 int abandonIdx = code - WAIT_ABANDONED_0;
5812 afsi_log("Error: smb_ClientWaiter event %d abandoned, errno %d\n", abandonIdx, GetLastError());
5815 if (code == WAIT_IO_COMPLETION)
5817 afsi_log("Error: smb_ClientWaiter WAIT_IO_COMPLETION\n");
5821 if (code == WAIT_TIMEOUT)
5823 afsi_log("Error: smb_ClientWaiter WAIT_TIMEOUT, errno %d\n", GetLastError());
5826 if (code == WAIT_FAILED)
5828 afsi_log("Error: smb_ClientWaiter WAIT_FAILED, errno %d\n", GetLastError());
5831 idx = code - WAIT_OBJECT_0;
5833 /* check idx range! */
5834 if (idx < 0 || idx > (sizeof(NCBevents) / sizeof(NCBevents[0])))
5836 /* this is fatal - log as much as possible */
5837 afsi_log("Fatal: NCBevents idx [ %d ] out of range.\n", idx);
5841 thrd_ResetEvent(NCBevents[idx]);
5842 thrd_SetEvent(NCBreturns[0][idx]);
5848 * Try to have one NCBRECV request waiting for every live session. Not more
5849 * than one, because if there is more than one, it's hard to handle Write Raw.
5851 void smb_ServerWaiter(void *parmp)
5854 int idx_session, idx_NCB;
5862 code = thrd_WaitForMultipleObjects_Event(numSessions, SessionEvents,
5864 if (code == WAIT_OBJECT_0)
5867 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numSessions))
5869 int abandonIdx = code - WAIT_ABANDONED_0;
5870 afsi_log("Error: smb_ServerWaiter (SessionEvents) event %d abandoned, errno %d\n", abandonIdx, GetLastError());
5873 if (code == WAIT_IO_COMPLETION)
5875 afsi_log("Error: smb_ServerWaiter (SessionEvents) WAIT_IO_COMPLETION\n");
5879 if (code == WAIT_TIMEOUT)
5881 afsi_log("Error: smb_ServerWaiter (SessionEvents) WAIT_TIMEOUT, errno %d\n", GetLastError());
5884 if (code == WAIT_FAILED)
5886 afsi_log("Error: smb_ServerWaiter (SessionEvents) WAIT_FAILED, errno %d\n", GetLastError());
5889 idx_session = code - WAIT_OBJECT_0;
5891 /* check idx range! */
5892 if (idx_session < 0 || idx_session > (sizeof(SessionEvents) / sizeof(SessionEvents[0])))
5894 /* this is fatal - log as much as possible */
5895 afsi_log("Fatal: session idx [ %d ] out of range.\n", idx_session);
5901 code = thrd_WaitForMultipleObjects_Event(numNCBs, NCBavails,
5903 if (code == WAIT_OBJECT_0)
5906 /* error checking */
5907 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numNCBs))
5909 int abandonIdx = code - WAIT_ABANDONED_0;
5910 afsi_log("Error: smb_ClientWaiter (NCBavails) event %d abandoned, errno %d\n", abandonIdx, GetLastError());
5913 if (code == WAIT_IO_COMPLETION)
5915 afsi_log("Error: smb_ClientWaiter (NCBavails) WAIT_IO_COMPLETION\n");
5919 if (code == WAIT_TIMEOUT)
5921 afsi_log("Error: smb_ClientWaiter (NCBavails) WAIT_TIMEOUT, errno %d\n", GetLastError());
5924 if (code == WAIT_FAILED)
5926 afsi_log("Error: smb_ClientWaiter (NCBavails) WAIT_FAILED, errno %d\n", GetLastError());
5929 idx_NCB = code - WAIT_OBJECT_0;
5931 /* check idx range! */
5932 if (idx_NCB < 0 || idx_NCB > (sizeof(NCBsessions) / sizeof(NCBsessions[0])))
5934 /* this is fatal - log as much as possible */
5935 afsi_log("Fatal: idx_NCB [ %d ] out of range.\n", idx_NCB);
5939 /* Link them together */
5940 NCBsessions[idx_NCB] = idx_session;
5943 ncbp = NCBs[idx_NCB];
5945 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
5947 ncbp->ncb_lsn = (unsigned char) LSNs[idx_session];
5948 ncbp->ncb_command = NCBRECV | ASYNCH;
5949 ncbp->ncb_lana_num = lanas[idx_session];
5951 ncbp->ncb_buffer = (unsigned char *) bufs[idx_NCB];
5952 ncbp->ncb_event = NCBevents[idx_NCB];
5953 ncbp->ncb_length = SMB_PACKETSIZE;
5956 ncbp->ncb_buffer = bufs[idx_NCB]->dos_pkt;
5957 ((smb_ncb_t*)ncbp)->orig_pkt = bufs[idx_NCB];
5958 ncbp->ncb_event = NCBreturns[0][idx_NCB];
5959 ncbp->ncb_length = SMB_PACKETSIZE;
5960 Netbios(ncbp, dos_ncb);
5966 * The top level loop for handling SMB request messages. Each server thread
5967 * has its own NCB and buffer for sending replies (outncbp, outbufp), but the
5968 * NCB and buffer for the incoming request are loaned to us.
5970 * Write Raw trickery starts here. When we get a Write Raw, we are supposed
5971 * to immediately send a request for the rest of the data. This must come
5972 * before any other traffic for that session, so we delay setting the session
5973 * event until that data has come in.
5975 void smb_Server(VOID *parmp)
5977 int myIdx = (int) parmp;
5981 smb_packet_t *outbufp;
5983 int idx_NCB, idx_session;
5992 outbufp = GetPacket();
5993 outbufp->ncbp = outncbp;
5997 /* check for demo expiration */
5999 unsigned long tod = time((void *) 0);
6000 if (tod > EXPIREDATE) {
6001 (*smb_MBfunc)(NULL, "AFS demo expiration",
6003 MB_OK|MB_ICONSTOP|MB_SETFOREGROUND|MB_SERVICE_NOTIFICATION);
6007 #endif /* !NOEXPIRE */
6009 code = thrd_WaitForMultipleObjects_Event(numNCBs, NCBreturns[myIdx],
6011 if (code == WAIT_OBJECT_0) {
6015 /* error checking */
6016 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numNCBs))
6018 int abandonIdx = code - WAIT_ABANDONED_0;
6019 afsi_log("Error: smb_Server ( NCBreturns[%d] ) event %d abandoned, errno %d\n", myIdx, abandonIdx, GetLastError());
6022 if (code == WAIT_IO_COMPLETION)
6024 afsi_log("Error: smb_Server ( NCBreturns[%d] ) WAIT_IO_COMPLETION\n", myIdx);
6028 if (code == WAIT_TIMEOUT)
6030 afsi_log("Error: smb_Server ( NCBreturns[%d] ) WAIT_TIMEOUT, errno %d\n", myIdx, GetLastError());
6033 if (code == WAIT_FAILED)
6035 afsi_log("Error: smb_Server ( NCBreturns[%d] ) WAIT_FAILED, errno %d\n", myIdx, GetLastError());
6038 idx_NCB = code - WAIT_OBJECT_0;
6040 /* check idx range! */
6041 if (idx_NCB < 0 || idx_NCB > (sizeof(NCBs) / sizeof(NCBs[0])))
6043 /* this is fatal - log as much as possible */
6044 afsi_log("Fatal: idx_NCB [ %d ] out of range.\n", idx_NCB);
6048 ncbp = NCBs[idx_NCB];
6050 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6052 idx_session = NCBsessions[idx_NCB];
6053 rc = ncbp->ncb_retcode;
6055 if (rc != NRC_PENDING && rc != NRC_GOODRET)
6056 osi_Log1(smb_logp, "NCBRECV failure code %d", rc);
6059 case NRC_GOODRET: break;
6062 /* Can this happen? Or is it just my
6069 /* Client closed session */
6070 if (reportSessionStartups)
6072 afsi_log("session [ %d ] closed", idx_session);
6074 dead_sessions[idx_session] = TRUE;
6075 vcp = smb_FindVC(ncbp->ncb_lsn, 0, lanas[idx_session]);
6076 /* Should also release vcp. Also, would do
6077 * sanity check that all TID's are gone.
6079 * TODO: check if we could use LSNs[idx_session] instead,
6080 * also cleanup after dead vcp
6085 "dead_vcp already set, %x",
6087 if (!dead_vcp && !(vcp->flags & SMB_VCFLAG_ALREADYDEAD)) {
6089 "setting dead_vcp %x, user struct %x",
6092 vcp->flags |= SMB_VCFLAG_ALREADYDEAD;
6094 if (vcp->justLoggedOut) {
6096 loggedOutTime = vcp->logoffTime;
6098 strdup(vcp->justLoggedOut->unp->name);
6099 loggedOutUserp = vcp->justLoggedOut;
6100 lock_ObtainWrite(&smb_rctLock);
6101 loggedOutUserp->refCount++;
6102 lock_ReleaseWrite(&smb_rctLock);
6108 /* Treat as transient error */
6115 osi_Log1(smb_logp, "dispatch smb recv failed, message incomplete, ncb_length %d",
6117 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
6118 sprintf(s, "SMB message incomplete, length %d",
6121 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0,
6123 ncbp->ncb_length, ptbuf,
6125 DeregisterEventSource(h);
6128 "dispatch smb recv failed, message incomplete, ncb_length %d",
6131 "SMB message incomplete, "
6132 "length %d", ncbp->ncb_length);
6136 * We used to discard the packet.
6137 * Instead, try handling it normally.
6145 /* A weird error code. Log it, sleep, and
6147 if (vcp->errorCount++ > 3) {
6148 afsi_log("session [ %d ] closed, vcp->errorCount = %d", idx_session, vcp->errorCount);
6149 dead_sessions[idx_session] = TRUE;
6153 thrd_SetEvent(SessionEvents[idx_session]);
6158 /* Success, so now dispatch on all the data in the packet */
6160 smb_concurrentCalls++;
6161 if (smb_concurrentCalls > smb_maxObsConcurrentCalls)
6162 smb_maxObsConcurrentCalls = smb_concurrentCalls;
6164 vcp = smb_FindVC(ncbp->ncb_lsn, 0, ncbp->ncb_lana_num);
6166 * If at this point vcp is NULL (implies that packet was invalid)
6167 * then we are in big trouble. This means either :
6168 * a) we have the wrong NCB.
6169 * b) Netbios screwed up the call.
6170 * Obviously this implies that
6171 * ( LSNs[idx_session] != ncbp->ncb_lsn ||
6172 * lanas[idx_session] != ncbp->ncb_lana_num )
6173 * Either way, we can't do anything with this packet.
6174 * Log, sleep and resume.
6183 "LSNs[idx_session]=[%d],"
6184 "lanas[idx_session]=[%d],"
6185 "ncbp->ncb_lsn=[%d],"
6186 "ncbp->ncb_lana_num=[%d]",
6190 ncbp->ncb_lana_num);
6194 h = RegisterEventSource(NULL,AFS_DAEMON_EVENT_NAME);
6196 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1001, NULL,1,sizeof(*ncbp),ptbuf,(void*)ncbp);
6197 DeregisterEventSource(h);
6200 /* Also log in the trace log. */
6201 osi_Log4(smb_logp, "Server: BAD VCP!"
6202 "LSNs[idx_session]=[%d],"
6203 "lanas[idx_session]=[%d],"
6204 "ncbp->ncb_lsn=[%d],"
6205 "ncbp->ncb_lana_num=[%d]",
6209 ncbp->ncb_lana_num);
6211 /* thrd_Sleep(1000); Don't bother sleeping */
6212 thrd_SetEvent(SessionEvents[idx_session]);
6213 smb_concurrentCalls--;
6218 vcp->errorCount = 0;
6219 bufp = (struct smb_packet *) ncbp->ncb_buffer;
6221 bufp = ((smb_ncb_t *) ncbp)->orig_pkt;
6222 /* copy whole packet to virtual memory */
6223 /*fprintf(stderr, "smb_Server: copying dos packet at 0x%x, "
6225 bufp->dos_pkt / 16, bufp);*/
6227 dosmemget(bufp->dos_pkt, ncbp->ncb_length, bufp->data);
6229 smbp = (smb_t *)bufp->data;
6232 #if !defined(DJGPP) && !defined(AFS_WIN32_ENV)
6236 if (smbp->com == 0x1d) {
6237 /* Special handling for Write Raw */
6238 raw_write_cont_t rwc;
6239 EVENT_HANDLE rwevent;
6240 char eventName[MAX_PATH];
6242 smb_DispatchPacket(vcp, bufp, outbufp, ncbp, &rwc);
6243 if (rwc.code == 0) {
6244 rwevent = thrd_CreateEvent(NULL, FALSE, FALSE, TEXT("smb_Server() rwevent"));
6245 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6246 afsi_log("Event Object Already Exists: %s", eventName);
6247 ncbp->ncb_command = NCBRECV | ASYNCH;
6248 ncbp->ncb_lsn = (unsigned char) vcp->lsn;
6249 ncbp->ncb_lana_num = vcp->lana;
6250 ncbp->ncb_buffer = rwc.buf;
6251 ncbp->ncb_length = 65535;
6252 ncbp->ncb_event = rwevent;
6256 Netbios(ncbp, dos_ncb);
6258 rcode = thrd_WaitForSingleObject_Event(rwevent, RAWTIMEOUT);
6259 thrd_CloseHandle(rwevent);
6261 thrd_SetEvent(SessionEvents[idx_session]);
6263 smb_CompleteWriteRaw(vcp, bufp, outbufp, ncbp, &rwc);
6264 } else if (smbp->com == 0xa0) {
6266 * Serialize the handling for NT Transact
6269 smb_DispatchPacket(vcp, bufp, outbufp, ncbp, NULL);
6270 thrd_SetEvent(SessionEvents[idx_session]);
6272 thrd_SetEvent(SessionEvents[idx_session]);
6273 /* TODO: what else needs to be serialized? */
6274 smb_DispatchPacket(vcp, bufp, outbufp, ncbp, NULL);
6276 #if !defined(DJGPP) && !defined(AFS_WIN95_ENV)
6278 __except( smb_ServerExceptionFilter() ) {
6282 smb_concurrentCalls--;
6285 thrd_SetEvent(NCBavails[idx_NCB]);
6290 * Exception filter for the server threads. If an exception occurs in the
6291 * dispatch routines, which is where exceptions are most common, then do a
6292 * force trace and give control to upstream exception handlers. Useful for
6295 #if !defined(DJGPP) && !defined(AFS_WIN95_ENV)
6296 DWORD smb_ServerExceptionFilter(void) {
6297 /* While this is not the best time to do a trace, if it succeeds, then
6298 * we have a trace (assuming tracing was enabled). Otherwise, this should
6299 * throw a second exception.
6304 ptbuf[0] = "Unhandled exception forcing trace";
6306 h = RegisterEventSource(NULL,AFS_DAEMON_EVENT_NAME);
6308 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1001, NULL,1,0,ptbuf,NULL);
6309 DeregisterEventSource(h);
6312 afsd_ForceTrace(TRUE);
6313 return EXCEPTION_CONTINUE_SEARCH;
6318 * Create a new NCB and associated events, packet buffer, and "space" buffer.
6319 * If the number of server threads is M, and the number of live sessions is
6320 * N, then the number of NCB's in use at any time either waiting for, or
6321 * holding, received messages is M + N, so that is how many NCB's get created.
6323 void InitNCBslot(int idx)
6325 struct smb_packet *bufp;
6326 EVENT_HANDLE retHandle;
6328 char eventName[MAX_PATH];
6330 osi_assert( idx < (sizeof(NCBs) / sizeof(NCBs[0])) );
6332 NCBs[idx] = GetNCB();
6333 sprintf(eventName,"NCBavails[%d]", idx);
6334 NCBavails[idx] = thrd_CreateEvent(NULL, FALSE, TRUE, eventName);
6335 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6336 afsi_log("Event Object Already Exists: %s", eventName);
6338 sprintf(eventName,"NCBevents[%d]", idx);
6339 NCBevents[idx] = thrd_CreateEvent(NULL, TRUE, FALSE, eventName);
6340 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6341 afsi_log("Event Object Already Exists: %s", eventName);
6343 sprintf(eventName,"NCBReturns[0<=i<smb_NumServerThreads][%d]", idx);
6344 retHandle = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6345 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6346 afsi_log("Event Object Already Exists: %s", eventName);
6347 for (i=0; i<smb_NumServerThreads; i++)
6348 NCBreturns[i][idx] = retHandle;
6350 bufp->spacep = cm_GetSpace();
6354 /* listen for new connections */
6355 void smb_Listener(void *parmp)
6363 char rname[NCBNAMSZ+1];
6364 char cname[MAX_COMPUTERNAME_LENGTH+1];
6365 int cnamelen = MAX_COMPUTERNAME_LENGTH+1;
6370 int lana = (int) parmp;
6374 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6377 /* retrieve computer name */
6378 GetComputerName(cname, &cnamelen);
6382 memset(ncbp, 0, sizeof(NCB));
6386 /* check for demo expiration */
6388 unsigned long tod = time((void *) 0);
6389 if (tod > EXPIREDATE) {
6390 (*smb_MBfunc)(NULL, "AFS demo expiration",
6392 MB_OK|MB_ICONSTOP|MB_SETFOREGROUND|MB_SERVICE_NOTIFICATION);
6400 #endif /* !NOEXPIRE */
6402 ncbp->ncb_command = NCBLISTEN;
6403 ncbp->ncb_rto = 0; /* No receive timeout */
6404 ncbp->ncb_sto = 0; /* No send timeout */
6406 /* pad out with spaces instead of null termination */
6407 len = strlen(smb_localNamep);
6408 strncpy(ncbp->ncb_name, smb_localNamep, NCBNAMSZ);
6409 for(i=len; i<NCBNAMSZ; i++) ncbp->ncb_name[i] = ' ';
6411 strcpy(ncbp->ncb_callname, "*");
6412 for(i=1; i<NCBNAMSZ; i++) ncbp->ncb_callname[i] = ' ';
6414 ncbp->ncb_lana_num = lana;
6417 code = Netbios(ncbp);
6419 code = Netbios(ncbp, dos_ncb);
6428 /* terminate silently if shutdown flag is set */
6429 if (smbShutdownFlag == 1) {
6438 "NCBLISTEN lana=%d failed with code %d",
6439 ncbp->ncb_lana_num, code);
6441 "Client exiting due to network failure. Please restart client.\n");
6445 "Client exiting due to network failure. Please restart client.\n"
6446 "NCBLISTEN lana=%d failed with code %d",
6447 ncbp->ncb_lana_num, code);
6449 code = (*smb_MBfunc)(NULL, tbuffer, "AFS Client Service: Fatal Error",
6450 MB_OK|MB_SERVICE_NOTIFICATION);
6451 osi_assert(tbuffer);
6454 fprintf(stderr, "NCBLISTEN lana=%d failed with code %d\n",
6455 ncbp->ncb_lana_num, code);
6456 fprintf(stderr, "\nClient exiting due to network failure "
6457 "(possibly due to power-saving mode)\n");
6458 fprintf(stderr, "Please restart client.\n");
6459 afs_exit(AFS_EXITCODE_NETWORK_FAILURE);
6463 /* check for remote conns */
6464 /* first get remote name and insert null terminator */
6465 memcpy(rname, ncbp->ncb_callname, NCBNAMSZ);
6466 for (i=NCBNAMSZ; i>0; i--) {
6467 if (rname[i-1] != ' ' && rname[i-1] != 0) {
6473 /* compare with local name */
6475 if (strncmp(rname, cname, NCBNAMSZ) != 0)
6476 flags |= SMB_VCFLAG_REMOTECONN;
6478 osi_Log1(smb_logp, "New session lsn %d", ncbp->ncb_lsn);
6480 lock_ObtainMutex(&smb_ListenerLock);
6482 /* New generation */
6485 /* Log session startup */
6487 fprintf(stderr, "New session(ncb_lsn,ncb_lana_num) %d,%d starting from host "
6489 ncbp->ncb_lsn,ncbp->ncb_lana_num, rname);
6491 afsi_log("New session(ncb_lsn,ncb_lana_num) (%d,%d) starting from host %s, %d ongoing ops",
6492 ncbp->ncb_lsn,ncbp->ncb_lana_num, rname, ongoingOps);
6494 if (reportSessionStartups) {
6500 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
6501 sprintf(s, "SMB session startup, %d ongoing ops", ongoingOps);
6503 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1004, NULL,
6505 DeregisterEventSource(h);
6507 afsi_log("NCBLISTEN completed, call from %s",rname);
6508 osi_Log1(smb_logp, "SMB session startup, %d ongoing ops",
6511 fprintf(stderr, "%s: New session %d starting from host %s\n",
6512 asctime(localtime(&now)), ncbp->ncb_lsn, rname);
6517 /* now ncbp->ncb_lsn is the connection ID */
6518 vcp = smb_FindVC(ncbp->ncb_lsn, SMB_FLAG_CREATE, ncbp->ncb_lana_num);
6519 vcp->flags |= flags;
6520 strcpy(vcp->rname, rname);
6522 /* Allocate slot in session arrays */
6523 /* Re-use dead session if possible, otherwise add one more */
6524 /* But don't look at session[0], it is reserved */
6525 for (i = 1; i < numSessions; i++) {
6526 if (dead_sessions[i]) {
6527 afsi_log("connecting to dead session [ %d ]", i);
6528 dead_sessions[i] = FALSE;
6533 /* assert that we do not exceed the maximum number of sessions or NCBs.
6534 * we should probably want to wait for a session to be freed in case
6538 osi_assert(i < Sessionmax && numNCBs < NCBmax - 1);
6540 LSNs[i] = ncbp->ncb_lsn;
6541 lanas[i] = ncbp->ncb_lana_num;
6543 if (i == numSessions) {
6544 /* Add new NCB for new session */
6545 char eventName[MAX_PATH];
6547 osi_Log1(smb_logp, "smb_Listener creating new session %d", i);
6549 InitNCBslot(numNCBs);
6551 thrd_SetEvent(NCBavails[0]);
6552 thrd_SetEvent(NCBevents[0]);
6553 for (j = 0; j < smb_NumServerThreads; j++)
6554 thrd_SetEvent(NCBreturns[j][0]);
6555 /* Also add new session event */
6556 sprintf(eventName, "SessionEvents[%d]", i);
6557 SessionEvents[i] = thrd_CreateEvent(NULL, FALSE, TRUE, eventName);
6558 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6559 afsi_log("Event Object Already Exists: %s", eventName);
6561 afsi_log("increasing numNCBs [ %d ] numSessions [ %d ]", numNCBs, numSessions);
6562 thrd_SetEvent(SessionEvents[0]);
6564 thrd_SetEvent(SessionEvents[i]);
6567 lock_ReleaseMutex(&smb_ListenerLock);
6569 } /* dispatch while loop */
6572 /* initialize Netbios */
6573 void smb_NetbiosInit()
6579 int i, lana, code, l;
6581 int delname_tried=0;
6584 OSVERSIONINFO Version;
6586 /* AFAIK, this is the default for the ms loopback adapter.*/
6587 unsigned char kWLA_MAC[6] = { 0x02, 0x00, 0x4c, 0x4f, 0x4f, 0x50 };
6588 /*******************************************************************/
6590 /* Get the version of Windows */
6591 memset(&Version, 0x00, sizeof(Version));
6592 Version.dwOSVersionInfoSize = sizeof(Version);
6593 GetVersionEx(&Version);
6595 /* setup the NCB system */
6598 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6602 if (smb_LANadapter == -1) {
6603 ncbp->ncb_command = NCBENUM;
6604 ncbp->ncb_buffer = (PUCHAR)&lana_list;
6605 ncbp->ncb_length = sizeof(lana_list);
6606 code = Netbios(ncbp);
6608 sprintf(s, "Netbios NCBENUM error code %d", code);
6610 osi_panic(s, __FILE__, __LINE__);
6614 lana_list.length = 1;
6615 lana_list.lana[0] = smb_LANadapter;
6618 for (i = 0; i < lana_list.length; i++) {
6619 /* reset the adaptor: in Win32, this is required for every process, and
6620 * acts as an init call, not as a real hardware reset.
6622 ncbp->ncb_command = NCBRESET;
6623 ncbp->ncb_callname[0] = 100;
6624 ncbp->ncb_callname[2] = 100;
6625 ncbp->ncb_lana_num = lana_list.lana[i];
6626 code = Netbios(ncbp);
6628 code = ncbp->ncb_retcode;
6630 sprintf(s, "Netbios NCBRESET lana %d error code %d", lana_list.lana[i], code);
6632 lana_list.lana[i] = 255; /* invalid lana */
6634 sprintf(s, "Netbios NCBRESET lana %d succeeded", lana_list.lana[i]);
6639 /* for DJGPP, there is no NCBENUM and NCBRESET is a real reset. so
6640 we will just fake the LANA list */
6641 if (smb_LANadapter == -1) {
6642 for (i = 0; i < 8; i++)
6643 lana_list.lana[i] = i;
6644 lana_list.length = 8;
6647 lana_list.length = 1;
6648 lana_list.lana[0] = smb_LANadapter;
6652 /* and declare our name so we can receive connections */
6653 memset(ncbp, 0, sizeof(*ncbp));
6654 len=lstrlen(smb_localNamep);
6655 memset(smb_sharename,' ',NCBNAMSZ);
6656 memcpy(smb_sharename,smb_localNamep,len);
6657 sprintf(s, "lana_list.length %d", lana_list.length);
6660 /* Keep the name so we can unregister it later */
6661 for (l = 0; l < lana_list.length; l++) {
6662 lana = lana_list.lana[l];
6664 ncbp->ncb_command = NCBADDNAME;
6665 ncbp->ncb_lana_num = lana;
6666 memcpy(ncbp->ncb_name,smb_sharename,NCBNAMSZ);
6668 code = Netbios(ncbp);
6670 code = Netbios(ncbp, dos_ncb);
6673 afsi_log("Netbios NCBADDNAME lana=%d code=%d retcode=%d complete=%d",
6674 lana, code, ncbp->ncb_retcode,ncbp->ncb_cmd_cplt);
6676 char name[NCBNAMSZ+1];
6678 memcpy(name,ncbp->ncb_name,NCBNAMSZ);
6679 afsi_log("Netbios NCBADDNAME added new name >%s<",name);
6682 if (code == 0) code = ncbp->ncb_retcode;
6684 afsi_log("Netbios NCBADDNAME succeeded on lana %d\n", lana);
6686 /* we only use one LANA with djgpp */
6687 lana_list.lana[0] = lana;
6688 lana_list.length = 1;
6692 sprintf(s, "Netbios NCBADDNAME lana %d error code %d", lana, code);
6694 if (code == NRC_BRIDGE) { /* invalid LANA num */
6695 lana_list.lana[l] = 255;
6698 else if (code == NRC_DUPNAME) {
6699 afsi_log("Name already exists; try to delete it");
6700 memset(ncbp, 0, sizeof(*ncbp));
6701 ncbp->ncb_command = NCBDELNAME;
6702 memcpy(ncbp->ncb_name,smb_sharename,NCBNAMSZ);
6703 ncbp->ncb_lana_num = lana;
6705 code = Netbios(ncbp);
6707 code = Netbios(ncbp, dos_ncb);
6709 if (code == 0) code = ncbp->ncb_retcode;
6711 sprintf(s, "Netbios NCBDELNAME lana %d error code %d\n", lana, code);
6714 if (code != 0 || delname_tried) {
6715 lana_list.lana[l] = 255;
6717 else if (code == 0) {
6718 if (!delname_tried) {
6726 sprintf(s, "Netbios NCBADDNAME lana %d error code %d", lana, code);
6728 lana_list.lana[l] = 255; /* invalid lana */
6729 osi_panic(s, __FILE__, __LINE__);
6733 lana_found = 1; /* at least one worked */
6740 osi_assert(lana_list.length >= 0);
6742 sprintf(s, "No valid LANA numbers found!");
6743 osi_panic(s, __FILE__, __LINE__);
6746 /* we're done with the NCB now */
6750 void smb_Init(osi_log_t *logp, char *snamep, int useV3, int LANadapt,
6767 EVENT_HANDLE retHandle;
6768 char eventName[MAX_PATH];
6771 smb_MBfunc = aMBfunc;
6775 /* check for demo expiration */
6777 unsigned long tod = time((void *) 0);
6778 if (tod > EXPIREDATE) {
6780 (*smb_MBfunc)(NULL, "AFS demo expiration", "afsd",
6781 MB_OK|MB_ICONSTOP|MB_SETFOREGROUND|MB_SERVICE_NOTIFICATION);
6784 fprintf(stderr, "AFS demo expiration\n");
6789 #endif /* !NOEXPIRE */
6792 smb_LANadapter = LANadapt;
6794 /* Initialize smb_localZero */
6795 myTime.tm_isdst = -1; /* compute whether on DST or not */
6796 myTime.tm_year = 70;
6802 smb_localZero = mktime(&myTime);
6804 /* Initialize kludge-GMT */
6805 smb_CalculateNowTZ();
6807 /* initialize the remote debugging log */
6810 /* remember the name */
6811 len = strlen(snamep);
6812 smb_localNamep = malloc(len+1);
6813 strcpy(smb_localNamep, snamep);
6814 afsi_log("smb_localNamep is >%s<", smb_localNamep);
6816 /* and the global lock */
6817 lock_InitializeRWLock(&smb_globalLock, "smb global lock");
6818 lock_InitializeRWLock(&smb_rctLock, "smb refct and tree struct lock");
6820 /* Raw I/O data structures */
6821 lock_InitializeMutex(&smb_RawBufLock, "smb raw buffer lock");
6823 lock_InitializeMutex(&smb_ListenerLock, "smb listener lock");
6825 /* 4 Raw I/O buffers */
6827 smb_RawBufs = calloc(65536,1);
6828 *((char **)smb_RawBufs) = NULL;
6829 for (i=0; i<3; i++) {
6830 char *rawBuf = calloc(65536,1);
6831 *((char **)rawBuf) = smb_RawBufs;
6832 smb_RawBufs = rawBuf;
6835 npar = 65536 >> 4; /* number of paragraphs */
6836 seg = __dpmi_allocate_dos_memory(npar, &smb_RawBufSel[0]);
6838 afsi_log("Cannot allocate %d paragraphs of DOS memory",
6840 osi_panic("",__FILE__,__LINE__);
6843 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X",
6846 smb_RawBufs = (seg * 16) + 0; /* DOS physical address */
6848 _farpokel(_dos_ds, smb_RawBufs, NULL);
6849 for (i=0; i<SMB_RAW_BUFS-1; i++) {
6850 npar = 65536 >> 4; /* number of paragraphs */
6851 seg = __dpmi_allocate_dos_memory(npar, &smb_RawBufSel[i+1]);
6853 afsi_log("Cannot allocate %d paragraphs of DOS memory",
6855 osi_panic("",__FILE__,__LINE__);
6858 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X",
6861 rawBuf = (seg * 16) + 0; /* DOS physical address */
6862 /*_farpokel(_dos_ds, smb_RawBufs, smb_RawBufs);*/
6863 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
6864 smb_RawBufs = rawBuf;
6868 /* global free lists */
6869 smb_ncbFreeListp = NULL;
6870 smb_packetFreeListp = NULL;
6874 /* Initialize listener and server structures */
6875 memset(dead_sessions, 0, sizeof(dead_sessions));
6876 sprintf(eventName, "SessionEvents[0]");
6877 SessionEvents[0] = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6878 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6879 afsi_log("Event Object Already Exists: %s", eventName);
6881 smb_NumServerThreads = nThreads;
6882 sprintf(eventName, "NCBavails[0]");
6883 NCBavails[0] = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6884 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6885 afsi_log("Event Object Already Exists: %s", eventName);
6886 sprintf(eventName, "NCBevents[0]");
6887 NCBevents[0] = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6888 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6889 afsi_log("Event Object Already Exists: %s", eventName);
6890 NCBreturns = malloc(nThreads * sizeof(EVENT_HANDLE *));
6891 sprintf(eventName, "NCBreturns[0<=i<smb_NumServerThreads][0]");
6892 retHandle = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6893 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6894 afsi_log("Event Object Already Exists: %s", eventName);
6895 for (i = 0; i < smb_NumServerThreads; i++) {
6896 NCBreturns[i] = malloc(NCBmax * sizeof(EVENT_HANDLE));
6897 NCBreturns[i][0] = retHandle;
6899 for (i = 1; i <= nThreads; i++)
6901 numNCBs = nThreads + 1;
6903 /* Initialize dispatch table */
6904 memset(&smb_dispatchTable, 0, sizeof(smb_dispatchTable));
6905 smb_dispatchTable[0x00].procp = smb_ReceiveCoreMakeDir;
6906 smb_dispatchTable[0x01].procp = smb_ReceiveCoreRemoveDir;
6907 smb_dispatchTable[0x02].procp = smb_ReceiveCoreOpen;
6908 smb_dispatchTable[0x03].procp = smb_ReceiveCoreCreate;
6909 smb_dispatchTable[0x04].procp = smb_ReceiveCoreClose;
6910 smb_dispatchTable[0x05].procp = smb_ReceiveCoreFlush;
6911 smb_dispatchTable[0x06].procp = smb_ReceiveCoreUnlink;
6912 smb_dispatchTable[0x07].procp = smb_ReceiveCoreRename;
6913 smb_dispatchTable[0x08].procp = smb_ReceiveCoreGetFileAttributes;
6914 smb_dispatchTable[0x09].procp = smb_ReceiveCoreSetFileAttributes;
6915 smb_dispatchTable[0x0a].procp = smb_ReceiveCoreRead;
6916 smb_dispatchTable[0x0b].procp = smb_ReceiveCoreWrite;
6917 smb_dispatchTable[0x0c].procp = smb_ReceiveCoreLockRecord;
6918 smb_dispatchTable[0x0d].procp = smb_ReceiveCoreUnlockRecord;
6919 smb_dispatchTable[0x0e].procp = smb_SendCoreBadOp; /* create temporary */
6920 smb_dispatchTable[0x0f].procp = smb_ReceiveCoreCreate;
6921 smb_dispatchTable[0x10].procp = smb_ReceiveCoreCheckPath;
6922 smb_dispatchTable[0x11].procp = smb_SendCoreBadOp; /* process exit */
6923 smb_dispatchTable[0x12].procp = smb_ReceiveCoreSeek;
6924 smb_dispatchTable[0x1a].procp = smb_ReceiveCoreReadRaw;
6925 /* Set NORESPONSE because smb_ReceiveCoreReadRaw() does the responses itself */
6926 smb_dispatchTable[0x1a].flags |= SMB_DISPATCHFLAG_NORESPONSE;
6927 smb_dispatchTable[0x1d].procp = smb_ReceiveCoreWriteRawDummy;
6928 smb_dispatchTable[0x22].procp = smb_ReceiveV3SetAttributes;
6929 smb_dispatchTable[0x23].procp = smb_ReceiveV3GetAttributes;
6930 smb_dispatchTable[0x24].procp = smb_ReceiveV3LockingX;
6931 smb_dispatchTable[0x24].flags |= SMB_DISPATCHFLAG_CHAINED;
6932 smb_dispatchTable[0x29].procp = smb_SendCoreBadOp; /* copy file */
6933 smb_dispatchTable[0x2b].procp = smb_ReceiveCoreEcho;
6934 /* Set NORESPONSE because smb_ReceiveCoreEcho() does the responses itself */
6935 smb_dispatchTable[0x2b].flags |= SMB_DISPATCHFLAG_NORESPONSE;
6936 smb_dispatchTable[0x2d].procp = smb_ReceiveV3OpenX;
6937 smb_dispatchTable[0x2d].flags |= SMB_DISPATCHFLAG_CHAINED;
6938 smb_dispatchTable[0x2e].procp = smb_ReceiveV3ReadX;
6939 smb_dispatchTable[0x2e].flags |= SMB_DISPATCHFLAG_CHAINED;
6940 smb_dispatchTable[0x32].procp = smb_ReceiveV3Tran2A; /* both are same */
6941 smb_dispatchTable[0x32].flags |= SMB_DISPATCHFLAG_NORESPONSE;
6942 smb_dispatchTable[0x33].procp = smb_ReceiveV3Tran2A;
6943 smb_dispatchTable[0x33].flags |= SMB_DISPATCHFLAG_NORESPONSE;
6944 smb_dispatchTable[0x34].procp = smb_ReceiveV3FindClose;
6945 smb_dispatchTable[0x35].procp = smb_ReceiveV3FindNotifyClose;
6946 smb_dispatchTable[0x70].procp = smb_ReceiveCoreTreeConnect;
6947 smb_dispatchTable[0x71].procp = smb_ReceiveCoreTreeDisconnect;
6948 smb_dispatchTable[0x72].procp = smb_ReceiveNegotiate;
6949 smb_dispatchTable[0x73].procp = smb_ReceiveV3SessionSetupX;
6950 smb_dispatchTable[0x73].flags |= SMB_DISPATCHFLAG_CHAINED;
6951 smb_dispatchTable[0x74].procp = smb_ReceiveV3UserLogoffX;
6952 smb_dispatchTable[0x74].flags |= SMB_DISPATCHFLAG_CHAINED;
6953 smb_dispatchTable[0x75].procp = smb_ReceiveV3TreeConnectX;
6954 smb_dispatchTable[0x75].flags |= SMB_DISPATCHFLAG_CHAINED;
6955 smb_dispatchTable[0x80].procp = smb_ReceiveCoreGetDiskAttributes;
6956 smb_dispatchTable[0x81].procp = smb_ReceiveCoreSearchDir;
6957 smb_dispatchTable[0xA0].procp = smb_ReceiveNTTransact;
6958 smb_dispatchTable[0xA2].procp = smb_ReceiveNTCreateX;
6959 smb_dispatchTable[0xA2].flags |= SMB_DISPATCHFLAG_CHAINED;
6960 smb_dispatchTable[0xA4].procp = smb_ReceiveNTCancel;
6961 smb_dispatchTable[0xA4].flags |= SMB_DISPATCHFLAG_NORESPONSE;
6962 smb_dispatchTable[0xc0].procp = smb_SendCoreBadOp;
6963 smb_dispatchTable[0xc1].procp = smb_SendCoreBadOp;
6964 smb_dispatchTable[0xc2].procp = smb_SendCoreBadOp;
6965 smb_dispatchTable[0xc3].procp = smb_SendCoreBadOp;
6966 for(i=0xd0; i<= 0xd7; i++) {
6967 smb_dispatchTable[i].procp = smb_SendCoreBadOp;
6970 /* setup tran 2 dispatch table */
6971 smb_tran2DispatchTable[0].procp = smb_ReceiveTran2Open;
6972 smb_tran2DispatchTable[1].procp = smb_ReceiveTran2SearchDir; /* FindFirst */
6973 smb_tran2DispatchTable[2].procp = smb_ReceiveTran2SearchDir; /* FindNext */
6974 smb_tran2DispatchTable[3].procp = smb_ReceiveTran2QFSInfo;
6975 smb_tran2DispatchTable[4].procp = smb_ReceiveTran2SetFSInfo;
6976 smb_tran2DispatchTable[5].procp = smb_ReceiveTran2QPathInfo;
6977 smb_tran2DispatchTable[6].procp = smb_ReceiveTran2SetPathInfo;
6978 smb_tran2DispatchTable[7].procp = smb_ReceiveTran2QFileInfo;
6979 smb_tran2DispatchTable[8].procp = smb_ReceiveTran2SetFileInfo;
6980 smb_tran2DispatchTable[9].procp = smb_ReceiveTran2FSCTL;
6981 smb_tran2DispatchTable[10].procp = smb_ReceiveTran2IOCTL;
6982 smb_tran2DispatchTable[11].procp = smb_ReceiveTran2FindNotifyFirst;
6983 smb_tran2DispatchTable[12].procp = smb_ReceiveTran2FindNotifyNext;
6984 smb_tran2DispatchTable[13].procp = smb_ReceiveTran2MKDir;
6988 /* Start listeners, waiters, servers, and daemons */
6990 for (i = 0; i < lana_list.length; i++) {
6991 if (lana_list.lana[i] == 255) continue;
6992 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_Listener,
6993 (void*)lana_list.lana[i], 0, &lpid, "smb_Listener");
6994 osi_assert(phandle != NULL);
6995 thrd_CloseHandle(phandle);
6999 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_ClientWaiter,
7000 NULL, 0, &lpid, "smb_ClientWaiter");
7001 osi_assert(phandle != NULL);
7002 thrd_CloseHandle(phandle);
7005 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_ServerWaiter,
7006 NULL, 0, &lpid, "smb_ServerWaiter");
7007 osi_assert(phandle != NULL);
7008 thrd_CloseHandle(phandle);
7010 for (i=0; i<nThreads; i++) {
7011 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_Server,
7012 (void *) i, 0, &lpid, "smb_Server");
7013 osi_assert(phandle != NULL);
7014 thrd_CloseHandle(phandle);
7017 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_Daemon,
7018 NULL, 0, &lpid, "smb_Daemon");
7019 osi_assert(phandle != NULL);
7020 thrd_CloseHandle(phandle);
7022 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_WaitingLocksDaemon,
7023 NULL, 0, &lpid, "smb_WaitingLocksDaemon");
7024 osi_assert(phandle != NULL);
7025 thrd_CloseHandle(phandle);
7034 void smb_Shutdown(void)
7043 /*fprintf(stderr, "Entering smb_Shutdown\n");*/
7045 /* setup the NCB system */
7048 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
7051 /* Block new sessions by setting shutdown flag */
7052 smbShutdownFlag = 1;
7054 /* Hang up all sessions */
7055 memset((char *)ncbp, 0, sizeof(NCB));
7056 for (i = 1; i < numSessions; i++)
7058 if (dead_sessions[i])
7061 /*fprintf(stderr, "NCBHANGUP session %d LSN %d\n", i, LSNs[i]);*/
7062 ncbp->ncb_command = NCBHANGUP;
7063 ncbp->ncb_lana_num = lanas[i]; /*smb_LANadapter;*/
7064 ncbp->ncb_lsn = LSNs[i];
7066 code = Netbios(ncbp);
7068 code = Netbios(ncbp, dos_ncb);
7070 /*fprintf(stderr, "returned from NCBHANGUP session %d LSN %d\n", i, LSNs[i]);*/
7071 if (code == 0) code = ncbp->ncb_retcode;
7073 osi_Log1(smb_logp, "Netbios NCBHANGUP error code %d", code);
7074 fprintf(stderr, "Session %d Netbios NCBHANGUP error code %d", i, code);
7078 /* Delete Netbios name */
7079 memset((char *)ncbp, 0, sizeof(NCB));
7080 for (i = 0; i < lana_list.length; i++) {
7081 if (lana_list.lana[i] == 255) continue;
7082 ncbp->ncb_command = NCBDELNAME;
7083 ncbp->ncb_lana_num = lana_list.lana[i];
7084 memcpy(ncbp->ncb_name,smb_sharename,NCBNAMSZ);
7086 code = Netbios(ncbp);
7088 code = Netbios(ncbp, dos_ncb);
7090 if (code == 0) code = ncbp->ncb_retcode;
7092 fprintf(stderr, "Netbios NCBDELNAME lana %d error code %d",
7093 ncbp->ncb_lana_num, code);
7099 /* Get the UNC \\<servername>\<sharename> prefix. */
7100 char *smb_GetSharename()
7104 /* Make sure we have been properly initialized. */
7105 if (smb_localNamep == NULL)
7108 /* Allocate space for \\<servername>\<sharename>, plus the
7111 name = malloc(strlen(smb_localNamep) + strlen("ALL") + 4);
7112 sprintf(name, "\\\\%s\\%s", smb_localNamep, "ALL");
7118 void smb_LogPacket(smb_packet_t *packet)
7121 unsigned length, paramlen, datalen, i, j;
7123 char hex[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
7127 osi_Log0(smb_logp, "*** SMB packet dump ***");
7129 vp = (BYTE *) packet->data;
7131 datalen = *((WORD*)(vp + (paramlen = ((unsigned)*(vp+20)) << 1)));
7132 length = paramlen + 2 + datalen;
7135 for(i=0;i < length; i+=16)
7137 memset( buf, ' ', 80 );
7142 buf[strlen(buf)] = ' ';
7144 cp = (BYTE*) buf + 7;
7146 for(j=0;j < 16 && (i+j)<length; j++)
7148 *(cp++) = hex[vp[i+j] >> 4];
7149 *(cp++) = hex[vp[i+j] & 0xf];
7159 for(j=0;j < 16 && (i+j)<length;j++)
7161 *(cp++) = ( 32 <= vp[i+j] && 128 > vp[i+j] )? vp[i+j]:'.';
7172 osi_Log0( smb_logp, buf );
7175 osi_Log0(smb_logp, "*** End SMB packet dump ***");
7179 #endif /* NOTSERVICE */
7181 int smb_DumpVCP(FILE *outputFile, char *cookie)
7188 lock_ObtainRead(&smb_rctLock);
7190 for(vcp = smb_allVCsp; vcp; vcp=vcp->nextp)
7194 sprintf(output, "%s vcp=0x%08X, refCount=%d, flags=%d, vcID=%d, lsn=%d, uidCounter=%d, tidCounter=%d, fidCounter=%d\n",
7195 cookie, vcp, vcp->refCount, vcp->flags, vcp->vcID, vcp->lsn, vcp->uidCounter, vcp->tidCounter, vcp->fidCounter);
7196 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7198 for(fidp = vcp->fidsp; fidp; fidp = (smb_fid_t *) osi_QNext(&fidp->q))
7200 sprintf(output, "%s -- fidp=0x%08X, refCount=%d, fid=%d, vcp=0x%08X, scp=0x%08X, ioctlp=0x%08X, NTopen_pathp=%s, NTopen_wholepathp=%s\n",
7201 cookie, fidp, fidp->refCount, fidp->fid, fidp->vcp, fidp->scp, fidp->ioctlp,
7202 fidp->NTopen_pathp ? fidp->NTopen_pathp : "NULL",
7203 fidp->NTopen_wholepathp ? fidp->NTopen_wholepathp : "NULL");
7204 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7207 sprintf(output, "done dumping fidsp\n");
7208 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7211 lock_ReleaseRead(&smb_rctLock);