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 /* MessageBox or something like it */
143 int (WINAPI *smb_MBfunc)(HWND, LPCTSTR, LPCTSTR, UINT) = NULL;
147 * Time in Unix format of midnight, 1/1/1970 local time.
148 * When added to dosUTime, gives Unix (AFS) time.
152 /* Time difference for converting to kludge-GMT */
155 char *smb_localNamep = NULL;
157 smb_vc_t *smb_allVCsp;
159 smb_username_t *usernamesp = NULL;
161 smb_waitingLock_t *smb_allWaitingLocks;
164 void smb_DispatchPacket(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp,
165 NCB *ncbp, raw_write_cont_t *rwcp);
166 void smb_NetbiosInit();
168 #ifndef AFS_WIN95_ENV
169 DWORD smb_ServerExceptionFilter(void);
172 extern char cm_HostName[];
173 extern char cm_confDir[];
177 #define LPTSTR char *
178 #define GetComputerName(str, sizep) \
179 strcpy((str), cm_HostName); \
180 *(sizep) = strlen(cm_HostName)
183 extern char AFSConfigKeyName[];
188 * To build an expiring version, comment out the definition of NOEXPIRE,
189 * and set the definition of EXPIREDATE to the desired value.
192 #define EXPIREDATE 834000000 /* Wed Jun 5 1996 */
195 char * myCrt_Dispatch(int i)
200 return "unknown SMB op";
202 return "(00)ReceiveCoreMakeDir";
204 return "(01)ReceiveCoreRemoveDir";
206 return "(02)ReceiveCoreOpen";
208 return "(03)ReceiveCoreCreate";
210 return "(04)ReceiveCoreClose";
212 return "(05)ReceiveCoreFlush";
214 return "(06)ReceiveCoreUnlink";
216 return "(07)ReceiveCoreRename";
218 return "(08)ReceiveCoreGetFileAttributes";
220 return "(09)ReceiveCoreSetFileAttributes";
222 return "(0a)ReceiveCoreRead";
224 return "(0b)ReceiveCoreWrite";
226 return "(0c)ReceiveCoreLockRecord";
228 return "(0d)ReceiveCoreUnlockRecord";
230 return "(0e)SendCoreBadOp";
232 return "(0f)ReceiveCoreCreate";
234 return "(10)ReceiveCoreCheckPath";
236 return "(11)SendCoreBadOp";
238 return "(12)ReceiveCoreSeek";
240 return "(1a)ReceiveCoreReadRaw";
242 return "(1d)ReceiveCoreWriteRawDummy";
244 return "(22)ReceiveV3SetAttributes";
246 return "(23)ReceiveV3GetAttributes";
248 return "(24)ReceiveV3LockingX";
250 return "(29)SendCoreBadOp";
252 return "(2b)ReceiveCoreEcho";
254 return "(2d)ReceiveV3OpenX";
256 return "(2e)ReceiveV3ReadX";
258 return "(32)ReceiveV3Tran2A";
260 return "(33)ReceiveV3Tran2A";
262 return "(34)ReceiveV3FindClose";
264 return "(35)ReceiveV3FindNotifyClose";
266 return "(70)ReceiveCoreTreeConnect";
268 return "(71)ReceiveCoreTreeDisconnect";
270 return "(72)ReceiveNegotiate";
272 return "(73)ReceiveV3SessionSetupX";
274 return "(74)ReceiveV3UserLogoffX";
276 return "(75)ReceiveV3TreeConnectX";
278 return "(80)ReceiveCoreGetDiskAttributes";
280 return "(81)ReceiveCoreSearchDir";
282 return "(A0)ReceiveNTTransact";
284 return "(A2)ReceiveNTCreateX";
286 return "(A4)ReceiveNTCancel";
288 return "(c0)SendCoreBadOp";
290 return "(c1)SendCoreBadOp";
292 return "(c2)SendCoreBadOp";
294 return "(c3)SendCoreBadOp";
298 char * myCrt_2Dispatch(int i)
303 return "unknown SMB op-2";
305 return "S(00)CreateFile";
307 return "S(01)FindFirst";
309 return "S(02)FindNext"; /* FindNext */
311 return "S(03)QueryFileSystem_ReceiveTran2QFSInfo";
315 return "S(05)QueryFileInfo_ReceiveTran2QPathInfo";
317 return "S(06)SetFileInfo_ReceiveTran2SetPathInfo";
319 return "S(07)SetInfoHandle_ReceiveTran2QFileInfo";
321 return "S(08)??_ReceiveTran2SetFileInfo";
323 return "S(09)??_ReceiveTran2FSCTL";
325 return "S(0a)_ReceiveTran2IOCTL";
327 return "S(0b)_ReceiveTran2FindNotifyFirst";
329 return "S(0c)_ReceiveTran2FindNotifyNext";
331 return "S(0d)CreateDirectory_ReceiveTran2MKDir";
335 /* scache must be locked */
336 unsigned int smb_Attributes(cm_scache_t *scp)
340 if (scp->fileType == CM_SCACHETYPE_DIRECTORY
341 || scp->fileType == CM_SCACHETYPE_MOUNTPOINT)
342 attrs = SMB_ATTR_DIRECTORY;
347 * We used to mark a file RO if it was in an RO volume, but that
348 * turns out to be impolitic in NT. See defect 10007.
351 if ((scp->unixModeBits & 0222) == 0 || (scp->flags & CM_SCACHEFLAG_RO))
353 if ((scp->unixModeBits & 0222) == 0)
354 attrs |= SMB_ATTR_READONLY; /* turn on read-only flag */
359 /* Check if the named file/dir is a dotfile/dotdir */
360 /* String pointed to by lastComp can have leading slashes, but otherwise should have
361 no other patch components */
362 unsigned int smb_IsDotFile(char *lastComp) {
365 /* skip over slashes */
366 for(s=lastComp;*s && (*s == '\\' || *s == '/'); s++);
371 /* nulls, curdir and parent dir doesn't count */
374 if(!*(s + 1)) return 0;
375 if(*(s+1) == '.' && !*(s + 2)) return 0;
381 static int ExtractBits(WORD bits, short start, short len)
388 num = bits << (16 - end);
389 num = num >> ((16 - end) + start);
395 void ShowUnixTime(char *FuncName, long unixTime)
400 smb_LargeSearchTimeFromUnixTime(&ft, unixTime);
402 if (!FileTimeToDosDateTime(&ft, &wDate, &wTime))
403 osi_Log1(afsd_logp, "Failed to convert filetime to dos datetime: %d", GetLastError());
405 int day, month, year, sec, min, hour;
408 day = ExtractBits(wDate, 0, 5);
409 month = ExtractBits(wDate, 5, 4);
410 year = ExtractBits(wDate, 9, 7) + 1980;
412 sec = ExtractBits(wTime, 0, 5);
413 min = ExtractBits(wTime, 5, 6);
414 hour = ExtractBits(wTime, 11, 5);
416 sprintf(msg, "%s = %02d-%02d-%04d %02d:%02d:%02d", FuncName, month, day, year, hour, min, sec);
417 osi_Log1(afsd_logp, "%s", osi_LogSaveString(afsd_logp, msg));
423 /* Determine if we are observing daylight savings time */
424 void GetTimeZoneInfo(BOOL *pDST, LONG *pDstBias, LONG *pBias)
426 TIME_ZONE_INFORMATION timeZoneInformation;
427 SYSTEMTIME utc, local, localDST;
429 /* Get the time zone info. NT uses this to calc if we are in DST. */
430 GetTimeZoneInformation(&timeZoneInformation);
432 /* Return the daylight bias */
433 *pDstBias = timeZoneInformation.DaylightBias;
435 /* Return the bias */
436 *pBias = timeZoneInformation.Bias;
438 /* Now determine if DST is being observed */
440 /* Get the UTC (GMT) time */
443 /* Convert UTC time to local time using the time zone info. If we are
444 observing DST, the calculated local time will include this.
446 SystemTimeToTzSpecificLocalTime(&timeZoneInformation, &utc, &localDST);
448 /* Set the daylight bias to 0. The daylight bias is the amount of change
449 in time that we use for daylight savings time. By setting this to 0
450 we cause there to be no change in time during daylight savings time.
452 timeZoneInformation.DaylightBias = 0;
454 /* Convert the utc time to local time again, but this time without any
455 adjustment for daylight savings time.
457 SystemTimeToTzSpecificLocalTime(&timeZoneInformation, &utc, &local);
459 /* If the two times are different, then it means that the localDST that
460 we calculated includes the daylight bias, and therefore we are
461 observing daylight savings time.
463 *pDST = localDST.wHour != local.wHour;
466 /* Determine if we are observing daylight savings time */
467 void GetTimeZoneInfo(BOOL *pDST, LONG *pDstBias, LONG *pBias)
473 *pDstBias = -60; /* where can this be different? */
479 void CompensateForSmbClientLastWriteTimeBugs(long *pLastWriteTime)
481 BOOL dst; /* Will be TRUE if observing DST */
482 LONG dstBias; /* Offset from local time if observing DST */
483 LONG bias; /* Offset from GMT for local time */
486 * This function will adjust the last write time to compensate
487 * for two bugs in the smb client:
489 * 1) During Daylight Savings Time, the LastWriteTime is ahead
490 * in time by the DaylightBias (ignoring the sign - the
491 * DaylightBias is always stored as a negative number). If
492 * the DaylightBias is -60, then the LastWriteTime will be
493 * ahead by 60 minutes.
495 * 2) If the local time zone is a positive offset from GMT, then
496 * the LastWriteTime will be the correct local time plus the
497 * Bias (ignoring the sign - a positive offset from GMT is
498 * always stored as a negative Bias). If the Bias is -120,
499 * then the LastWriteTime will be ahead by 120 minutes.
501 * These bugs can occur at the same time.
504 GetTimeZoneInfo(&dst, &dstBias, &bias);
506 /* First adjust for DST */
508 *pLastWriteTime -= (-dstBias * 60); /* Convert dstBias to seconds */
510 /* Now adjust for a positive offset from GMT (a negative bias). */
512 *pLastWriteTime -= (-bias * 60); /* Convert bias to seconds */
516 * Calculate the difference (in seconds) between local time and GMT.
517 * This enables us to convert file times to kludge-GMT.
523 struct tm gmt_tm, local_tm;
524 int days, hours, minutes, seconds;
527 gmt_tm = *(gmtime(&t));
528 local_tm = *(localtime(&t));
530 days = local_tm.tm_yday - gmt_tm.tm_yday;
531 hours = 24 * days + local_tm.tm_hour - gmt_tm.tm_hour - (local_tm.tm_isdst ? 1 : 0);
532 minutes = 60 * hours + local_tm.tm_min - gmt_tm.tm_min;
533 seconds = 60 * minutes + local_tm.tm_sec - gmt_tm.tm_sec;
539 void smb_LargeSearchTimeFromUnixTime(FILETIME *largeTimep, long unixTime)
544 long ersatz_unixTime;
547 * Must use kludge-GMT instead of real GMT.
548 * kludge-GMT is computed by adding time zone difference to localtime.
551 * ltp = gmtime(&unixTime);
553 ersatz_unixTime = unixTime - smb_NowTZ;
554 ltp = localtime(&ersatz_unixTime);
556 /* if we fail, make up something */
559 localJunk.tm_year = 89 - 20;
560 localJunk.tm_mon = 4;
561 localJunk.tm_mday = 12;
562 localJunk.tm_hour = 0;
563 localJunk.tm_min = 0;
564 localJunk.tm_sec = 0;
567 stm.wYear = ltp->tm_year + 1900;
568 stm.wMonth = ltp->tm_mon + 1;
569 stm.wDayOfWeek = ltp->tm_wday;
570 stm.wDay = ltp->tm_mday;
571 stm.wHour = ltp->tm_hour;
572 stm.wMinute = ltp->tm_min;
573 stm.wSecond = ltp->tm_sec;
574 stm.wMilliseconds = 0;
576 SystemTimeToFileTime(&stm, largeTimep);
579 void smb_LargeSearchTimeFromUnixTime(FILETIME *largeTimep, long unixTime)
581 /* unixTime: seconds since 1/1/1970 00:00:00 GMT */
582 /* FILETIME: 100ns intervals since 1/1/1601 00:00:00 ??? */
583 LARGE_INTEGER *ft = (LARGE_INTEGER *) largeTimep;
585 int leap_years = 89; /* leap years betw 1/1/1601 and 1/1/1970 */
587 /* set ft to number of 100ns intervals betw 1/1/1601 and 1/1/1970 GMT */
588 *ft = ConvertLongToLargeInteger(((EPOCH_YEAR-1601) * 365 + leap_years)
590 *ft = LargeIntegerMultiplyByLong(*ft, 60);
591 *ft = LargeIntegerMultiplyByLong(*ft, 10000000);
594 ut = ConvertLongToLargeInteger(unixTime);
595 ut = LargeIntegerMultiplyByLong(ut, 10000000);
596 *ft = LargeIntegerAdd(*ft, ut);
601 void smb_UnixTimeFromLargeSearchTime(long *unixTimep, FILETIME *largeTimep)
607 FileTimeToSystemTime(largeTimep, &stm);
609 lt.tm_year = stm.wYear - 1900;
610 lt.tm_mon = stm.wMonth - 1;
611 lt.tm_wday = stm.wDayOfWeek;
612 lt.tm_mday = stm.wDay;
613 lt.tm_hour = stm.wHour;
614 lt.tm_min = stm.wMinute;
615 lt.tm_sec = stm.wSecond;
618 save_timezone = _timezone;
619 _timezone += smb_NowTZ;
620 *unixTimep = mktime(<);
621 _timezone = save_timezone;
624 void smb_UnixTimeFromLargeSearchTime(long *unixTimep, FILETIME *largeTimep)
626 /* unixTime: seconds since 1/1/1970 00:00:00 GMT */
627 /* FILETIME: 100ns intervals since 1/1/1601 00:00:00 GMT? */
628 LARGE_INTEGER *ft = (LARGE_INTEGER *) largeTimep;
632 /* set to number of 100ns intervals betw 1/1/1601 and 1/1/1970 */
633 a = ConvertLongToLargeInteger(((EPOCH_YEAR-1601) * 365 + leap_years) * 24 * 60);
634 a = LargeIntegerMultiplyByLong(a, 60);
635 a = LargeIntegerMultiplyByLong(a, 10000000);
637 /* subtract it from ft */
638 a = LargeIntegerSubtract(*ft, a);
640 /* divide down to seconds */
641 *unixTimep = LargeIntegerDivideByLong(a, 10000000);
645 void smb_SearchTimeFromUnixTime(long *dosTimep, long unixTime)
652 ltp = localtime((time_t*) &unixTime);
654 /* if we fail, make up something */
657 localJunk.tm_year = 89 - 20;
658 localJunk.tm_mon = 4;
659 localJunk.tm_mday = 12;
660 localJunk.tm_hour = 0;
661 localJunk.tm_min = 0;
662 localJunk.tm_sec = 0;
665 dosDate = ((ltp->tm_year-80)<<9) | ((ltp->tm_mon+1) << 5) | (ltp->tm_mday);
666 dosTime = (ltp->tm_hour<<11) | (ltp->tm_min << 5) | (ltp->tm_sec / 2);
667 *dosTimep = (dosDate<<16) | dosTime;
670 void smb_UnixTimeFromSearchTime(long *unixTimep, long searchTime)
672 unsigned short dosDate;
673 unsigned short dosTime;
676 dosDate = searchTime & 0xffff;
677 dosTime = (searchTime >> 16) & 0xffff;
679 localTm.tm_year = 80 + ((dosDate>>9) & 0x3f);
680 localTm.tm_mon = ((dosDate >> 5) & 0xf) - 1; /* January is 0 in localTm */
681 localTm.tm_mday = (dosDate) & 0x1f;
682 localTm.tm_hour = (dosTime>>11) & 0x1f;
683 localTm.tm_min = (dosTime >> 5) & 0x3f;
684 localTm.tm_sec = (dosTime & 0x1f) * 2;
685 localTm.tm_isdst = -1; /* compute whether DST in effect */
687 *unixTimep = mktime(&localTm);
690 void smb_DosUTimeFromUnixTime(long *dosUTimep, long unixTime)
692 *dosUTimep = unixTime - smb_localZero;
695 void smb_UnixTimeFromDosUTime(long *unixTimep, long dosTime)
698 *unixTimep = dosTime + smb_localZero;
700 /* dosTime seems to be already adjusted for GMT */
701 *unixTimep = dosTime;
705 smb_vc_t *smb_FindVC(unsigned short lsn, int flags, int lana)
709 lock_ObtainWrite(&smb_rctLock);
710 for(vcp = smb_allVCsp; vcp; vcp=vcp->nextp) {
711 if (lsn == vcp->lsn && lana == vcp->lana) {
716 if (!vcp && (flags & SMB_FLAG_CREATE)) {
717 vcp = malloc(sizeof(*vcp));
718 memset(vcp, 0, sizeof(*vcp));
722 vcp->uidCounter = 1; /* UID 0 is reserved for blank user */
723 vcp->nextp = smb_allVCsp;
725 lock_InitializeMutex(&vcp->mx, "vc_t mutex");
729 lock_ReleaseWrite(&smb_rctLock);
733 int smb_IsStarMask(char *maskp)
738 for(i=0; i<11; i++) {
740 if (tc == '?' || tc == '*' || tc == '>') return 1;
745 void smb_ReleaseVC(smb_vc_t *vcp)
747 lock_ObtainWrite(&smb_rctLock);
748 osi_assert(vcp->refCount-- > 0);
749 lock_ReleaseWrite(&smb_rctLock);
752 void smb_HoldVC(smb_vc_t *vcp)
754 lock_ObtainWrite(&smb_rctLock);
756 lock_ReleaseWrite(&smb_rctLock);
759 smb_tid_t *smb_FindTID(smb_vc_t *vcp, unsigned short tid, int flags)
763 lock_ObtainWrite(&smb_rctLock);
764 for(tidp = vcp->tidsp; tidp; tidp = tidp->nextp) {
765 if (tid == tidp->tid) {
770 if (!tidp && (flags & SMB_FLAG_CREATE)) {
771 tidp = malloc(sizeof(*tidp));
772 memset(tidp, 0, sizeof(*tidp));
773 tidp->nextp = vcp->tidsp;
777 lock_InitializeMutex(&tidp->mx, "tid_t mutex");
780 lock_ReleaseWrite(&smb_rctLock);
784 void smb_ReleaseTID(smb_tid_t *tidp)
791 lock_ObtainWrite(&smb_rctLock);
792 osi_assert(tidp->refCount-- > 0);
793 if (tidp->refCount == 0 && (tidp->flags & SMB_TIDFLAG_DELETE)) {
794 ltpp = &tidp->vcp->tidsp;
795 for(tp = *ltpp; tp; ltpp = &tp->nextp, tp = *ltpp) {
796 if (tp == tidp) break;
798 osi_assert(tp != NULL);
800 lock_FinalizeMutex(&tidp->mx);
801 userp = tidp->userp; /* remember to drop ref later */
803 lock_ReleaseWrite(&smb_rctLock);
805 cm_ReleaseUser(userp);
809 smb_user_t *smb_FindUID(smb_vc_t *vcp, unsigned short uid, int flags)
811 smb_user_t *uidp = NULL;
813 lock_ObtainWrite(&smb_rctLock);
814 for(uidp = vcp->usersp; uidp; uidp = uidp->nextp) {
815 if (uid == uidp->userID) {
817 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 : "");
821 if (!uidp && (flags & SMB_FLAG_CREATE)) {
822 uidp = malloc(sizeof(*uidp));
823 memset(uidp, 0, sizeof(*uidp));
824 uidp->nextp = vcp->usersp;
828 lock_InitializeMutex(&uidp->mx, "uid_t mutex");
830 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 : ""));
832 lock_ReleaseWrite(&smb_rctLock);
836 smb_username_t *smb_FindUserByName(char *usern, char *machine, int flags)
838 smb_username_t *unp= NULL;
840 lock_ObtainWrite(&smb_rctLock);
841 for(unp = usernamesp; unp; unp = unp->nextp) {
842 if (stricmp(unp->name, usern) == 0 &&
843 stricmp(unp->machine, machine) == 0) {
848 if (!unp && (flags & SMB_FLAG_CREATE)) {
849 unp = malloc(sizeof(*unp));
850 memset(unp, 0, sizeof(*unp));
852 unp->nextp = usernamesp;
853 unp->name = strdup(usern);
854 unp->machine = strdup(machine);
856 lock_InitializeMutex(&unp->mx, "username_t mutex");
858 lock_ReleaseWrite(&smb_rctLock);
862 smb_user_t *smb_FindUserByNameThisSession(smb_vc_t *vcp, char *usern)
864 smb_user_t *uidp= NULL;
866 lock_ObtainWrite(&smb_rctLock);
867 for(uidp = vcp->usersp; uidp; uidp = uidp->nextp) {
870 if (stricmp(uidp->unp->name, usern) == 0) {
872 osi_LogEvent("AFS smb_FindUserByNameThisSession",NULL,"VCP[%x] uid[%d] match-name[%s]",(int)vcp,uidp->userID,usern);
877 lock_ReleaseWrite(&smb_rctLock);
880 void smb_ReleaseUID(smb_user_t *uidp)
887 lock_ObtainWrite(&smb_rctLock);
888 osi_assert(uidp->refCount-- > 0);
889 if (uidp->refCount == 0 && (uidp->flags & SMB_USERFLAG_DELETE)) {
890 lupp = &uidp->vcp->usersp;
891 for(up = *lupp; up; lupp = &up->nextp, up = *lupp) {
892 if (up == uidp) break;
894 osi_assert(up != NULL);
896 lock_FinalizeMutex(&uidp->mx);
898 userp = uidp->unp->userp; /* remember to drop ref later */
899 uidp->unp->userp = NULL;
902 lock_ReleaseWrite(&smb_rctLock);
904 cm_ReleaseUserVCRef(userp);
905 cm_ReleaseUser(userp);
909 /* retrieve a held reference to a user structure corresponding to an incoming
911 * corresponding release function is cm_ReleaseUser.
913 cm_user_t *smb_GetUser(smb_vc_t *vcp, smb_packet_t *inp)
919 smbp = (smb_t *) inp;
920 uidp = smb_FindUID(vcp, smbp->uid, 0);
921 if ((!uidp) || (!uidp->unp))
924 lock_ObtainMutex(&uidp->mx);
925 up = uidp->unp->userp;
927 lock_ReleaseMutex(&uidp->mx);
929 smb_ReleaseUID(uidp);
935 * Return a pointer to a pathname extracted from a TID structure. The
936 * TID structure is not held; assume it won't go away.
938 char *smb_GetTIDPath(smb_vc_t *vcp, unsigned short tid)
943 tidp = smb_FindTID(vcp, tid, 0);
946 tpath = tidp->pathname;
947 smb_ReleaseTID(tidp);
951 /* check to see if we have a chained fid, that is, a fid that comes from an
952 * OpenAndX message that ran earlier in this packet. In this case, the fid
953 * field in a read, for example, request, isn't set, since the value is
954 * supposed to be inherited from the openAndX call.
956 int smb_ChainFID(int fid, smb_packet_t *inp)
958 if (inp->fid == 0 || inp->inCount == 0)
964 /* are we a priv'd user? What does this mean on NT? */
965 int smb_SUser(cm_user_t *userp)
970 /* find a file ID. If pass in 0, we'll allocate on on a create operation. */
971 smb_fid_t *smb_FindFID(smb_vc_t *vcp, unsigned short fid, int flags)
976 /* figure out if we need to allocate a new file ID */
979 fid = vcp->fidCounter;
983 lock_ObtainWrite(&smb_rctLock);
985 for(fidp = vcp->fidsp; fidp; fidp = (smb_fid_t *) osi_QNext(&fidp->q)) {
986 if (fid == fidp->fid) {
997 if (!fidp && (flags & SMB_FLAG_CREATE)) {
998 char eventName[MAX_PATH];
999 sprintf(eventName,"fid_t event fid=%d", fid);
1000 fidp = malloc(sizeof(*fidp));
1001 memset(fidp, 0, sizeof(*fidp));
1002 osi_QAdd((osi_queue_t **)&vcp->fidsp, &fidp->q);
1005 lock_InitializeMutex(&fidp->mx, "fid_t mutex");
1007 fidp->curr_chunk = fidp->prev_chunk = -2;
1008 fidp->raw_write_event = thrd_CreateEvent(NULL, FALSE, TRUE, eventName);
1009 if ( GetLastError() == ERROR_ALREADY_EXISTS )
1010 afsi_log("Event Object Already Exists: %s", eventName);
1012 vcp->fidCounter = fid+1;
1013 if (vcp->fidCounter == 0) vcp->fidCounter = 1;
1016 lock_ReleaseWrite(&smb_rctLock);
1020 void smb_ReleaseFID(smb_fid_t *fidp)
1024 smb_ioctl_t *ioctlp;
1030 lock_ObtainWrite(&smb_rctLock);
1031 osi_assert(fidp->refCount-- > 0);
1032 if (fidp->refCount == 0 && (fidp->flags & SMB_FID_DELETE)) {
1034 if (!(fidp->flags & SMB_FID_IOCTL))
1036 osi_QRemove((osi_queue_t **) &vcp->fidsp, &fidp->q);
1037 thrd_CloseHandle(fidp->raw_write_event);
1039 /* and see if there is ioctl stuff to free */
1040 ioctlp = fidp->ioctlp;
1042 if (ioctlp->prefix) cm_FreeSpace(ioctlp->prefix);
1043 if (ioctlp->inAllocp) free(ioctlp->inAllocp);
1044 if (ioctlp->outAllocp) free(ioctlp->outAllocp);
1050 lock_ReleaseWrite(&smb_rctLock);
1052 /* now release the scache structure */
1054 cm_ReleaseSCache(scp);
1058 * Case-insensitive search for one string in another;
1059 * used to find variable names in submount pathnames.
1061 static char *smb_stristr(char *str1, char *str2)
1065 for (cursor = str1; *cursor; cursor++)
1066 if (stricmp(cursor, str2) == 0)
1073 * Substitute a variable value for its name in a submount pathname. Variable
1074 * name has been identified by smb_stristr() and is in substr. Variable name
1075 * length (plus one) is in substr_size. Variable value is in newstr.
1077 static void smb_subst(char *str1, char *substr, unsigned int substr_size,
1082 strcpy(temp, substr + substr_size - 1);
1083 strcpy(substr, newstr);
1087 char VNUserName[] = "%USERNAME%";
1088 char VNLCUserName[] = "%LCUSERNAME%";
1089 char VNComputerName[] = "%COMPUTERNAME%";
1090 char VNLCComputerName[] = "%LCCOMPUTERNAME%";
1092 /* List available shares */
1093 int smb_ListShares()
1097 char shareBuf[4096];
1105 /*strcpy(shareNameList[num_shares], "all");
1106 strcpy(pathNameList[num_shares++], "/afs");*/
1107 fprintf(stderr, "The following shares are available:\n");
1108 fprintf(stderr, "Share Name (AFS Path)\n");
1109 fprintf(stderr, "---------------------\n");
1110 fprintf(stderr, "\\\\%s\\%-16s (%s)\n", smb_localNamep, "ALL", cm_mountRoot);
1113 code = GetWindowsDirectory(sbmtpath, sizeof(sbmtpath));
1114 if (code == 0 || code > sizeof(sbmtpath)) return -1;
1116 strcpy(sbmtpath, cm_confDir);
1118 strcat(sbmtpath, "/afsdsbmt.ini");
1119 len = GetPrivateProfileString("AFS Submounts", NULL, NULL,
1120 shareBuf, sizeof(shareBuf),
1126 this_share = shareBuf;
1130 /*strcpy(shareNameList[num_shares], this_share);*/
1131 len = GetPrivateProfileString("AFS Submounts", this_share,
1138 if (strncmp(p, cm_mountRoot, strlen(cm_mountRoot)) != 0)
1141 if (*p == '\\') *p = '/'; /* change to / */
1145 fprintf(stderr, "\\\\%s\\%-16s (%s%s)\n",
1146 smb_localNamep, this_share, (print_afs ? cm_mountRoot : "\0"),
1149 while (*this_share != 0) this_share++; /* find next NUL */
1150 this_share++; /* skip past the NUL */
1151 } while (*this_share != 0); /* stop at final NUL */
1156 /* find a shareName in the table of submounts */
1157 int smb_FindShare(smb_vc_t *vcp, smb_packet_t *inp, char *shareName,
1161 char pathName[1024];
1166 char sbmtpath[MAX_PATH];
1170 DWORD allSubmount = 1;
1172 if (strcmp(shareName, "IPC$") == 0) {
1177 /* if allSubmounts == 0, only return the //mountRoot/all share
1178 * if in fact it has been been created in the subMounts table.
1179 * This is to allow sites that want to restrict access to the
1182 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSConfigKeyName,
1183 0, KEY_QUERY_VALUE, &parmKey);
1184 if (code == ERROR_SUCCESS) {
1185 len = sizeof(allSubmount);
1186 code = RegQueryValueEx(parmKey, "AllSubmount", NULL, NULL,
1187 (BYTE *) &allSubmount, &len);
1188 if (code != ERROR_SUCCESS) {
1191 RegCloseKey (parmKey);
1194 if (allSubmount && _stricmp(shareName, "all") == 0) {
1199 /* In case, the all share is disabled we need to still be able
1200 * to handle ioctl requests
1202 if (_stricmp(shareName, "ioctl$") == 0) {
1203 *pathNamep = strdup("/.__ioctl__");
1208 strcpy(sbmtpath, "afsdsbmt.ini");
1210 strcpy(sbmtpath, cm_confDir);
1211 strcat(sbmtpath, "/afsdsbmt.ini");
1213 len = GetPrivateProfileString("AFS Submounts", shareName, "",
1214 pathName, sizeof(pathName), sbmtpath);
1215 if (len != 0 && len != sizeof(pathName) - 1) {
1216 /* We can accept either unix or PC style AFS pathnames. Convert
1217 * Unix-style to PC style here for internal use.
1220 if (strncmp(p, cm_mountRoot, strlen(cm_mountRoot)) == 0)
1221 p += strlen(cm_mountRoot); /* skip mount path */
1224 if (*q == '/') *q = '\\'; /* change to \ */
1230 if (var = smb_stristr(p, VNUserName)) {
1231 uidp = smb_FindUID(vcp, ((smb_t *)inp)->uid, 0);
1232 if (uidp && uidp->unp)
1233 smb_subst(p, var, sizeof(VNUserName),uidp->unp->name);
1235 smb_subst(p, var, sizeof(VNUserName)," ");
1237 smb_ReleaseUID(uidp);
1239 else if (var = smb_stristr(p, VNLCUserName))
1241 uidp = smb_FindUID(vcp, ((smb_t *)inp)->uid, 0);
1242 if (uidp && uidp->unp)
1243 strcpy(temp, uidp->unp->name);
1247 smb_subst(p, var, sizeof(VNLCUserName), temp);
1249 smb_ReleaseUID(uidp);
1251 else if (var = smb_stristr(p, VNComputerName))
1253 sizeTemp = sizeof(temp);
1254 GetComputerName((LPTSTR)temp, &sizeTemp);
1255 smb_subst(p, var, sizeof(VNComputerName), temp);
1257 else if (var = smb_stristr(p, VNLCComputerName))
1259 sizeTemp = sizeof(temp);
1260 GetComputerName((LPTSTR)temp, &sizeTemp);
1262 smb_subst(p, var, sizeof(VNLCComputerName), temp);
1267 *pathNamep = strdup(p);
1270 else /* create \\<netbiosName>\<cellname> */
1272 /* Get the full name for this cell */
1273 code = cm_SearchCellFile(shareName, temp, 0, 0);
1274 #ifdef AFS_AFSDB_ENV
1275 if (code && cm_dnsEnabled) {
1277 code = cm_SearchCellByDNS(shareName, temp, &ttl, 0, 0);
1280 /* construct the path */
1282 sprintf(pathName,"/%s/",temp);
1283 *pathNamep = strdup(strlwr(pathName));
1292 /* find a dir search structure by cookie value, and return it held.
1293 * Must be called with smb_globalLock held.
1295 smb_dirSearch_t *smb_FindDirSearchNL(long cookie)
1297 smb_dirSearch_t *dsp;
1299 for(dsp = smb_firstDirSearchp; dsp; dsp = (smb_dirSearch_t *) osi_QNext(&dsp->q)) {
1300 if (dsp->cookie == cookie) {
1301 if (dsp != smb_firstDirSearchp) {
1302 /* move to head of LRU queue, too, if we're not already there */
1303 if (smb_lastDirSearchp == (smb_dirSearch_t *) &dsp->q)
1304 smb_lastDirSearchp = (smb_dirSearch_t *)
1306 osi_QRemove((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1307 osi_QAdd((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1308 if (!smb_lastDirSearchp)
1309 smb_lastDirSearchp = (smb_dirSearch_t *) &dsp->q;
1318 void smb_DeleteDirSearch(smb_dirSearch_t *dsp)
1320 lock_ObtainWrite(&smb_globalLock);
1321 dsp->flags |= SMB_DIRSEARCH_DELETE;
1322 lock_ReleaseWrite(&smb_globalLock);
1323 lock_ObtainMutex(&dsp->mx);
1324 if(dsp->scp != NULL) {
1325 lock_ObtainMutex(&dsp->scp->mx);
1326 if (dsp->flags & SMB_DIRSEARCH_BULKST) {
1327 dsp->flags &= ~SMB_DIRSEARCH_BULKST;
1328 dsp->scp->flags &= ~CM_SCACHEFLAG_BULKSTATTING;
1329 dsp->scp->bulkStatProgress = hones;
1331 lock_ReleaseMutex(&dsp->scp->mx);
1333 lock_ReleaseMutex(&dsp->mx);
1336 void smb_ReleaseDirSearch(smb_dirSearch_t *dsp)
1342 lock_ObtainWrite(&smb_globalLock);
1343 osi_assert(dsp->refCount-- > 0);
1344 if (dsp->refCount == 0 && (dsp->flags & SMB_DIRSEARCH_DELETE)) {
1345 if (&dsp->q == (osi_queue_t *) smb_lastDirSearchp)
1346 smb_lastDirSearchp = (smb_dirSearch_t *) osi_QPrev(&smb_lastDirSearchp->q);
1347 osi_QRemove((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1348 lock_FinalizeMutex(&dsp->mx);
1352 lock_ReleaseWrite(&smb_globalLock);
1354 /* do this now to avoid spurious locking hierarchy creation */
1355 if (scp) cm_ReleaseSCache(scp);
1358 /* find a dir search structure by cookie value, and return it held */
1359 smb_dirSearch_t *smb_FindDirSearch(long cookie)
1361 smb_dirSearch_t *dsp;
1363 lock_ObtainWrite(&smb_globalLock);
1364 dsp = smb_FindDirSearchNL(cookie);
1365 lock_ReleaseWrite(&smb_globalLock);
1369 /* GC some dir search entries, in the address space expected by the specific protocol.
1370 * Must be called with smb_globalLock held; release the lock temporarily.
1372 #define SMB_DIRSEARCH_GCMAX 10 /* how many at once */
1373 void smb_GCDirSearches(int isV3)
1375 smb_dirSearch_t *prevp;
1376 smb_dirSearch_t *tp;
1377 smb_dirSearch_t *victimsp[SMB_DIRSEARCH_GCMAX];
1381 victimCount = 0; /* how many have we got so far */
1382 for(tp = smb_lastDirSearchp; tp; tp=prevp) {
1383 /* we'll move tp from queue, so
1386 prevp = (smb_dirSearch_t *) osi_QPrev(&tp->q);
1387 /* if no one is using this guy, and we're either in the new protocol,
1388 * or we're in the old one and this is a small enough ID to be useful
1389 * to the old protocol, GC this guy.
1391 if (tp->refCount == 0 && (isV3 || tp->cookie <= 255)) {
1392 /* hold and delete */
1393 tp->flags |= SMB_DIRSEARCH_DELETE;
1394 victimsp[victimCount++] = tp;
1398 /* don't do more than this */
1399 if (victimCount >= SMB_DIRSEARCH_GCMAX) break;
1402 /* now release them */
1403 lock_ReleaseWrite(&smb_globalLock);
1404 for(i = 0; i < victimCount; i++) {
1405 smb_ReleaseDirSearch(victimsp[i]);
1407 lock_ObtainWrite(&smb_globalLock);
1410 /* function for allocating a dir search entry. We need these to remember enough context
1411 * since we don't get passed the path from call to call during a directory search.
1413 * Returns a held dir search structure, and bumps the reference count on the vnode,
1414 * since it saves a pointer to the vnode.
1416 smb_dirSearch_t *smb_NewDirSearch(int isV3)
1418 smb_dirSearch_t *dsp;
1422 lock_ObtainWrite(&smb_globalLock);
1425 /* what's the biggest ID allowed in this version of the protocol */
1426 if (isV3) maxAllowed = 65535;
1427 else maxAllowed = 255;
1430 /* twice so we have enough tries to find guys we GC after one pass;
1431 * 10 extra is just in case I mis-counted.
1433 if (++counter > 2*maxAllowed+10) osi_panic("afsd: dir search cookie leak",
1434 __FILE__, __LINE__);
1435 if (smb_dirSearchCounter > maxAllowed) {
1436 smb_dirSearchCounter = 1;
1437 smb_GCDirSearches(isV3); /* GC some (drops global lock) */
1439 dsp = smb_FindDirSearchNL(smb_dirSearchCounter);
1441 /* don't need to watch for refcount zero and deleted, since
1442 * we haven't dropped the global lock.
1445 ++smb_dirSearchCounter;
1449 dsp = malloc(sizeof(*dsp));
1450 memset(dsp, 0, sizeof(*dsp));
1451 osi_QAdd((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1452 if (!smb_lastDirSearchp) smb_lastDirSearchp = (smb_dirSearch_t *) &dsp->q;
1453 dsp->cookie = smb_dirSearchCounter;
1454 ++smb_dirSearchCounter;
1456 lock_InitializeMutex(&dsp->mx, "cm_dirSearch_t");
1457 dsp->lastTime = osi_Time();
1460 lock_ReleaseWrite(&smb_globalLock);
1464 static smb_packet_t *GetPacket(void)
1468 unsigned int npar, seg, tb_sel;
1471 lock_ObtainWrite(&smb_globalLock);
1472 tbp = smb_packetFreeListp;
1474 smb_packetFreeListp = tbp->nextp;
1475 lock_ReleaseWrite(&smb_globalLock);
1478 tbp = calloc(65540,1);
1480 tbp = malloc(sizeof(smb_packet_t));
1482 tbp->magic = SMB_PACKETMAGIC;
1485 tbp->resumeCode = 0;
1491 tbp->ncb_length = 0;
1496 npar = SMB_PACKETSIZE >> 4; /* number of paragraphs */
1499 __dpmi_allocate_dos_memory(npar, &tb_sel); /* DOS segment */
1501 afsi_log("Cannot allocate %d paragraphs of DOS memory",
1503 osi_panic("",__FILE__,__LINE__);
1506 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X",
1511 tbp->dos_pkt = (seg * 16) + 0; /* DOS physical address */
1512 tbp->dos_pkt_sel = tb_sel;
1515 osi_assert(tbp->magic == SMB_PACKETMAGIC);
1520 smb_packet_t *smb_CopyPacket(smb_packet_t *pkt)
1524 memcpy(tbp, pkt, sizeof(smb_packet_t));
1525 tbp->wctp = tbp->data + ((unsigned int)pkt->wctp - (unsigned int)pkt->data);
1529 static NCB *GetNCB(void)
1534 unsigned int npar, seg, tb_sel;
1537 lock_ObtainWrite(&smb_globalLock);
1538 tbp = smb_ncbFreeListp;
1540 smb_ncbFreeListp = tbp->nextp;
1541 lock_ReleaseWrite(&smb_globalLock);
1544 tbp = calloc(sizeof(*tbp),1);
1546 tbp = malloc(sizeof(*tbp));
1547 npar = (sizeof(NCB)+15) >> 4; /* number of paragraphs */
1550 __dpmi_allocate_dos_memory(npar, &tb_sel); /* DOS segment */
1552 afsi_log("Cannot allocate %d paragraphs of DOS mem in GetNCB",
1554 osi_panic("",__FILE__,__LINE__);
1556 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X in GetNCB",
1561 tbp->dos_ncb = (seg * 16) + 0; /* DOS physical address */
1562 tbp->dos_ncb_sel = tb_sel;
1564 tbp->magic = SMB_NCBMAGIC;
1567 osi_assert(tbp->magic == SMB_NCBMAGIC);
1569 memset(&tbp->ncb, 0, sizeof(NCB));
1572 dos_memset(tbp->dos_ncb, 0, sizeof(NCB));
1577 void smb_FreePacket(smb_packet_t *tbp)
1579 osi_assert(tbp->magic == SMB_PACKETMAGIC);
1581 lock_ObtainWrite(&smb_globalLock);
1582 tbp->nextp = smb_packetFreeListp;
1583 smb_packetFreeListp = tbp;
1584 tbp->magic = SMB_PACKETMAGIC;
1587 tbp->resumeCode = 0;
1593 tbp->ncb_length = 0;
1595 lock_ReleaseWrite(&smb_globalLock);
1598 static void FreeNCB(NCB *bufferp)
1602 tbp = (smb_ncb_t *) bufferp;
1603 osi_assert(tbp->magic == SMB_NCBMAGIC);
1605 lock_ObtainWrite(&smb_globalLock);
1606 tbp->nextp = smb_ncbFreeListp;
1607 smb_ncbFreeListp = tbp;
1608 lock_ReleaseWrite(&smb_globalLock);
1611 /* get a ptr to the data part of a packet, and its count */
1612 unsigned char *smb_GetSMBData(smb_packet_t *smbp, int *nbytesp)
1616 unsigned char *afterParmsp;
1618 parmBytes = *smbp->wctp << 1;
1619 afterParmsp = smbp->wctp + parmBytes + 1;
1621 dataBytes = afterParmsp[0] + (afterParmsp[1]<<8);
1622 if (nbytesp) *nbytesp = dataBytes;
1624 /* don't forget to skip the data byte count, since it follows
1625 * the parameters; that's where the "2" comes from below.
1627 return (unsigned char *) (afterParmsp + 2);
1630 /* must set all the returned parameters before playing around with the
1631 * data region, since the data region is located past the end of the
1632 * variable number of parameters.
1634 void smb_SetSMBDataLength(smb_packet_t *smbp, unsigned int dsize)
1636 unsigned char *afterParmsp;
1638 afterParmsp = smbp->wctp + ((*smbp->wctp)<<1) + 1;
1640 *afterParmsp++ = dsize & 0xff;
1641 *afterParmsp = (dsize>>8) & 0xff;
1644 /* return the parm'th parameter in the smbp packet */
1645 unsigned int smb_GetSMBParm(smb_packet_t *smbp, int parm)
1648 unsigned char *parmDatap;
1650 parmCount = *smbp->wctp;
1652 if (parm >= parmCount) {
1657 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
1658 sprintf(s, "Bad SMB param %d out of %d, ncb len %d",
1659 parm, parmCount, smbp->ncb_length);
1661 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1006, NULL,
1662 1, smbp->ncb_length, ptbuf, smbp);
1663 DeregisterEventSource(h);
1667 sprintf(s, "Bad SMB param %d out of %d, ncb len %d",
1668 parm, parmCount, smbp->ncb_length);
1669 osi_Log0(afsd_logp, s);
1671 osi_panic(s, __FILE__, __LINE__);
1673 parmDatap = smbp->wctp + (2*parm) + 1;
1675 return parmDatap[0] + (parmDatap[1] << 8);
1678 /* return the parm'th parameter in the smbp packet */
1679 unsigned int smb_GetSMBOffsetParm(smb_packet_t *smbp, int parm, int offset)
1682 unsigned char *parmDatap;
1684 parmCount = *smbp->wctp;
1686 if (parm * 2 + offset >= parmCount * 2) {
1691 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
1692 sprintf(s, "Bad SMB param %d offset %d out of %d, ncb len %d",
1693 parm, offset, parmCount, smbp->ncb_length);
1695 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1006, NULL,
1696 1, smbp->ncb_length, ptbuf, smbp);
1697 DeregisterEventSource(h);
1701 sprintf(s, "Bad SMB param %d offset %d out of %d, "
1703 parm, offset, parmCount, smbp->ncb_length);
1704 osi_Log0(afsd_logp, s);
1707 osi_panic(s, __FILE__, __LINE__);
1709 parmDatap = smbp->wctp + (2*parm) + 1 + offset;
1711 return parmDatap[0] + (parmDatap[1] << 8);
1714 void smb_SetSMBParm(smb_packet_t *smbp, int slot, unsigned int parmValue)
1718 /* make sure we have enough slots */
1719 if (*smbp->wctp <= slot) *smbp->wctp = slot+1;
1721 parmDatap = smbp->wctp + 2*slot + 1 + smbp->oddByte;
1722 *parmDatap++ = parmValue & 0xff;
1723 *parmDatap = (parmValue>>8) & 0xff;
1726 void smb_SetSMBParmLong(smb_packet_t *smbp, int slot, unsigned int parmValue)
1730 /* make sure we have enough slots */
1731 if (*smbp->wctp <= slot) *smbp->wctp = slot+2;
1733 parmDatap = smbp->wctp + 2*slot + 1 + smbp->oddByte;
1734 *parmDatap++ = parmValue & 0xff;
1735 *parmDatap++ = (parmValue>>8) & 0xff;
1736 *parmDatap++ = (parmValue>>16) & 0xff;
1737 *parmDatap++ = (parmValue>>24) & 0xff;
1740 void smb_SetSMBParmDouble(smb_packet_t *smbp, int slot, char *parmValuep)
1745 /* make sure we have enough slots */
1746 if (*smbp->wctp <= slot) *smbp->wctp = slot+4;
1748 parmDatap = smbp->wctp + 2*slot + 1 + smbp->oddByte;
1750 *parmDatap++ = *parmValuep++;
1753 void smb_SetSMBParmByte(smb_packet_t *smbp, int slot, unsigned int parmValue)
1757 /* make sure we have enough slots */
1758 if (*smbp->wctp <= slot) {
1759 if (smbp->oddByte) {
1761 *smbp->wctp = slot+1;
1766 parmDatap = smbp->wctp + 2*slot + 1 + (1 - smbp->oddByte);
1767 *parmDatap++ = parmValue & 0xff;
1770 void smb_StripLastComponent(char *outPathp, char **lastComponentp, char *inPathp)
1774 lastSlashp = strrchr(inPathp, '\\');
1776 *lastComponentp = lastSlashp;
1779 if (inPathp == lastSlashp)
1781 *outPathp++ = *inPathp++;
1790 unsigned char *smb_ParseASCIIBlock(unsigned char *inp, char **chainpp)
1795 *chainpp = inp + strlen(inp) + 1; /* skip over null-terminated string */
1800 unsigned char *smb_ParseVblBlock(unsigned char *inp, char **chainpp, int *lengthp)
1806 tlen = inp[0] + (inp[1]<<8);
1807 inp += 2; /* skip length field */
1810 *chainpp = inp + tlen;
1819 /* format a packet as a response */
1820 void smb_FormatResponsePacket(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *op)
1825 outp = (smb_t *) op;
1827 /* zero the basic structure through the smb_wct field, and zero the data
1828 * size field, assuming that wct stays zero; otherwise, you have to
1829 * explicitly set the data size field, too.
1831 inSmbp = (smb_t *) inp;
1832 memset(outp, 0, sizeof(smb_t)+2);
1838 outp->com = inSmbp->com;
1839 outp->tid = inSmbp->tid;
1840 outp->pid = inSmbp->pid;
1841 outp->uid = inSmbp->uid;
1842 outp->mid = inSmbp->mid;
1843 outp->res[0] = inSmbp->res[0];
1844 outp->res[1] = inSmbp->res[1];
1845 op->inCom = inSmbp->com;
1847 outp->reb = 0x80; /* SERVER_RESP */
1848 outp->flg2 = 0x1; /* KNOWS_LONG_NAMES */
1850 /* copy fields in generic packet area */
1851 op->wctp = &outp->wct;
1854 /* send a (probably response) packet; vcp tells us to whom to send it.
1855 * we compute the length by looking at wct and bcc fields.
1857 void smb_SendPacket(smb_vc_t *vcp, smb_packet_t *inp)
1874 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
1877 memset((char *)ncbp, 0, sizeof(NCB));
1879 extra = 2 * (*inp->wctp); /* space used by parms, in bytes */
1880 tp = inp->wctp + 1+ extra; /* points to count of data bytes */
1881 extra += tp[0] + (tp[1]<<8);
1882 extra += ((unsigned int)inp->wctp - (unsigned int)inp->data); /* distance to last wct field */
1883 extra += 3; /* wct and length fields */
1885 ncbp->ncb_length = extra; /* bytes to send */
1886 ncbp->ncb_lsn = (unsigned char) vcp->lsn; /* vc to use */
1887 ncbp->ncb_lana_num = vcp->lana;
1888 ncbp->ncb_command = NCBSEND; /* op means send data */
1890 ncbp->ncb_buffer = (char *) inp;/* packet */
1891 code = Netbios(ncbp);
1893 ncbp->ncb_buffer = inp->dos_pkt;/* packet */
1894 ((smb_ncb_t*)ncbp)->orig_pkt = inp;
1896 /* copy header information from virtual to DOS address space */
1897 dosmemput((char*)inp, SMB_PACKETSIZE, inp->dos_pkt);
1898 code = Netbios(ncbp, dos_ncb);
1902 osi_Log1(afsd_logp, "SendPacket failure code %d", code);
1908 void smb_MapNTError(long code, unsigned long *NTStatusp)
1910 unsigned long NTStatus;
1912 /* map CM_ERROR_* errors to NT 32-bit status codes */
1913 if (code == CM_ERROR_NOSUCHCELL) {
1914 NTStatus = 0xC000000FL; /* No such file */
1916 else if (code == CM_ERROR_NOSUCHVOLUME) {
1917 NTStatus = 0xC000000FL; /* No such file */
1919 else if (code == CM_ERROR_TIMEDOUT) {
1920 NTStatus = 0xC00000CFL; /* Sharing Paused */
1922 else if (code == CM_ERROR_RETRY) {
1923 NTStatus = 0xC000022DL; /* Retry */
1925 else if (code == CM_ERROR_NOACCESS) {
1926 NTStatus = 0xC0000022L; /* Access denied */
1928 else if (code == CM_ERROR_READONLY) {
1929 NTStatus = 0xC00000A2L; /* Write protected */
1931 else if (code == CM_ERROR_NOSUCHFILE) {
1932 NTStatus = 0xC000000FL; /* No such file */
1934 else if (code == CM_ERROR_NOSUCHPATH) {
1935 NTStatus = 0xC000003AL; /* Object path not found */
1937 else if (code == CM_ERROR_TOOBIG) {
1938 NTStatus = 0xC000007BL; /* Invalid image format */
1940 else if (code == CM_ERROR_INVAL) {
1941 NTStatus = 0xC000000DL; /* Invalid parameter */
1943 else if (code == CM_ERROR_BADFD) {
1944 NTStatus = 0xC0000008L; /* Invalid handle */
1946 else if (code == CM_ERROR_BADFDOP) {
1947 NTStatus = 0xC0000022L; /* Access denied */
1949 else if (code == CM_ERROR_EXISTS) {
1950 NTStatus = 0xC0000035L; /* Object name collision */
1952 else if (code == CM_ERROR_NOTEMPTY) {
1953 NTStatus = 0xC0000101L; /* Directory not empty */
1955 else if (code == CM_ERROR_CROSSDEVLINK) {
1956 NTStatus = 0xC00000D4L; /* Not same device */
1958 else if (code == CM_ERROR_NOTDIR) {
1959 NTStatus = 0xC0000103L; /* Not a directory */
1961 else if (code == CM_ERROR_ISDIR) {
1962 NTStatus = 0xC00000BAL; /* File is a directory */
1964 else if (code == CM_ERROR_BADOP) {
1965 NTStatus = 0xC09820FFL; /* SMB no support */
1967 else if (code == CM_ERROR_BADSHARENAME) {
1968 NTStatus = 0xC00000CCL; /* Bad network name */
1970 else if (code == CM_ERROR_NOIPC) {
1972 NTStatus = 0xC0000022L; /* Access Denied */
1974 NTStatus = 0xC000013DL; /* Remote Resources */
1977 else if (code == CM_ERROR_CLOCKSKEW) {
1978 NTStatus = 0xC0000133L; /* Time difference at DC */
1980 else if (code == CM_ERROR_BADTID) {
1981 NTStatus = 0xC0982005L; /* SMB bad TID */
1983 else if (code == CM_ERROR_USESTD) {
1984 NTStatus = 0xC09820FBL; /* SMB use standard */
1986 else if (code == CM_ERROR_QUOTA) {
1987 NTStatus = 0xC0000044L; /* Quota exceeded */
1989 else if (code == CM_ERROR_SPACE) {
1990 NTStatus = 0xC000007FL; /* Disk full */
1992 else if (code == CM_ERROR_ATSYS) {
1993 NTStatus = 0xC0000033L; /* Object name invalid */
1995 else if (code == CM_ERROR_BADNTFILENAME) {
1996 NTStatus = 0xC0000033L; /* Object name invalid */
1998 else if (code == CM_ERROR_WOULDBLOCK) {
1999 NTStatus = 0xC0000055L; /* Lock not granted */
2001 else if (code == CM_ERROR_PARTIALWRITE) {
2002 NTStatus = 0xC000007FL; /* Disk full */
2004 else if (code == CM_ERROR_BUFFERTOOSMALL) {
2005 NTStatus = 0xC0000023L; /* Buffer too small */
2008 NTStatus = 0xC0982001L; /* SMB non-specific error */
2011 *NTStatusp = NTStatus;
2012 osi_Log2(afsd_logp, "SMB SEND code %x as NT %x", code, NTStatus);
2015 void smb_MapCoreError(long code, smb_vc_t *vcp, unsigned short *scodep,
2016 unsigned char *classp)
2018 unsigned char class;
2019 unsigned short error;
2021 /* map CM_ERROR_* errors to SMB errors */
2022 if (code == CM_ERROR_NOSUCHCELL) {
2024 error = 3; /* bad path */
2026 else if (code == CM_ERROR_NOSUCHVOLUME) {
2028 error = 3; /* bad path */
2030 else if (code == CM_ERROR_TIMEDOUT) {
2032 error = 81; /* server is paused */
2034 else if (code == CM_ERROR_RETRY) {
2035 class = 2; /* shouldn't happen */
2038 else if (code == CM_ERROR_NOACCESS) {
2040 error = 4; /* bad access */
2042 else if (code == CM_ERROR_READONLY) {
2044 error = 19; /* read only */
2046 else if (code == CM_ERROR_NOSUCHFILE) {
2048 error = 2; /* ENOENT! */
2050 else if (code == CM_ERROR_NOSUCHPATH) {
2052 error = 3; /* Bad path */
2054 else if (code == CM_ERROR_TOOBIG) {
2056 error = 11; /* bad format */
2058 else if (code == CM_ERROR_INVAL) {
2059 class = 2; /* server non-specific error code */
2062 else if (code == CM_ERROR_BADFD) {
2064 error = 6; /* invalid file handle */
2066 else if (code == CM_ERROR_BADFDOP) {
2067 class = 1; /* invalid op on FD */
2070 else if (code == CM_ERROR_EXISTS) {
2072 error = 80; /* file already exists */
2074 else if (code == CM_ERROR_NOTEMPTY) {
2076 error = 5; /* delete directory not empty */
2078 else if (code == CM_ERROR_CROSSDEVLINK) {
2080 error = 17; /* EXDEV */
2082 else if (code == CM_ERROR_NOTDIR) {
2083 class = 1; /* bad path */
2086 else if (code == CM_ERROR_ISDIR) {
2087 class = 1; /* access denied; DOS doesn't have a good match */
2090 else if (code == CM_ERROR_BADOP) {
2094 else if (code == CM_ERROR_BADSHARENAME) {
2098 else if (code == CM_ERROR_NOIPC) {
2100 error = 4; /* bad access */
2102 else if (code == CM_ERROR_CLOCKSKEW) {
2103 class = 1; /* invalid function */
2106 else if (code == CM_ERROR_BADTID) {
2110 else if (code == CM_ERROR_USESTD) {
2114 else if (code == CM_ERROR_REMOTECONN) {
2118 else if (code == CM_ERROR_QUOTA) {
2119 if (vcp->flags & SMB_VCFLAG_USEV3) {
2121 error = 39; /* disk full */
2125 error = 5; /* access denied */
2128 else if (code == CM_ERROR_SPACE) {
2129 if (vcp->flags & SMB_VCFLAG_USEV3) {
2131 error = 39; /* disk full */
2135 error = 5; /* access denied */
2138 else if (code == CM_ERROR_PARTIALWRITE) {
2140 error = 39; /* disk full */
2142 else if (code == CM_ERROR_ATSYS) {
2144 error = 2; /* ENOENT */
2146 else if (code == CM_ERROR_WOULDBLOCK) {
2148 error = 33; /* lock conflict */
2150 else if (code == CM_ERROR_NOFILES) {
2152 error = 18; /* no files in search */
2154 else if (code == CM_ERROR_RENAME_IDENTICAL) {
2156 error = 183; /* Samba uses this */
2165 osi_Log3(afsd_logp, "SMB SEND code %x as SMB %d: %d", code, class, error);
2168 long smb_SendCoreBadOp(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2170 return CM_ERROR_BADOP;
2173 long smb_ReceiveCoreEcho(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2175 unsigned short EchoCount, i;
2176 char *data, *outdata;
2179 EchoCount = (unsigned short) smb_GetSMBParm(inp, 0);
2181 for (i=1; i<=EchoCount; i++) {
2182 data = smb_GetSMBData(inp, &dataSize);
2183 smb_SetSMBParm(outp, 0, i);
2184 smb_SetSMBDataLength(outp, dataSize);
2185 outdata = smb_GetSMBData(outp, NULL);
2186 memcpy(outdata, data, dataSize);
2187 smb_SendPacket(vcp, outp);
2193 long smb_ReceiveCoreReadRaw(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2196 long count, minCount, finalCount;
2200 cm_user_t *userp = NULL;
2204 char *rawBuf = NULL;
2206 dos_ptr rawBuf = NULL;
2213 fd = smb_GetSMBParm(inp, 0);
2214 count = smb_GetSMBParm(inp, 3);
2215 minCount = smb_GetSMBParm(inp, 4);
2216 offset.HighPart = 0; /* too bad */
2217 offset.LowPart = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
2219 osi_Log3(afsd_logp, "smb_ReceieveCoreReadRaw fd %d, off 0x%x, size 0x%x",
2220 fd, offset.LowPart, count);
2222 fidp = smb_FindFID(vcp, fd, 0);
2226 lock_ObtainMutex(&smb_RawBufLock);
2228 /* Get a raw buf, from head of list */
2229 rawBuf = smb_RawBufs;
2231 smb_RawBufs = *(char **)smb_RawBufs;
2233 smb_RawBufs = _farpeekl(_dos_ds, smb_RawBufs);
2236 lock_ReleaseMutex(&smb_RawBufLock);
2240 if (fidp->flags & SMB_FID_IOCTL)
2243 rc = smb_IoctlReadRaw(fidp, vcp, inp, outp);
2245 rc = smb_IoctlReadRaw(fidp, vcp, inp, outp, rawBuf);
2248 /* Give back raw buffer */
2249 lock_ObtainMutex(&smb_RawBufLock);
2251 *((char **) rawBuf) = smb_RawBufs;
2253 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
2256 smb_RawBufs = rawBuf;
2257 lock_ReleaseMutex(&smb_RawBufLock);
2260 smb_ReleaseFID(fidp);
2264 userp = smb_GetUser(vcp, inp);
2267 code = smb_ReadData(fidp, &offset, count, rawBuf, userp, &finalCount);
2269 /* have to give ReadData flag so it will treat buffer as DOS mem. */
2270 code = smb_ReadData(fidp, &offset, count, (unsigned char *)rawBuf,
2271 userp, &finalCount, TRUE /* rawFlag */);
2278 cm_ReleaseUser(userp);
2281 smb_ReleaseFID(fidp);
2286 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
2288 memset((char *)ncbp, 0, sizeof(NCB));
2290 ncbp->ncb_length = (unsigned short) finalCount;
2291 ncbp->ncb_lsn = (unsigned char) vcp->lsn;
2292 ncbp->ncb_lana_num = vcp->lana;
2293 ncbp->ncb_command = NCBSEND;
2294 ncbp->ncb_buffer = rawBuf;
2297 code = Netbios(ncbp);
2299 code = Netbios(ncbp, dos_ncb);
2302 osi_Log1(afsd_logp, "ReadRaw send failure code %d", code);
2305 /* Give back raw buffer */
2306 lock_ObtainMutex(&smb_RawBufLock);
2308 *((char **) rawBuf) = smb_RawBufs;
2310 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
2313 smb_RawBufs = rawBuf;
2314 lock_ReleaseMutex(&smb_RawBufLock);
2320 long smb_ReceiveCoreLockRecord(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2325 long smb_ReceiveCoreUnlockRecord(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2330 long smb_ReceiveNegotiate(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2336 int protoIndex; /* index we're using */
2341 char protocol_array[10][1024]; /* protocol signature of the client */
2344 osi_Log1(afsd_logp, "SMB receive negotiate; %d + 1 ongoing ops",
2348 DWORD now = GetCurrentTime();
2349 if (now - last_msg_time >= 30000
2350 && now - last_msg_time <= 90000) {
2352 "Setting dead_vcp %x", active_vcp);
2353 dead_vcp = active_vcp;
2354 dead_vcp->flags |= SMB_VCFLAG_ALREADYDEAD;
2359 inp->flags |= SMB_PACKETFLAG_PROFILE_UPDATE_OK;
2361 namep = smb_GetSMBData(inp, &dbytes);
2364 coreProtoIndex = -1; /* not found */
2367 while(namex < dbytes) {
2368 osi_Log1(afsd_logp, "Protocol %s",
2369 osi_LogSaveString(afsd_logp, namep+1));
2370 strcpy(protocol_array[tcounter], namep+1);
2372 /* namep points at the first protocol, or really, a 0x02
2373 * byte preceding the null-terminated ASCII name.
2375 if (strcmp("PC NETWORK PROGRAM 1.0", namep+1) == 0) {
2376 coreProtoIndex = tcounter;
2378 else if (smb_useV3 && strcmp("LM1.2X002", namep+1) == 0) {
2379 v3ProtoIndex = tcounter;
2381 else if (smb_useV3 && strcmp("NT LM 0.12", namep+1) == 0) {
2382 NTProtoIndex = tcounter;
2385 /* compute size of protocol entry */
2386 entryLength = strlen(namep+1);
2387 entryLength += 2; /* 0x02 bytes and null termination */
2389 /* advance over this protocol entry */
2390 namex += entryLength;
2391 namep += entryLength;
2392 tcounter++; /* which proto entry we're looking at */
2394 #ifndef NOMOREFILESFIX
2396 * NOTE: We can determine what OS (NT4.0, W2K, W9X, etc)
2397 * the client is running by reading the protocol signature.
2398 * ie. the order in which it sends us the protocol list.
2400 * Special handling for Windows 2000 clients (defect 11765 )
2401 * <asanka:11Jun03> Proto signature is the same for Win XP. </>
2403 if (tcounter == 6) {
2405 smb_t *ip = (smb_t *) inp;
2406 smb_t *op = (smb_t *) outp;
2408 if ((strcmp("PC NETWORK PROGRAM 1.0", protocol_array[0]) == 0) &&
2409 (strcmp("LANMAN1.0", protocol_array[1]) == 0) &&
2410 (strcmp("Windows for Workgroups 3.1a", protocol_array[2]) == 0) &&
2411 (strcmp("LM1.2X002", protocol_array[3]) == 0) &&
2412 (strcmp("LANMAN2.1", protocol_array[4]) == 0) &&
2413 (strcmp("NT LM 0.12", protocol_array[5]) == 0)) {
2414 isWindows2000 = TRUE;
2415 osi_Log0(afsd_logp, "Looks like a Windows 2000 client");
2417 * HACK: for now - just negotiate a lower protocol till we
2418 * figure out which flag/flag2 or some other field
2419 * (capabilities maybe?) to set in order for this to work
2420 * correctly with Windows 2000 clients (defect 11765)
2423 /* Things to try (after looking at tcpdump output could be
2424 * setting flags and flags2 to 0x98 and 0xc853 like this
2425 * op->reb = 0x98; op->flg2 = 0xc853;
2426 * osi_Log2(afsd_logp, "Flags:0x%x Flags2:0x%x", ip->reb, ip->flg2);
2430 #endif /* NOMOREFILESFIX */
2432 if (NTProtoIndex != -1) {
2433 protoIndex = NTProtoIndex;
2434 vcp->flags |= (SMB_VCFLAG_USENT | SMB_VCFLAG_USEV3);
2436 else if (v3ProtoIndex != -1) {
2437 protoIndex = v3ProtoIndex;
2438 vcp->flags |= SMB_VCFLAG_USEV3;
2440 else if (coreProtoIndex != -1) {
2441 protoIndex = coreProtoIndex;
2442 vcp->flags |= SMB_VCFLAG_USECORE;
2444 else protoIndex = -1;
2446 if (protoIndex == -1)
2447 return CM_ERROR_INVAL;
2448 else if (NTProtoIndex != -1) {
2449 smb_SetSMBParm(outp, 0, protoIndex);
2450 smb_SetSMBParmByte(outp, 1, 0); /* share level security, no passwd encrypt */
2451 smb_SetSMBParm(outp, 1, smb_maxMpxRequests); /* max multiplexed requests */
2452 smb_SetSMBParm(outp, 2, smb_maxVCPerServer); /* max VCs per consumer/server connection */
2453 smb_SetSMBParmLong(outp, 3, SMB_PACKETSIZE); /* xmit buffer size */
2454 smb_SetSMBParmLong(outp, 5, 65536); /* raw buffer size */
2455 smb_SetSMBParm(outp, 7, 1); /* next 2: session key */
2456 smb_SetSMBParm(outp, 8, 1);
2458 * Tried changing the capabilities to support for W2K - defect 117695
2459 * Maybe something else needs to be changed here?
2463 smb_SetSMBParmLong(outp, 9, 0x43fd);
2465 smb_SetSMBParmLong(outp, 9, 0x251);
2468 * 32-bit error codes *
2472 smb_SetSMBParmLong(outp, 9, 0x251);
2473 smb_SetSMBParmLong(outp, 11, 0);/* XXX server time: do we need? */
2474 smb_SetSMBParmLong(outp, 13, 0);/* XXX server date: do we need? */
2475 smb_SetSMBParm(outp, 15, 0); /* XXX server tzone: do we need? */
2476 smb_SetSMBParmByte(outp, 16, 0);/* Encryption key length */
2477 smb_SetSMBDataLength(outp, 0); /* perhaps should specify 8 bytes anyway */
2479 else if (v3ProtoIndex != -1) {
2480 smb_SetSMBParm(outp, 0, protoIndex);
2481 smb_SetSMBParm(outp, 1, 0); /* share level security, no passwd encrypt */
2482 smb_SetSMBParm(outp, 2, SMB_PACKETSIZE);
2483 smb_SetSMBParm(outp, 3, smb_maxMpxRequests); /* max multiplexed requests */
2484 smb_SetSMBParm(outp, 4, smb_maxVCPerServer); /* max VCs per consumer/server connection */
2485 smb_SetSMBParm(outp, 5, 0); /* no support of block mode for read or write */
2486 smb_SetSMBParm(outp, 6, 1); /* next 2: session key */
2487 smb_SetSMBParm(outp, 7, 1);
2488 smb_SetSMBParm(outp, 8, 0); /* XXX server time: do we need? */
2489 smb_SetSMBParm(outp, 9, 0); /* XXX server date: do we need? */
2490 smb_SetSMBParm(outp, 10, 0); /* XXX server tzone: do we need? */
2491 smb_SetSMBParm(outp, 11, 0); /* resvd */
2492 smb_SetSMBParm(outp, 12, 0); /* resvd */
2493 smb_SetSMBDataLength(outp, 0); /* perhaps should specify 8 bytes anyway */
2495 else if (coreProtoIndex != -1) {
2496 smb_SetSMBParm(outp, 0, protoIndex);
2497 smb_SetSMBDataLength(outp, 0);
2502 void smb_Daemon(void *parmp)
2509 if ((count % 360) == 0) /* every hour */
2510 smb_CalculateNowTZ();
2511 /* XXX GC dir search entries */
2515 void smb_WaitingLocksDaemon()
2517 smb_waitingLock_t *wL, *nwL;
2520 smb_packet_t *inp, *outp;
2525 lock_ObtainWrite(&smb_globalLock);
2526 nwL = smb_allWaitingLocks;
2528 osi_SleepW((long)&smb_allWaitingLocks, &smb_globalLock);
2537 lock_ObtainWrite(&smb_globalLock);
2539 nwL = (smb_waitingLock_t *) osi_QNext(&wL->q);
2540 lock_ReleaseWrite(&smb_globalLock);
2541 code = cm_RetryLock((cm_file_lock_t *) wL->lockp,
2542 wL->vcp->flags & SMB_VCFLAG_ALREADYDEAD);
2543 if (code == CM_ERROR_WOULDBLOCK) {
2545 if (wL->timeRemaining != 0xffffffff
2546 && (wL->timeRemaining -= 1000) < 0)
2555 ncbp->ncb_length = inp->ncb_length;
2556 inp->spacep = cm_GetSpace();
2558 /* Remove waitingLock from list */
2559 lock_ObtainWrite(&smb_globalLock);
2560 osi_QRemove((osi_queue_t **)&smb_allWaitingLocks,
2562 lock_ReleaseWrite(&smb_globalLock);
2564 /* Resume packet processing */
2566 smb_SetSMBDataLength(outp, 0);
2567 outp->flags |= SMB_PACKETFLAG_SUSPENDED;
2568 outp->resumeCode = code;
2570 smb_DispatchPacket(vcp, inp, outp, ncbp, NULL);
2573 cm_FreeSpace(inp->spacep);
2574 smb_FreePacket(inp);
2575 smb_FreePacket(outp);
2583 long smb_ReceiveCoreGetDiskAttributes(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2585 osi_Log0(afsd_logp, "SMB receive get disk attributes");
2587 smb_SetSMBParm(outp, 0, 32000);
2588 smb_SetSMBParm(outp, 1, 64);
2589 smb_SetSMBParm(outp, 2, 1024);
2590 smb_SetSMBParm(outp, 3, 30000);
2591 smb_SetSMBParm(outp, 4, 0);
2592 smb_SetSMBDataLength(outp, 0);
2596 long smb_ReceiveCoreTreeConnect(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *rsp)
2599 unsigned short newTid;
2600 char shareName[256];
2608 osi_Log0(afsd_logp, "SMB receive tree connect");
2610 /* parse input parameters */
2611 tp = smb_GetSMBData(inp, NULL);
2612 pathp = smb_ParseASCIIBlock(tp, &tp);
2613 passwordp = smb_ParseASCIIBlock(tp, &tp);
2614 tp = strrchr(pathp, '\\');
2616 return CM_ERROR_BADSMB;
2617 strcpy(shareName, tp+1);
2619 userp = smb_GetUser(vcp, inp);
2621 lock_ObtainMutex(&vcp->mx);
2622 newTid = vcp->tidCounter++;
2623 lock_ReleaseMutex(&vcp->mx);
2625 tidp = smb_FindTID(vcp, newTid, SMB_FLAG_CREATE);
2626 shareFound = smb_FindShare(vcp, inp, shareName, &sharePath);
2628 smb_ReleaseTID(tidp);
2629 return CM_ERROR_BADSHARENAME;
2631 lock_ObtainMutex(&tidp->mx);
2632 tidp->userp = userp;
2633 tidp->pathname = sharePath;
2634 lock_ReleaseMutex(&tidp->mx);
2635 smb_ReleaseTID(tidp);
2637 smb_SetSMBParm(rsp, 0, SMB_PACKETSIZE);
2638 smb_SetSMBParm(rsp, 1, newTid);
2639 smb_SetSMBDataLength(rsp, 0);
2641 osi_Log1(afsd_logp, "SMB tree connect created ID %d", newTid);
2645 unsigned char *smb_ParseDataBlock(unsigned char *inp, char **chainpp, int *lengthp)
2649 if (*inp++ != 0x1) return NULL;
2650 tlen = inp[0] + (inp[1]<<8);
2651 inp += 2; /* skip length field */
2654 *chainpp = inp + tlen;
2657 if (lengthp) *lengthp = tlen;
2662 /* set maskp to the mask part of the incoming path.
2663 * Mask is 11 bytes long (8.3 with the dot elided).
2664 * Returns true if succeeds with a valid name, otherwise it does
2665 * its best, but returns false.
2667 int smb_Get8Dot3MaskFromPath(unsigned char *maskp, unsigned char *pathp)
2675 /* starts off valid */
2678 /* mask starts out all blanks */
2679 memset(maskp, ' ', 11);
2681 /* find last backslash, or use whole thing if there is none */
2682 tp = strrchr(pathp, '\\');
2683 if (!tp) tp = pathp;
2684 else tp++; /* skip slash */
2688 /* names starting with a dot are illegal */
2689 if (*tp == '.') valid8Dot3 = 0;
2693 if (tc == 0) return valid8Dot3;
2694 if (tc == '.' || tc == '"') break;
2695 if (i < 8) *up++ = tc;
2696 else valid8Dot3 = 0;
2699 /* if we get here, tp point after the dot */
2700 up = maskp+8; /* ext goes here */
2707 if (tc == '.' || tc == '"')
2710 /* copy extension if not too long */
2720 int smb_Match8Dot3Mask(char *unixNamep, char *maskp)
2730 /* XXX redo this, calling smb_V3MatchMask with a converted mask */
2732 valid = smb_Get8Dot3MaskFromPath(umask, unixNamep);
2736 /* otherwise, we have a valid 8.3 name; see if we have a match,
2737 * treating '?' as a wildcard in maskp (but not in the file name).
2739 tp1 = umask; /* real name, in mask format */
2740 tp2 = maskp; /* mask, in mask format */
2741 for(i=0; i<11; i++) {
2742 tc1 = *tp1++; /* char from real name */
2743 tc2 = *tp2++; /* char from mask */
2744 tc1 = (char) cm_foldUpper[(unsigned char)tc1];
2745 tc2 = (char) cm_foldUpper[(unsigned char)tc2];
2748 if (tc2 == '?' && tc1 != ' ')
2755 /* we got a match */
2759 char *smb_FindMask(char *pathp)
2763 tp = strrchr(pathp, '\\'); /* find last slash */
2766 return tp+1; /* skip the slash */
2768 return pathp; /* no slash, return the entire path */
2771 long smb_ReceiveCoreSearchVolume(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2773 unsigned char *pathp;
2775 unsigned char mask[11];
2776 unsigned char *statBlockp;
2777 unsigned char initStatBlock[21];
2780 osi_Log0(afsd_logp, "SMB receive search volume");
2782 /* pull pathname and stat block out of request */
2783 tp = smb_GetSMBData(inp, NULL);
2784 pathp = smb_ParseASCIIBlock(tp, (char **) &tp);
2785 osi_assert(pathp != NULL);
2786 statBlockp = smb_ParseVblBlock(tp, (char **) &tp, &statLen);
2787 osi_assert(statBlockp != NULL);
2789 statBlockp = initStatBlock;
2793 /* for returning to caller */
2794 smb_Get8Dot3MaskFromPath(mask, pathp);
2796 smb_SetSMBParm(outp, 0, 1); /* we're returning one entry */
2797 tp = smb_GetSMBData(outp, NULL);
2799 *tp++ = 43; /* bytes in a dir entry */
2800 *tp++ = 0; /* high byte in counter */
2802 /* now marshall the dir entry, starting with the search status */
2803 *tp++ = statBlockp[0]; /* Reserved */
2804 memcpy(tp, mask, 11); tp += 11; /* FileName */
2806 /* now pass back server use info, with 1st byte non-zero */
2808 memset(tp, 0, 4); tp += 4; /* reserved for server use */
2810 memcpy(tp, statBlockp+17, 4); tp += 4; /* reserved for consumer */
2812 *tp++ = 0x8; /* attribute: volume */
2822 /* 4 byte file size */
2828 /* finally, null-terminated 8.3 pathname, which we set to AFS */
2829 memset(tp, ' ', 13);
2832 /* set the length of the data part of the packet to 43 + 3, for the dir
2833 * entry plus the 5 and the length fields.
2835 smb_SetSMBDataLength(outp, 46);
2839 long smb_ApplyDirListPatches(smb_dirListPatch_t **dirPatchespp,
2840 cm_user_t *userp, cm_req_t *reqp)
2848 smb_dirListPatch_t *patchp;
2849 smb_dirListPatch_t *npatchp;
2851 for(patchp = *dirPatchespp; patchp; patchp =
2852 (smb_dirListPatch_t *) osi_QNext(&patchp->q)) {
2853 code = cm_GetSCache(&patchp->fid, &scp, userp, reqp);
2855 lock_ObtainMutex(&scp->mx);
2856 code = cm_SyncOp(scp, NULL, userp, reqp, 0,
2857 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2859 lock_ReleaseMutex(&scp->mx);
2860 cm_ReleaseSCache(scp);
2863 dptr = patchp->dptr;
2865 attr = smb_Attributes(scp);
2866 /* check hidden attribute (the flag is only ON when dot file hiding is on ) */
2867 if( patchp->flags & SMB_DIRLISTPATCH_DOTFILE )
2868 attr |= SMB_ATTR_HIDDEN;
2872 smb_SearchTimeFromUnixTime(&dosTime, scp->clientModTime);
2875 shortTemp = dosTime & 0xffff;
2876 *((u_short *)dptr) = shortTemp;
2879 /* and copy out date */
2880 shortTemp = (dosTime>>16) & 0xffff;
2881 *((u_short *)dptr) = shortTemp;
2884 /* copy out file length */
2885 *((u_long *)dptr) = scp->length.LowPart;
2887 lock_ReleaseMutex(&scp->mx);
2888 cm_ReleaseSCache(scp);
2891 /* now free the patches */
2892 for(patchp = *dirPatchespp; patchp; patchp = npatchp) {
2893 npatchp = (smb_dirListPatch_t *) osi_QNext(&patchp->q);
2897 /* and mark the list as empty */
2898 *dirPatchespp = NULL;
2903 long smb_ReceiveCoreSearchDir(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2912 smb_dirListPatch_t *dirListPatchesp;
2913 smb_dirListPatch_t *curPatchp;
2917 osi_hyper_t dirLength;
2918 osi_hyper_t bufferOffset;
2919 osi_hyper_t curOffset;
2921 unsigned char *inCookiep;
2922 smb_dirSearch_t *dsp;
2926 unsigned long clientCookie;
2927 cm_pageHeader_t *pageHeaderp;
2928 cm_user_t *userp = NULL;
2935 long nextEntryCookie;
2936 int numDirChunks; /* # of 32 byte dir chunks in this entry */
2937 char resByte; /* reserved byte from the cookie */
2938 char *op; /* output data ptr */
2939 char *origOp; /* original value of op */
2940 cm_space_t *spacep; /* for pathname buffer */
2951 maxCount = smb_GetSMBParm(inp, 0);
2953 dirListPatchesp = NULL;
2955 caseFold = CM_FLAG_CASEFOLD;
2957 tp = smb_GetSMBData(inp, NULL);
2958 pathp = smb_ParseASCIIBlock(tp, &tp);
2959 inCookiep = smb_ParseVblBlock(tp, &tp, &dataLength);
2961 /* bail out if request looks bad */
2962 if (!tp || !pathp) {
2963 return CM_ERROR_BADSMB;
2966 /* We can handle long names */
2967 if (vcp->flags & SMB_VCFLAG_USENT)
2968 ((smb_t *)outp)->flg2 |= 0x40; /* IS_LONG_NAME */
2970 /* make sure we got a whole search status */
2971 if (dataLength < 21) {
2972 nextCookie = 0; /* start at the beginning of the dir */
2975 attribute = smb_GetSMBParm(inp, 1);
2977 /* handle volume info in another function */
2978 if (attribute & 0x8)
2979 return smb_ReceiveCoreSearchVolume(vcp, inp, outp);
2981 osi_Log2(afsd_logp, "SMB receive search dir count %d [%s]",
2982 maxCount, osi_LogSaveString(afsd_logp, pathp));
2984 if (*pathp == 0) { /* null pathp, treat as root dir */
2985 if (!(attribute & SMB_ATTR_DIRECTORY)) /* exclude dirs */
2986 return CM_ERROR_NOFILES;
2990 dsp = smb_NewDirSearch(0);
2991 dsp->attribute = attribute;
2992 smb_Get8Dot3MaskFromPath(mask, pathp);
2993 memcpy(dsp->mask, mask, 11);
2995 /* track if this is likely to match a lot of entries */
2996 if (smb_IsStarMask(mask)) starPattern = 1;
2997 else starPattern = 0;
3000 /* pull the next cookie value out of the search status block */
3001 nextCookie = inCookiep[13] + (inCookiep[14]<<8) + (inCookiep[15]<<16)
3002 + (inCookiep[16]<<24);
3003 dsp = smb_FindDirSearch(inCookiep[12]);
3005 /* can't find dir search status; fatal error */
3006 return CM_ERROR_BADFD;
3008 attribute = dsp->attribute;
3009 resByte = inCookiep[0];
3011 /* copy out client cookie, in host byte order. Don't bother
3012 * interpreting it, since we're just passing it through, anyway.
3014 memcpy(&clientCookie, &inCookiep[17], 4);
3016 memcpy(mask, dsp->mask, 11);
3018 /* assume we're doing a star match if it has continued for more
3024 osi_Log3(afsd_logp, "SMB dir search cookie 0x%x, connection %d, attr 0x%x",
3025 nextCookie, dsp->cookie, attribute);
3027 userp = smb_GetUser(vcp, inp);
3029 /* try to get the vnode for the path name next */
3030 lock_ObtainMutex(&dsp->mx);
3037 spacep = inp->spacep;
3038 smb_StripLastComponent(spacep->data, NULL, pathp);
3039 lock_ReleaseMutex(&dsp->mx);
3040 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3041 code = cm_NameI(cm_rootSCachep, spacep->data,
3042 caseFold | CM_FLAG_FOLLOW, userp, tidPathp, &req, &scp);
3043 lock_ObtainMutex(&dsp->mx);
3045 if (dsp->scp != 0) cm_ReleaseSCache(dsp->scp);
3047 /* we need one hold for the entry we just stored into,
3048 * and one for our own processing. When we're done with this
3049 * function, we'll drop the one for our own processing.
3050 * We held it once from the namei call, and so we do another hold
3054 lock_ObtainMutex(&scp->mx);
3055 if ((scp->flags & CM_SCACHEFLAG_BULKSTATTING) == 0
3056 && LargeIntegerGreaterOrEqualToZero(scp->bulkStatProgress)) {
3057 scp->flags |= CM_SCACHEFLAG_BULKSTATTING;
3058 dsp->flags |= SMB_DIRSEARCH_BULKST;
3060 lock_ReleaseMutex(&scp->mx);
3063 lock_ReleaseMutex(&dsp->mx);
3065 cm_ReleaseUser(userp);
3066 smb_DeleteDirSearch(dsp);
3067 smb_ReleaseDirSearch(dsp);
3071 /* reserves space for parameter; we'll adjust it again later to the
3072 * real count of the # of entries we returned once we've actually
3073 * assembled the directory listing.
3075 smb_SetSMBParm(outp, 0, 0);
3077 /* get the directory size */
3078 lock_ObtainMutex(&scp->mx);
3079 code = cm_SyncOp(scp, NULL, userp, &req, 0,
3080 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3082 lock_ReleaseMutex(&scp->mx);
3083 cm_ReleaseSCache(scp);
3084 cm_ReleaseUser(userp);
3085 smb_DeleteDirSearch(dsp);
3086 smb_ReleaseDirSearch(dsp);
3090 dirLength = scp->length;
3092 bufferOffset.LowPart = bufferOffset.HighPart = 0;
3093 curOffset.HighPart = 0;
3094 curOffset.LowPart = nextCookie;
3095 origOp = op = smb_GetSMBData(outp, NULL);
3096 /* and write out the basic header */
3097 *op++ = 5; /* variable block */
3098 op += 2; /* skip vbl block length; we'll fill it in later */
3102 /* make sure that curOffset.LowPart doesn't point to the first
3103 * 32 bytes in the 2nd through last dir page, and that it doesn't
3104 * point at the first 13 32-byte chunks in the first dir page,
3105 * since those are dir and page headers, and don't contain useful
3108 temp = curOffset.LowPart & (2048-1);
3109 if (curOffset.HighPart == 0 && curOffset.LowPart < 2048) {
3110 /* we're in the first page */
3111 if (temp < 13*32) temp = 13*32;
3114 /* we're in a later dir page */
3115 if (temp < 32) temp = 32;
3118 /* make sure the low order 5 bits are zero */
3121 /* now put temp bits back ito curOffset.LowPart */
3122 curOffset.LowPart &= ~(2048-1);
3123 curOffset.LowPart |= temp;
3125 /* check if we've returned all the names that will fit in the
3128 if (returnedNames >= maxCount)
3131 /* check if we've passed the dir's EOF */
3132 if (LargeIntegerGreaterThanOrEqualTo(curOffset, dirLength)) break;
3134 /* see if we can use the bufferp we have now; compute in which page
3135 * the current offset would be, and check whether that's the offset
3136 * of the buffer we have. If not, get the buffer.
3138 thyper.HighPart = curOffset.HighPart;
3139 thyper.LowPart = curOffset.LowPart & ~(buf_bufferSize-1);
3140 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
3143 buf_Release(bufferp);
3146 lock_ReleaseMutex(&scp->mx);
3147 lock_ObtainRead(&scp->bufCreateLock);
3148 code = buf_Get(scp, &thyper, &bufferp);
3149 lock_ReleaseRead(&scp->bufCreateLock);
3151 /* now, if we're doing a star match, do bulk fetching of all of
3152 * the status info for files in the dir.
3155 smb_ApplyDirListPatches(&dirListPatchesp, userp,
3157 if ((dsp->flags & SMB_DIRSEARCH_BULKST)
3158 && LargeIntegerGreaterThanOrEqualTo(thyper,
3159 scp->bulkStatProgress)) {
3160 /* Don't bulk stat if risking timeout */
3161 int now = GetCurrentTime();
3162 if (now - req.startTime > 5000) {
3163 scp->bulkStatProgress = thyper;
3164 scp->flags &= ~CM_SCACHEFLAG_BULKSTATTING;
3165 dsp->flags &= ~SMB_DIRSEARCH_BULKST;
3167 cm_TryBulkStat(scp, &thyper, userp, &req);
3171 lock_ObtainMutex(&scp->mx);
3174 bufferOffset = thyper;
3176 /* now get the data in the cache */
3178 code = cm_SyncOp(scp, bufferp, userp, &req,
3180 CM_SCACHESYNC_NEEDCALLBACK
3181 | CM_SCACHESYNC_READ);
3184 if (cm_HaveBuffer(scp, bufferp, 0)) break;
3186 /* otherwise, load the buffer and try again */
3187 code = cm_GetBuffer(scp, bufferp, NULL, userp,
3192 buf_Release(bufferp);
3196 } /* if (wrong buffer) ... */
3198 /* now we have the buffer containing the entry we're interested in; copy
3199 * it out if it represents a non-deleted entry.
3201 entryInDir = curOffset.LowPart & (2048-1);
3202 entryInBuffer = curOffset.LowPart & (buf_bufferSize - 1);
3204 /* page header will help tell us which entries are free. Page header
3205 * can change more often than once per buffer, since AFS 3 dir page size
3206 * may be less than (but not more than a buffer package buffer.
3208 temp = curOffset.LowPart & (buf_bufferSize - 1); /* only look intra-buffer */
3209 temp &= ~(2048 - 1); /* turn off intra-page bits */
3210 pageHeaderp = (cm_pageHeader_t *) (bufferp->datap + temp);
3212 /* now determine which entry we're looking at in the page. If it is
3213 * free (there's a free bitmap at the start of the dir), we should
3214 * skip these 32 bytes.
3216 slotInPage = (entryInDir & 0x7e0) >> 5;
3217 if (!(pageHeaderp->freeBitmap[slotInPage>>3] & (1 << (slotInPage & 0x7)))) {
3218 /* this entry is free */
3219 numDirChunks = 1; /* only skip this guy */
3223 tp = bufferp->datap + entryInBuffer;
3224 dep = (cm_dirEntry_t *) tp; /* now points to AFS3 dir entry */
3226 /* while we're here, compute the next entry's location, too,
3227 * since we'll need it when writing out the cookie into the dir
3230 * XXXX Probably should do more sanity checking.
3232 numDirChunks = cm_NameEntries(dep->name, NULL);
3234 /* compute the offset of the cookie representing the next entry */
3235 nextEntryCookie = curOffset.LowPart + (CM_DIR_CHUNKSIZE * numDirChunks);
3237 /* Compute 8.3 name if necessary */
3238 actualName = dep->name;
3239 if (dep->fid.vnode != 0 && !cm_Is8Dot3(actualName)) {
3240 cm_Gen8Dot3Name(dep, shortName, &shortNameEnd);
3241 actualName = shortName;
3244 if (dep->fid.vnode != 0 && smb_Match8Dot3Mask(actualName, mask)) {
3245 /* this is one of the entries to use: it is not deleted
3246 * and it matches the star pattern we're looking for.
3249 /* Eliminate entries that don't match requested
3252 /* no hidden files */
3253 if(smb_hideDotFiles && !(dsp->attribute & SMB_ATTR_HIDDEN) && smb_IsDotFile(actualName))
3256 if (!(dsp->attribute & SMB_ATTR_DIRECTORY)) /* no directories */
3258 /* We have already done the cm_TryBulkStat above */
3259 fid.cell = scp->fid.cell;
3260 fid.volume = scp->fid.volume;
3261 fid.vnode = ntohl(dep->fid.vnode);
3262 fid.unique = ntohl(dep->fid.unique);
3263 fileType = cm_FindFileType(&fid);
3264 osi_Log2(afsd_logp, "smb_ReceiveCoreSearchDir: file %s "
3265 "has filetype %d", dep->name,
3267 if (fileType == CM_SCACHETYPE_DIRECTORY)
3272 memcpy(op, mask, 11); op += 11;
3273 *op++ = (char) dsp->cookie; /* they say it must be non-zero */
3274 *op++ = nextEntryCookie & 0xff;
3275 *op++ = (nextEntryCookie>>8) & 0xff;
3276 *op++ = (nextEntryCookie>>16) & 0xff;
3277 *op++ = (nextEntryCookie>>24) & 0xff;
3278 memcpy(op, &clientCookie, 4); op += 4;
3280 /* now we emit the attribute. This is sort of tricky,
3281 * since we need to really stat the file to find out
3282 * what type of entry we've got. Right now, we're
3283 * copying out data from a buffer, while holding the
3284 * scp locked, so it isn't really convenient to stat
3285 * something now. We'll put in a place holder now,
3286 * and make a second pass before returning this to get
3287 * the real attributes. So, we just skip the data for
3288 * now, and adjust it later. We allocate a patch
3289 * record to make it easy to find this point later.
3290 * The replay will happen at a time when it is safe to
3291 * unlock the directory.
3293 curPatchp = malloc(sizeof(*curPatchp));
3294 osi_QAdd((osi_queue_t **) &dirListPatchesp, &curPatchp->q);
3295 curPatchp->dptr = op;
3296 curPatchp->fid.cell = scp->fid.cell;
3297 curPatchp->fid.volume = scp->fid.volume;
3298 curPatchp->fid.vnode = ntohl(dep->fid.vnode);
3299 curPatchp->fid.unique = ntohl(dep->fid.unique);
3301 /* do hidden attribute here since name won't be around when applying
3305 if ( smb_hideDotFiles && smb_IsDotFile(actualName) )
3306 curPatchp->flags = SMB_DIRLISTPATCH_DOTFILE;
3308 curPatchp->flags = 0;
3310 op += 9; /* skip attr, time, date and size */
3312 /* zero out name area. The spec says to pad with
3313 * spaces, but Samba doesn't, and neither do we.
3317 /* finally, we get to copy out the name; we know that
3318 * it fits in 8.3 or the pattern wouldn't match, but it
3319 * never hurts to be sure.
3321 strncpy(op, actualName, 13);
3323 /* Uppercase if requested by client */
3324 if ((((smb_t *)inp)->flg2 & 1) == 0)
3329 /* now, adjust the # of entries copied */
3331 } /* if we're including this name */
3334 /* and adjust curOffset to be where the new cookie is */
3335 thyper.HighPart = 0;
3336 thyper.LowPart = CM_DIR_CHUNKSIZE * numDirChunks;
3337 curOffset = LargeIntegerAdd(thyper, curOffset);
3338 } /* while copying data for dir listing */
3340 /* release the mutex */
3341 lock_ReleaseMutex(&scp->mx);
3342 if (bufferp) buf_Release(bufferp);
3344 /* apply and free last set of patches; if not doing a star match, this
3345 * will be empty, but better safe (and freeing everything) than sorry.
3347 smb_ApplyDirListPatches(&dirListPatchesp, userp, &req);
3349 /* special return code for unsuccessful search */
3350 if (code == 0 && dataLength < 21 && returnedNames == 0)
3351 code = CM_ERROR_NOFILES;
3353 osi_Log2(afsd_logp, "SMB search dir done, %d names, code %d",
3354 returnedNames, code);
3357 smb_DeleteDirSearch(dsp);
3358 smb_ReleaseDirSearch(dsp);
3359 cm_ReleaseSCache(scp);
3360 cm_ReleaseUser(userp);
3364 /* finalize the output buffer */
3365 smb_SetSMBParm(outp, 0, returnedNames);
3366 temp = (long) (op - origOp);
3367 smb_SetSMBDataLength(outp, temp);
3369 /* the data area is a variable block, which has a 5 (already there)
3370 * followed by the length of the # of data bytes. We now know this to
3371 * be "temp," although that includes the 3 bytes of vbl block header.
3372 * Deduct for them and fill in the length field.
3374 temp -= 3; /* deduct vbl block info */
3375 osi_assert(temp == (43 * returnedNames));
3376 origOp[1] = temp & 0xff;
3377 origOp[2] = (temp>>8) & 0xff;
3378 if (returnedNames == 0) smb_DeleteDirSearch(dsp);
3379 smb_ReleaseDirSearch(dsp);
3380 cm_ReleaseSCache(scp);
3381 cm_ReleaseUser(userp);
3385 /* verify that this is a valid path to a directory. I don't know why they
3386 * don't use the get file attributes call.
3388 long smb_ReceiveCoreCheckPath(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3392 cm_scache_t *rootScp;
3393 cm_scache_t *newScp;
3402 pathp = smb_GetSMBData(inp, NULL);
3403 pathp = smb_ParseASCIIBlock(pathp, NULL);
3404 osi_Log1(afsd_logp, "SMB receive check path %s",
3405 osi_LogSaveString(afsd_logp, pathp));
3408 return CM_ERROR_BADFD;
3411 rootScp = cm_rootSCachep;
3413 userp = smb_GetUser(vcp, inp);
3415 caseFold = CM_FLAG_CASEFOLD;
3417 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3418 code = cm_NameI(rootScp, pathp,
3419 caseFold | CM_FLAG_FOLLOW | CM_FLAG_CHECKPATH,
3420 userp, tidPathp, &req, &newScp);
3423 cm_ReleaseUser(userp);
3427 /* now lock the vnode with a callback; returns with newScp locked */
3428 lock_ObtainMutex(&newScp->mx);
3429 code = cm_SyncOp(newScp, NULL, userp, &req, PRSFS_LOOKUP,
3430 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
3431 if (code && code != CM_ERROR_NOACCESS) {
3432 lock_ReleaseMutex(&newScp->mx);
3433 cm_ReleaseSCache(newScp);
3434 cm_ReleaseUser(userp);
3438 attrs = smb_Attributes(newScp);
3440 if (!(attrs & 0x10))
3441 code = CM_ERROR_NOTDIR;
3443 lock_ReleaseMutex(&newScp->mx);
3445 cm_ReleaseSCache(newScp);
3446 cm_ReleaseUser(userp);
3450 long smb_ReceiveCoreSetFileAttributes(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3454 cm_scache_t *rootScp;
3455 unsigned short attribute;
3457 cm_scache_t *newScp;
3466 /* decode basic attributes we're passed */
3467 attribute = smb_GetSMBParm(inp, 0);
3468 dosTime = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
3470 pathp = smb_GetSMBData(inp, NULL);
3471 pathp = smb_ParseASCIIBlock(pathp, NULL);
3474 return CM_ERROR_BADSMB;
3477 osi_Log2(afsd_logp, "SMB receive setfile attributes time %d, attr 0x%x",
3478 dosTime, attribute);
3480 rootScp = cm_rootSCachep;
3482 userp = smb_GetUser(vcp, inp);
3484 caseFold = CM_FLAG_CASEFOLD;
3486 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3487 code = cm_NameI(rootScp, pathp, caseFold | CM_FLAG_FOLLOW, userp,
3488 tidPathp, &req, &newScp);
3491 cm_ReleaseUser(userp);
3495 /* now lock the vnode with a callback; returns with newScp locked; we
3496 * need the current status to determine what the new status is, in some
3499 lock_ObtainMutex(&newScp->mx);
3500 code = cm_SyncOp(newScp, NULL, userp, &req, 0,
3501 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
3503 lock_ReleaseMutex(&newScp->mx);
3504 cm_ReleaseSCache(newScp);
3505 cm_ReleaseUser(userp);
3509 /* Check for RO volume */
3510 if (newScp->flags & CM_SCACHEFLAG_RO) {
3511 lock_ReleaseMutex(&newScp->mx);
3512 cm_ReleaseSCache(newScp);
3513 cm_ReleaseUser(userp);
3514 return CM_ERROR_READONLY;
3517 /* prepare for setattr call */
3520 attr.mask |= CM_ATTRMASK_CLIENTMODTIME;
3521 smb_UnixTimeFromDosUTime(&attr.clientModTime, dosTime);
3523 if ((newScp->unixModeBits & 0222) && (attribute & 1) != 0) {
3524 /* we're told to make a writable file read-only */
3525 attr.unixModeBits = newScp->unixModeBits & ~0222;
3526 attr.mask |= CM_ATTRMASK_UNIXMODEBITS;
3528 else if ((newScp->unixModeBits & 0222) == 0 && (attribute & 1) == 0) {
3529 /* we're told to make a read-only file writable */
3530 attr.unixModeBits = newScp->unixModeBits | 0222;
3531 attr.mask |= CM_ATTRMASK_UNIXMODEBITS;
3533 lock_ReleaseMutex(&newScp->mx);
3535 /* now call setattr */
3537 code = cm_SetAttr(newScp, &attr, userp, &req);
3541 cm_ReleaseSCache(newScp);
3542 cm_ReleaseUser(userp);
3547 long smb_ReceiveCoreGetFileAttributes(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3551 cm_scache_t *rootScp;
3552 cm_scache_t *newScp, *dscp;
3564 pathp = smb_GetSMBData(inp, NULL);
3565 pathp = smb_ParseASCIIBlock(pathp, NULL);
3568 return CM_ERROR_BADSMB;
3571 if (*pathp == 0) /* null path */
3574 osi_Log1(afsd_logp, "SMB receive getfile attributes path %s",
3575 osi_LogSaveString(afsd_logp, pathp));
3577 rootScp = cm_rootSCachep;
3579 userp = smb_GetUser(vcp, inp);
3581 /* we shouldn't need this for V3 requests, but we seem to */
3582 caseFold = CM_FLAG_CASEFOLD;
3584 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3587 * XXX Strange hack XXX
3589 * As of Patch 5 (16 July 97), we are having the following problem:
3590 * In NT Explorer 4.0, whenever we click on a directory, AFS gets
3591 * requests to look up "desktop.ini" in all the subdirectories.
3592 * This can cause zillions of timeouts looking up non-existent cells
3593 * and volumes, especially in the top-level directory.
3595 * We have not found any way to avoid this or work around it except
3596 * to explicitly ignore the requests for mount points that haven't
3597 * yet been evaluated and for directories that haven't yet been
3600 * We should modify this hack to provide a fake desktop.ini file
3601 * http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/custom.asp
3603 spacep = inp->spacep;
3604 smb_StripLastComponent(spacep->data, &lastComp, pathp);
3605 if (lastComp && stricmp(lastComp, "\\desktop.ini") == 0) {
3606 code = cm_NameI(rootScp, spacep->data,
3607 caseFold | CM_FLAG_DIRSEARCH | CM_FLAG_FOLLOW,
3608 userp, tidPathp, &req, &dscp);
3610 if (dscp->fileType == CM_SCACHETYPE_MOUNTPOINT
3611 && !dscp->mountRootFidp)
3612 code = CM_ERROR_NOSUCHFILE;
3613 else if (dscp->fileType == CM_SCACHETYPE_DIRECTORY) {
3614 cm_buf_t *bp = buf_Find(dscp, &hzero);
3618 code = CM_ERROR_NOSUCHFILE;
3620 cm_ReleaseSCache(dscp);
3622 cm_ReleaseUser(userp);
3628 code = cm_NameI(rootScp, pathp, caseFold | CM_FLAG_FOLLOW, userp,
3629 tidPathp, &req, &newScp);
3632 cm_ReleaseUser(userp);
3636 /* now lock the vnode with a callback; returns with newScp locked */
3637 lock_ObtainMutex(&newScp->mx);
3638 code = cm_SyncOp(newScp, NULL, userp, &req, 0,
3639 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
3641 lock_ReleaseMutex(&newScp->mx);
3642 cm_ReleaseSCache(newScp);
3643 cm_ReleaseUser(userp);
3648 /* use smb_Attributes instead. Also the fact that a file is
3649 * in a readonly volume doesn't mean it shojuld be marked as RO
3651 if (newScp->fileType == CM_SCACHETYPE_DIRECTORY
3652 || newScp->fileType == CM_SCACHETYPE_MOUNTPOINT)
3653 attrs = SMB_ATTR_DIRECTORY;
3656 if ((newScp->unixModeBits & 0222) == 0 || (newScp->flags & CM_SCACHEFLAG_RO))
3657 attrs |= SMB_ATTR_READONLY; /* turn on read-only flag */
3659 attrs = smb_Attributes(newScp);
3662 smb_SetSMBParm(outp, 0, attrs);
3664 smb_DosUTimeFromUnixTime(&dosTime, newScp->clientModTime);
3665 smb_SetSMBParm(outp, 1, dosTime & 0xffff);
3666 smb_SetSMBParm(outp, 2, (dosTime>>16) & 0xffff);
3667 smb_SetSMBParm(outp, 3, newScp->length.LowPart & 0xffff);
3668 smb_SetSMBParm(outp, 4, (newScp->length.LowPart >> 16) & 0xffff);
3669 smb_SetSMBParm(outp, 5, 0);
3670 smb_SetSMBParm(outp, 6, 0);
3671 smb_SetSMBParm(outp, 7, 0);
3672 smb_SetSMBParm(outp, 8, 0);
3673 smb_SetSMBParm(outp, 9, 0);
3674 smb_SetSMBDataLength(outp, 0);
3675 lock_ReleaseMutex(&newScp->mx);
3677 cm_ReleaseSCache(newScp);
3678 cm_ReleaseUser(userp);
3683 long smb_ReceiveCoreTreeDisconnect(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3687 osi_Log0(afsd_logp, "SMB receive tree disconnect");
3689 /* find the tree and free it */
3690 tidp = smb_FindTID(vcp, ((smb_t *)inp)->tid, 0);
3692 lock_ObtainMutex(&tidp->mx);
3693 tidp->flags |= SMB_TIDFLAG_DELETE;
3694 lock_ReleaseMutex(&tidp->mx);
3695 smb_ReleaseTID(tidp);
3701 long smb_ReceiveCoreOpen(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3719 pathp = smb_GetSMBData(inp, NULL);
3720 pathp = smb_ParseASCIIBlock(pathp, NULL);
3722 osi_Log1(afsd_logp, "SMB receive open file [%s]", osi_LogSaveString(afsd_logp, pathp));
3724 #ifdef DEBUG_VERBOSE
3728 hexpath = osi_HexifyString( pathp );
3729 DEBUG_EVENT2("AFS", "CoreOpen H[%s] A[%s]", hexpath, pathp);
3734 share = smb_GetSMBParm(inp, 0);
3735 attribute = smb_GetSMBParm(inp, 1);
3737 spacep = inp->spacep;
3738 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
3739 if (lastNamep && strcmp(lastNamep, SMB_IOCTL_FILENAME) == 0) {
3740 /* special case magic file name for receiving IOCTL requests
3741 * (since IOCTL calls themselves aren't getting through).
3743 fidp = smb_FindFID(vcp, 0, SMB_FLAG_CREATE);
3744 smb_SetupIoctlFid(fidp, spacep);
3745 smb_SetSMBParm(outp, 0, fidp->fid);
3746 smb_SetSMBParm(outp, 1, 0); /* attrs */
3747 smb_SetSMBParm(outp, 2, 0); /* next 2 are DOS time */
3748 smb_SetSMBParm(outp, 3, 0);
3749 smb_SetSMBParm(outp, 4, 0); /* next 2 are length */
3750 smb_SetSMBParm(outp, 5, 0x7fff);
3751 /* pass the open mode back */
3752 smb_SetSMBParm(outp, 6, (share & 0xf));
3753 smb_SetSMBDataLength(outp, 0);
3754 smb_ReleaseFID(fidp);
3758 userp = smb_GetUser(vcp, inp);
3760 caseFold = CM_FLAG_CASEFOLD;
3762 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3763 code = cm_NameI(cm_rootSCachep, pathp, caseFold | CM_FLAG_FOLLOW, userp,
3764 tidPathp, &req, &scp);
3767 cm_ReleaseUser(userp);
3771 code = cm_CheckOpen(scp, share & 0x7, 0, userp, &req);
3773 cm_ReleaseSCache(scp);
3774 cm_ReleaseUser(userp);
3778 /* don't need callback to check file type, since file types never
3779 * change, and namei and cm_Lookup all stat the object at least once on
3780 * a successful return.
3782 if (scp->fileType != CM_SCACHETYPE_FILE) {
3783 cm_ReleaseSCache(scp);
3784 cm_ReleaseUser(userp);
3785 return CM_ERROR_ISDIR;
3788 fidp = smb_FindFID(vcp, 0, SMB_FLAG_CREATE);
3791 /* save a pointer to the vnode */
3794 if ((share & 0xf) == 0)
3795 fidp->flags |= SMB_FID_OPENREAD;
3796 else if ((share & 0xf) == 1)
3797 fidp->flags |= SMB_FID_OPENWRITE;
3799 fidp->flags |= (SMB_FID_OPENREAD | SMB_FID_OPENWRITE);
3801 lock_ObtainMutex(&scp->mx);
3802 smb_SetSMBParm(outp, 0, fidp->fid);
3803 smb_SetSMBParm(outp, 1, smb_Attributes(scp));
3804 smb_DosUTimeFromUnixTime(&dosTime, scp->clientModTime);
3805 smb_SetSMBParm(outp, 2, dosTime & 0xffff);
3806 smb_SetSMBParm(outp, 3, (dosTime >> 16) & 0xffff);
3807 smb_SetSMBParm(outp, 4, scp->length.LowPart & 0xffff);
3808 smb_SetSMBParm(outp, 5, (scp->length.LowPart >> 16) & 0xffff);
3809 /* pass the open mode back; XXXX add access checks */
3810 smb_SetSMBParm(outp, 6, (share & 0xf));
3811 smb_SetSMBDataLength(outp, 0);
3812 lock_ReleaseMutex(&scp->mx);
3815 cm_Open(scp, 0, userp);
3817 /* send and free packet */
3818 smb_ReleaseFID(fidp);
3819 cm_ReleaseUser(userp);
3820 /* don't release scp, since we've squirreled away the pointer in the fid struct */
3824 typedef struct smb_unlinkRock {
3829 char *maskp; /* pointer to the star pattern */
3834 int smb_UnlinkProc(cm_scache_t *dscp, cm_dirEntry_t *dep, void *vrockp, osi_hyper_t *offp)
3837 smb_unlinkRock_t *rockp;
3845 if (rockp->vcp->flags & SMB_VCFLAG_USEV3)
3846 caseFold = CM_FLAG_CASEFOLD;
3848 caseFold = CM_FLAG_CASEFOLD | CM_FLAG_8DOT3;
3850 matchName = dep->name;
3851 match = smb_V3MatchMask(matchName, rockp->maskp, caseFold);
3854 && !cm_Is8Dot3(dep->name)) {
3855 cm_Gen8Dot3Name(dep, shortName, NULL);
3856 matchName = shortName;
3857 match = smb_V3MatchMask(matchName, rockp->maskp, caseFold);
3860 osi_Log1(smb_logp, "Unlinking %s",
3861 osi_LogSaveString(smb_logp, matchName));
3862 code = cm_Unlink(dscp, dep->name, rockp->userp, rockp->reqp);
3863 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
3864 smb_NotifyChange(FILE_ACTION_REMOVED,
3865 FILE_NOTIFY_CHANGE_FILE_NAME,
3866 dscp, dep->name, NULL, TRUE);
3875 long smb_ReceiveCoreUnlink(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3884 smb_unlinkRock_t rock;
3893 attribute = smb_GetSMBParm(inp, 0);
3895 tp = smb_GetSMBData(inp, NULL);
3896 pathp = smb_ParseASCIIBlock(tp, &tp);
3898 osi_Log1(smb_logp, "SMB receive unlink %s",
3899 osi_LogSaveString(smb_logp, pathp));
3901 spacep = inp->spacep;
3902 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
3904 userp = smb_GetUser(vcp, inp);
3906 caseFold = CM_FLAG_FOLLOW | CM_FLAG_CASEFOLD;
3908 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3909 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold, userp, tidPathp,
3913 cm_ReleaseUser(userp);
3917 /* otherwise, scp points to the parent directory. */
3924 rock.maskp = smb_FindMask(pathp);
3925 rock.hasTilde = ((strchr(rock.maskp, '~') != NULL) ? 1 : 0);
3928 thyper.HighPart = 0;
3933 code = cm_ApplyDir(dscp, smb_UnlinkProc, &rock, &thyper, userp, &req, NULL);
3935 cm_ReleaseUser(userp);
3937 cm_ReleaseSCache(dscp);
3939 if (code == 0 && !rock.any)
3940 code = CM_ERROR_NOSUCHFILE;
3944 typedef struct smb_renameRock {
3945 cm_scache_t *odscp; /* old dir */
3946 cm_scache_t *ndscp; /* new dir */
3947 cm_user_t *userp; /* user */
3948 cm_req_t *reqp; /* request struct */
3949 smb_vc_t *vcp; /* virtual circuit */
3950 char *maskp; /* pointer to star pattern of old file name */
3951 int hasTilde; /* star pattern might be shortname? */
3952 char *newNamep; /* ptr to the new file's name */
3955 int smb_RenameProc(cm_scache_t *dscp, cm_dirEntry_t *dep, void *vrockp, osi_hyper_t *offp)
3958 smb_renameRock_t *rockp;
3965 if (rockp->vcp->flags & SMB_VCFLAG_USEV3)
3966 caseFold = CM_FLAG_CASEFOLD;
3968 caseFold = CM_FLAG_CASEFOLD | CM_FLAG_8DOT3;
3970 match = smb_V3MatchMask(dep->name, rockp->maskp, caseFold);
3973 && !cm_Is8Dot3(dep->name)) {
3974 cm_Gen8Dot3Name(dep, shortName, NULL);
3975 match = smb_V3MatchMask(shortName, rockp->maskp, caseFold);
3978 code = cm_Rename(rockp->odscp, dep->name,
3979 rockp->ndscp, rockp->newNamep, rockp->userp,
3981 /* if the call worked, stop doing the search now, since we
3982 * really only want to rename one file.
3985 code = CM_ERROR_STOPNOW;
3992 long smb_ReceiveCoreRename(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3999 smb_renameRock_t rock;
4000 cm_scache_t *oldDscp;
4001 cm_scache_t *newDscp;
4002 cm_scache_t *tmpscp;
4014 tp = smb_GetSMBData(inp, NULL);
4015 oldPathp = smb_ParseASCIIBlock(tp, &tp);
4016 newPathp = smb_ParseASCIIBlock(tp, &tp);
4018 osi_Log2(afsd_logp, "smb rename %s to %s",
4019 osi_LogSaveString(afsd_logp, oldPathp),
4020 osi_LogSaveString(afsd_logp, newPathp));
4022 spacep = inp->spacep;
4023 smb_StripLastComponent(spacep->data, &oldLastNamep, oldPathp);
4025 userp = smb_GetUser(vcp, inp);
4028 * Changed to use CASEFOLD always. This enables us to rename Foo/baz when
4029 * what actually exists is foo/baz. I don't know why the code used to be
4030 * the way it was. 1/29/96
4032 * caseFold = ((vcp->flags & SMB_VCFLAG_USEV3) ? 0: CM_FLAG_CASEFOLD);
4034 * Changed to use CM_FLAG_FOLLOW. 7/24/96
4036 * caseFold = CM_FLAG_CASEFOLD;
4038 caseFold = CM_FLAG_FOLLOW | CM_FLAG_CASEFOLD;
4040 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
4041 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold,
4042 userp, tidPathp, &req, &oldDscp);
4045 cm_ReleaseUser(userp);
4049 smb_StripLastComponent(spacep->data, &newLastNamep, newPathp);
4050 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold,
4051 userp, tidPathp, &req, &newDscp);
4054 cm_ReleaseSCache(oldDscp);
4055 cm_ReleaseUser(userp);
4059 /* otherwise, oldDscp and newDscp point to the corresponding directories.
4060 * next, get the component names, and lower case them.
4063 /* handle the old name first */
4065 oldLastNamep = oldPathp;
4069 /* and handle the new name, too */
4071 newLastNamep = newPathp;
4075 /* do the vnode call */
4076 rock.odscp = oldDscp;
4077 rock.ndscp = newDscp;
4081 rock.maskp = oldLastNamep;
4082 rock.hasTilde = ((strchr(oldLastNamep, '~') != NULL) ? 1 : 0);
4083 rock.newNamep = newLastNamep;
4085 /* Check if the file already exists; if so return error */
4086 code = cm_Lookup(newDscp,newLastNamep,CM_FLAG_CHECKPATH,userp,&req,&tmpscp);
4087 if((code != CM_ERROR_NOSUCHFILE) && (code != CM_ERROR_NOSUCHPATH) && (code != CM_ERROR_NOSUCHVOLUME) ) {
4088 cm_ReleaseSCache(tmpscp);
4089 return CM_ERROR_EXISTS; /* file exist, do not rename, also
4094 /* Now search the directory for the pattern, and do the appropriate rename when found */
4095 thyper.LowPart = 0; /* search dir from here */
4096 thyper.HighPart = 0;
4098 code = cm_ApplyDir(oldDscp, smb_RenameProc, &rock, &thyper, userp, &req, NULL);
4100 if (code == CM_ERROR_STOPNOW)
4103 code = CM_ERROR_NOSUCHFILE;
4105 /* Handle Change Notification */
4107 * Being lazy, not distinguishing between files and dirs in this
4108 * filter, since we'd have to do a lookup.
4110 filter = FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME;
4111 if (oldDscp == newDscp) {
4112 if (oldDscp->flags & CM_SCACHEFLAG_ANYWATCH)
4113 smb_NotifyChange(FILE_ACTION_RENAMED_OLD_NAME,
4114 filter, oldDscp, oldLastNamep,
4115 newLastNamep, TRUE);
4117 if (oldDscp->flags & CM_SCACHEFLAG_ANYWATCH)
4118 smb_NotifyChange(FILE_ACTION_RENAMED_OLD_NAME,
4119 filter, oldDscp, oldLastNamep,
4121 if (newDscp->flags & CM_SCACHEFLAG_ANYWATCH)
4122 smb_NotifyChange(FILE_ACTION_RENAMED_NEW_NAME,
4123 filter, newDscp, newLastNamep,
4127 cm_ReleaseUser(userp);
4129 cm_ReleaseSCache(oldDscp);
4130 cm_ReleaseSCache(newDscp);
4135 typedef struct smb_rmdirRock {
4139 char *maskp; /* pointer to the star pattern */
4144 int smb_RmdirProc(cm_scache_t *dscp, cm_dirEntry_t *dep, void *vrockp, osi_hyper_t *offp)
4147 smb_rmdirRock_t *rockp;
4154 matchName = dep->name;
4155 match = (cm_stricmp(matchName, rockp->maskp) == 0);
4158 && !cm_Is8Dot3(dep->name)) {
4159 cm_Gen8Dot3Name(dep, shortName, NULL);
4160 matchName = shortName;
4161 match = (cm_stricmp(matchName, rockp->maskp) == 0);
4164 osi_Log1(smb_logp, "Removing directory %s",
4165 osi_LogSaveString(smb_logp, matchName));
4166 code = cm_RemoveDir(dscp, dep->name, rockp->userp, rockp->reqp);
4167 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4168 smb_NotifyChange(FILE_ACTION_REMOVED,
4169 FILE_NOTIFY_CHANGE_DIR_NAME,
4170 dscp, dep->name, NULL, TRUE);
4179 long smb_ReceiveCoreRemoveDir(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4187 smb_rmdirRock_t rock;
4196 tp = smb_GetSMBData(inp, NULL);
4197 pathp = smb_ParseASCIIBlock(tp, &tp);
4199 spacep = inp->spacep;
4200 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
4202 userp = smb_GetUser(vcp, inp);
4204 caseFold = CM_FLAG_CASEFOLD;
4206 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
4207 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold | CM_FLAG_FOLLOW,
4208 userp, tidPathp, &req, &dscp);
4211 cm_ReleaseUser(userp);
4215 /* otherwise, scp points to the parent directory. */
4222 rock.maskp = lastNamep;
4223 rock.hasTilde = ((strchr(rock.maskp, '~') != NULL) ? 1 : 0);
4226 thyper.HighPart = 0;
4230 code = cm_ApplyDir(dscp, smb_RmdirProc, &rock, &thyper, userp, &req, NULL);
4232 cm_ReleaseUser(userp);
4234 cm_ReleaseSCache(dscp);
4236 if (code == 0 && !rock.any)
4237 code = CM_ERROR_NOSUCHFILE;
4241 long smb_ReceiveCoreFlush(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4251 fid = smb_GetSMBParm(inp, 0);
4253 osi_Log1(afsd_logp, "SMB flush fid %d", fid);
4255 fid = smb_ChainFID(fid, inp);
4256 fidp = smb_FindFID(vcp, fid, 0);
4257 if (!fidp || (fidp->flags & SMB_FID_IOCTL)) {
4259 smb_ReleaseFID(fidp);
4260 return CM_ERROR_BADFD;
4263 userp = smb_GetUser(vcp, inp);
4265 lock_ObtainMutex(&fidp->mx);
4266 if (fidp->flags & SMB_FID_OPENWRITE)
4267 code = cm_FSync(fidp->scp, userp, &req);
4270 lock_ReleaseMutex(&fidp->mx);
4272 smb_ReleaseFID(fidp);
4274 cm_ReleaseUser(userp);
4279 struct smb_FullNameRock {
4285 int smb_FullNameProc(cm_scache_t *scp, cm_dirEntry_t *dep, void *rockp,
4289 struct smb_FullNameRock *vrockp;
4293 if (!cm_Is8Dot3(dep->name)) {
4294 cm_Gen8Dot3Name(dep, shortName, NULL);
4296 if (strcmp(shortName, vrockp->name) == 0) {
4297 vrockp->fullName = strdup(dep->name);
4298 return CM_ERROR_STOPNOW;
4301 if (stricmp(dep->name, vrockp->name) == 0
4302 && ntohl(dep->fid.vnode) == vrockp->vnode->fid.vnode
4303 && ntohl(dep->fid.unique) == vrockp->vnode->fid.unique) {
4304 vrockp->fullName = strdup(dep->name);
4305 return CM_ERROR_STOPNOW;
4310 void smb_FullName(cm_scache_t *dscp, cm_scache_t *scp, char *pathp,
4311 char **newPathp, cm_user_t *userp, cm_req_t *reqp)
4313 struct smb_FullNameRock rock;
4319 code = cm_ApplyDir(dscp, smb_FullNameProc, &rock, NULL,
4321 if (code == CM_ERROR_STOPNOW)
4322 *newPathp = rock.fullName;
4324 *newPathp = strdup(pathp);
4327 long smb_ReceiveCoreClose(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4338 fid = smb_GetSMBParm(inp, 0);
4339 dosTime = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
4341 osi_Log1(afsd_logp, "SMB close fid %d", fid);
4343 fid = smb_ChainFID(fid, inp);
4344 fidp = smb_FindFID(vcp, fid, 0);
4346 return CM_ERROR_BADFD;
4349 userp = smb_GetUser(vcp, inp);
4351 lock_ObtainMutex(&fidp->mx);
4353 /* Don't jump the gun on an async raw write */
4354 while (fidp->raw_writers) {
4355 lock_ReleaseMutex(&fidp->mx);
4356 thrd_WaitForSingleObject_Event(fidp->raw_write_event, RAWTIMEOUT);
4357 lock_ObtainMutex(&fidp->mx);
4360 fidp->flags |= SMB_FID_DELETE;
4362 /* watch for ioctl closes, and read-only opens */
4363 if (fidp->scp != NULL
4364 && (fidp->flags & (SMB_FID_OPENWRITE | SMB_FID_DELONCLOSE))
4365 == SMB_FID_OPENWRITE) {
4366 if (dosTime != 0 && dosTime != -1) {
4367 fidp->scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
4368 /* This fixes defect 10958 */
4369 CompensateForSmbClientLastWriteTimeBugs(&dosTime);
4370 smb_UnixTimeFromDosUTime(&fidp->scp->clientModTime, dosTime);
4372 code = cm_FSync(fidp->scp, userp, &req);
4377 if (fidp->flags & SMB_FID_DELONCLOSE) {
4378 cm_scache_t *dscp = fidp->NTopen_dscp;
4379 char *pathp = fidp->NTopen_pathp;
4382 smb_FullName(dscp, fidp->scp, pathp, &fullPathp, userp, &req);
4383 if (fidp->scp->fileType == CM_SCACHETYPE_DIRECTORY) {
4384 code = cm_RemoveDir(dscp, fullPathp, userp, &req);
4385 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4386 smb_NotifyChange(FILE_ACTION_REMOVED,
4387 FILE_NOTIFY_CHANGE_DIR_NAME,
4388 dscp, fullPathp, NULL, TRUE);
4392 code = cm_Unlink(dscp, fullPathp, userp, &req);
4393 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4394 smb_NotifyChange(FILE_ACTION_REMOVED,
4395 FILE_NOTIFY_CHANGE_FILE_NAME,
4396 dscp, fullPathp, NULL, TRUE);
4400 lock_ReleaseMutex(&fidp->mx);
4402 if (fidp->flags & SMB_FID_NTOPEN) {
4403 cm_ReleaseSCache(fidp->NTopen_dscp);
4404 free(fidp->NTopen_pathp);
4406 if (fidp->NTopen_wholepathp)
4407 free(fidp->NTopen_wholepathp);
4409 smb_ReleaseFID(fidp);
4410 cm_ReleaseUser(userp);
4415 * smb_ReadData -- common code for Read, Read And X, and Raw Read
4418 long smb_ReadData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4419 cm_user_t *userp, long *readp)
4421 long smb_ReadData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4422 cm_user_t *userp, long *readp, int dosflag)
4429 osi_hyper_t fileLength;
4431 osi_hyper_t lastByte;
4432 osi_hyper_t bufferOffset;
4433 long bufIndex, nbytes;
4443 lock_ObtainMutex(&fidp->mx);
4445 lock_ObtainMutex(&scp->mx);
4447 if (offset.HighPart == 0) {
4448 chunk = offset.LowPart >> cm_logChunkSize;
4449 if (chunk != fidp->curr_chunk) {
4450 fidp->prev_chunk = fidp->curr_chunk;
4451 fidp->curr_chunk = chunk;
4453 if (fidp->curr_chunk == fidp->prev_chunk + 1)
4457 /* start by looking up the file's end */
4458 code = cm_SyncOp(scp, NULL, userp, &req, 0,
4459 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
4460 if (code) goto done;
4462 /* now we have the entry locked, look up the length */
4463 fileLength = scp->length;
4465 /* adjust count down so that it won't go past EOF */
4466 thyper.LowPart = count;
4467 thyper.HighPart = 0;
4468 thyper = LargeIntegerAdd(offset, thyper); /* where read should end */
4470 if (LargeIntegerGreaterThan(thyper, fileLength)) {
4471 /* we'd read past EOF, so just stop at fileLength bytes.
4472 * Start by computing how many bytes remain in the file.
4474 thyper = LargeIntegerSubtract(fileLength, offset);
4476 /* if we are past EOF, read 0 bytes */
4477 if (LargeIntegerLessThanZero(thyper))
4480 count = thyper.LowPart;
4485 /* now, copy the data one buffer at a time,
4486 * until we've filled the request packet
4489 /* if we've copied all the data requested, we're done */
4490 if (count <= 0) break;
4492 /* otherwise, load up a buffer of data */
4493 thyper.HighPart = offset.HighPart;
4494 thyper.LowPart = offset.LowPart & ~(buf_bufferSize-1);
4495 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
4498 buf_Release(bufferp);
4501 lock_ReleaseMutex(&scp->mx);
4503 lock_ObtainRead(&scp->bufCreateLock);
4504 code = buf_Get(scp, &thyper, &bufferp);
4505 lock_ReleaseRead(&scp->bufCreateLock);
4507 lock_ObtainMutex(&scp->mx);
4508 if (code) goto done;
4509 bufferOffset = thyper;
4511 /* now get the data in the cache */
4513 code = cm_SyncOp(scp, bufferp, userp, &req, 0,
4514 CM_SCACHESYNC_NEEDCALLBACK
4515 | CM_SCACHESYNC_READ);
4516 if (code) goto done;
4518 if (cm_HaveBuffer(scp, bufferp, 0)) break;
4520 /* otherwise, load the buffer and try again */
4521 code = cm_GetBuffer(scp, bufferp, NULL, userp, &req);
4525 buf_Release(bufferp);
4529 } /* if (wrong buffer) ... */
4531 /* now we have the right buffer loaded. Copy out the
4532 * data from here to the user's buffer.
4534 bufIndex = offset.LowPart & (buf_bufferSize - 1);
4536 /* and figure out how many bytes we want from this buffer */
4537 nbytes = buf_bufferSize - bufIndex; /* what remains in buffer */
4538 if (nbytes > count) nbytes = count; /* don't go past EOF */
4540 /* now copy the data */
4543 dosmemput(bufferp->datap + bufIndex, nbytes, (dos_ptr)op);
4546 memcpy(op, bufferp->datap + bufIndex, nbytes);
4548 /* adjust counters, pointers, etc. */
4551 thyper.LowPart = nbytes;
4552 thyper.HighPart = 0;
4553 offset = LargeIntegerAdd(thyper, offset);
4557 lock_ReleaseMutex(&scp->mx);
4558 lock_ReleaseMutex(&fidp->mx);
4560 buf_Release(bufferp);
4562 if (code == 0 && sequential)
4563 cm_ConsiderPrefetch(scp, &lastByte, userp, &req);
4569 * smb_WriteData -- common code for Write and Raw Write
4572 long smb_WriteData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4573 cm_user_t *userp, long *writtenp)
4575 long smb_WriteData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4576 cm_user_t *userp, long *writtenp, int dosflag)
4583 osi_hyper_t fileLength; /* file's length at start of write */
4584 osi_hyper_t minLength; /* don't read past this */
4585 long nbytes; /* # of bytes to transfer this iteration */
4587 osi_hyper_t thyper; /* hyper tmp variable */
4588 osi_hyper_t bufferOffset;
4589 long bufIndex; /* index in buffer where our data is */
4591 osi_hyper_t writeBackOffset; /* offset of region to write back when
4602 lock_ObtainMutex(&fidp->mx);
4604 lock_ObtainMutex(&scp->mx);
4606 /* start by looking up the file's end */
4607 code = cm_SyncOp(scp, NULL, userp, &req, 0,
4608 CM_SCACHESYNC_NEEDCALLBACK
4609 | CM_SCACHESYNC_SETSTATUS
4610 | CM_SCACHESYNC_GETSTATUS);
4614 /* make sure we have a writable FD */
4615 if (!(fidp->flags & SMB_FID_OPENWRITE)) {
4616 code = CM_ERROR_BADFDOP;
4620 /* now we have the entry locked, look up the length */
4621 fileLength = scp->length;
4622 minLength = fileLength;
4623 if (LargeIntegerGreaterThan(minLength, scp->serverLength))
4624 minLength = scp->serverLength;
4626 /* adjust file length if we extend past EOF */
4627 thyper.LowPart = count;
4628 thyper.HighPart = 0;
4629 thyper = LargeIntegerAdd(offset, thyper); /* where write should end */
4630 if (LargeIntegerGreaterThan(thyper, fileLength)) {
4631 /* we'd write past EOF, so extend the file */
4632 scp->mask |= CM_SCACHEMASK_LENGTH;
4633 scp->length = thyper;
4634 filter |= (FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE);
4636 filter |= FILE_NOTIFY_CHANGE_LAST_WRITE;
4638 /* now, if the new position (thyper) and the old (offset) are in
4639 * different storeback windows, remember to store back the previous
4640 * storeback window when we're done with the write.
4642 if ((thyper.LowPart & (-cm_chunkSize)) !=
4643 (offset.LowPart & (-cm_chunkSize))) {
4644 /* they're different */
4646 writeBackOffset.HighPart = offset.HighPart;
4647 writeBackOffset.LowPart = offset.LowPart & (-cm_chunkSize);
4652 /* now, copy the data one buffer at a time, until we've filled the
4655 /* if we've copied all the data requested, we're done */
4656 if (count <= 0) break;
4658 /* handle over quota or out of space */
4659 if (scp->flags & (CM_SCACHEFLAG_OVERQUOTA | CM_SCACHEFLAG_OUTOFSPACE)) {
4660 *writtenp = written;
4664 /* otherwise, load up a buffer of data */
4665 thyper.HighPart = offset.HighPart;
4666 thyper.LowPart = offset.LowPart & ~(buf_bufferSize-1);
4667 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
4670 lock_ReleaseMutex(&bufferp->mx);
4671 buf_Release(bufferp);
4674 lock_ReleaseMutex(&scp->mx);
4676 lock_ObtainRead(&scp->bufCreateLock);
4677 code = buf_Get(scp, &thyper, &bufferp);
4678 lock_ReleaseRead(&scp->bufCreateLock);
4680 lock_ObtainMutex(&bufferp->mx);
4681 lock_ObtainMutex(&scp->mx);
4682 if (code) goto done;
4684 bufferOffset = thyper;
4686 /* now get the data in the cache */
4688 code = cm_SyncOp(scp, bufferp, userp, &req, 0,
4689 CM_SCACHESYNC_NEEDCALLBACK
4690 | CM_SCACHESYNC_WRITE
4691 | CM_SCACHESYNC_BUFLOCKED);
4695 /* If we're overwriting the entire buffer, or
4696 * if we're writing at or past EOF, mark the
4697 * buffer as current so we don't call
4698 * cm_GetBuffer. This skips the fetch from the
4699 * server in those cases where we're going to
4700 * obliterate all the data in the buffer anyway,
4701 * or in those cases where there is no useful
4702 * data at the server to start with.
4704 * Use minLength instead of scp->length, since
4705 * the latter has already been updated by this
4708 if (LargeIntegerGreaterThanOrEqualTo(
4709 bufferp->offset, minLength)
4710 || LargeIntegerEqualTo(offset, bufferp->offset)
4711 && (count >= buf_bufferSize
4712 || LargeIntegerGreaterThanOrEqualTo(
4713 LargeIntegerAdd(offset,
4714 ConvertLongToLargeInteger(count)),
4716 if (count < buf_bufferSize
4717 && bufferp->dataVersion == -1)
4718 memset(bufferp->datap, 0,
4720 bufferp->dataVersion = scp->dataVersion;
4723 if (cm_HaveBuffer(scp, bufferp, 1)) break;
4725 /* otherwise, load the buffer and try again */
4726 lock_ReleaseMutex(&bufferp->mx);
4727 code = cm_GetBuffer(scp, bufferp, NULL, userp,
4729 lock_ReleaseMutex(&scp->mx);
4730 lock_ObtainMutex(&bufferp->mx);
4731 lock_ObtainMutex(&scp->mx);
4735 lock_ReleaseMutex(&bufferp->mx);
4736 buf_Release(bufferp);
4740 } /* if (wrong buffer) ... */
4742 /* now we have the right buffer loaded. Copy out the
4743 * data from here to the user's buffer.
4745 bufIndex = offset.LowPart & (buf_bufferSize - 1);
4747 /* and figure out how many bytes we want from this buffer */
4748 nbytes = buf_bufferSize - bufIndex; /* what remains in buffer */
4750 nbytes = count; /* don't go past end of request */
4752 /* now copy the data */
4755 dosmemget((dos_ptr)op, nbytes, bufferp->datap + bufIndex);
4758 memcpy(bufferp->datap + bufIndex, op, nbytes);
4759 buf_SetDirty(bufferp);
4761 /* and record the last writer */
4762 if (bufferp->userp != userp) {
4765 cm_ReleaseUser(bufferp->userp);
4766 bufferp->userp = userp;
4769 /* adjust counters, pointers, etc. */
4773 thyper.LowPart = nbytes;
4774 thyper.HighPart = 0;
4775 offset = LargeIntegerAdd(thyper, offset);
4779 lock_ReleaseMutex(&scp->mx);
4780 lock_ReleaseMutex(&fidp->mx);
4782 lock_ReleaseMutex(&bufferp->mx);
4783 buf_Release(bufferp);
4786 if (code == 0 && filter != 0 && (fidp->flags & SMB_FID_NTOPEN)
4787 && (fidp->NTopen_dscp->flags & CM_SCACHEFLAG_ANYWATCH)) {
4788 smb_NotifyChange(FILE_ACTION_MODIFIED, filter,
4789 fidp->NTopen_dscp, fidp->NTopen_pathp,
4793 if (code == 0 && doWriteBack) {
4794 lock_ObtainMutex(&scp->mx);
4795 cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_ASYNCSTORE);
4796 lock_ReleaseMutex(&scp->mx);
4797 cm_QueueBKGRequest(scp, cm_BkgStore, writeBackOffset.LowPart,
4798 writeBackOffset.HighPart, cm_chunkSize, 0, userp);
4804 long smb_ReceiveCoreWrite(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4807 long count, written = 0;
4812 cm_attr_t truncAttr; /* attribute struct used for truncating file */
4814 int inDataBlockCount;
4816 fd = smb_GetSMBParm(inp, 0);
4817 count = smb_GetSMBParm(inp, 1);
4818 offset.HighPart = 0; /* too bad */
4819 offset.LowPart = smb_GetSMBParm(inp, 2) | (smb_GetSMBParm(inp, 3) << 16);
4821 op = smb_GetSMBData(inp, NULL);
4822 op = smb_ParseDataBlock(op, NULL, &inDataBlockCount);
4824 osi_Log3(afsd_logp, "smb_ReceiveCoreWrite fd %d, off 0x%x, size 0x%x",
4825 fd, offset.LowPart, count);
4827 fd = smb_ChainFID(fd, inp);
4828 fidp = smb_FindFID(vcp, fd, 0);
4830 return CM_ERROR_BADFD;
4833 if (fidp->flags & SMB_FID_IOCTL)
4834 return smb_IoctlWrite(fidp, vcp, inp, outp);
4836 userp = smb_GetUser(vcp, inp);
4838 /* special case: 0 bytes transferred means truncate to this position */
4844 truncAttr.mask = CM_ATTRMASK_LENGTH;
4845 truncAttr.length.LowPart = offset.LowPart;
4846 truncAttr.length.HighPart = 0;
4847 lock_ObtainMutex(&fidp->mx);
4848 code = cm_SetAttr(fidp->scp, &truncAttr, userp, &req);
4849 lock_ReleaseMutex(&fidp->mx);
4850 smb_SetSMBParm(outp, 0, /* count */ 0);
4851 smb_SetSMBDataLength(outp, 0);
4852 fidp->flags |= SMB_FID_LENGTHSETDONE;
4857 * Work around bug in NT client
4859 * When copying a file, the NT client should first copy the data,
4860 * then copy the last write time. But sometimes the NT client does
4861 * these in the wrong order, so the data copies would inadvertently
4862 * cause the last write time to be overwritten. We try to detect this,
4863 * and don't set client mod time if we think that would go against the
4866 if ((fidp->flags & SMB_FID_MTIMESETDONE) != SMB_FID_MTIMESETDONE) {
4867 fidp->scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
4868 fidp->scp->clientModTime = time(NULL);
4872 code = smb_WriteData(fidp, &offset, count, op, userp, &written);
4874 code = smb_WriteData(fidp, &offset, count, op, userp, &written, FALSE);
4876 if (code == 0 && written < count)
4877 code = CM_ERROR_PARTIALWRITE;
4879 /* set the packet data length to 3 bytes for the data block header,
4880 * plus the size of the data.
4882 smb_SetSMBParm(outp, 0, written);
4883 smb_SetSMBDataLength(outp, 0);
4886 smb_ReleaseFID(fidp);
4887 cm_ReleaseUser(userp);
4892 void smb_CompleteWriteRaw(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp,
4893 NCB *ncbp, raw_write_cont_t *rwcp)
4906 fd = smb_GetSMBParm(inp, 0);
4907 fidp = smb_FindFID(vcp, fd, 0);
4909 osi_Log2(afsd_logp, "Completing Raw Write offset %x count %x",
4910 rwcp->offset.LowPart, rwcp->count);
4912 userp = smb_GetUser(vcp, inp);
4916 code = smb_WriteData(fidp, &rwcp->offset, rwcp->count, rawBuf, userp,
4919 rawBuf = (dos_ptr) rwcp->buf;
4920 code = smb_WriteData(fidp, &rwcp->offset, rwcp->count,
4921 (unsigned char *) rawBuf, userp,
4925 if (rwcp->writeMode & 0x1) { /* synchronous */
4928 smb_FormatResponsePacket(vcp, inp, outp);
4929 op = (smb_t *) outp;
4930 op->com = 0x20; /* SMB_COM_WRITE_COMPLETE */
4931 smb_SetSMBParm(outp, 0, written + rwcp->alreadyWritten);
4932 smb_SetSMBDataLength(outp, 0);
4933 smb_SendPacket(vcp, outp);
4934 smb_FreePacket(outp);
4936 else { /* asynchronous */
4937 lock_ObtainMutex(&fidp->mx);
4938 fidp->raw_writers--;
4939 if (fidp->raw_writers == 0)
4940 thrd_SetEvent(fidp->raw_write_event);
4941 lock_ReleaseMutex(&fidp->mx);
4944 /* Give back raw buffer */
4945 lock_ObtainMutex(&smb_RawBufLock);
4947 *((char **)rawBuf) = smb_RawBufs;
4949 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
4951 smb_RawBufs = rawBuf;
4952 lock_ReleaseMutex(&smb_RawBufLock);
4954 smb_ReleaseFID(fidp);
4955 cm_ReleaseUser(userp);
4958 long smb_ReceiveCoreWriteRawDummy(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4963 long smb_ReceiveCoreWriteRaw(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp, raw_write_cont_t *rwcp)
4966 long count, written = 0;
4973 unsigned short writeMode;
4980 fd = smb_GetSMBParm(inp, 0);
4981 totalCount = smb_GetSMBParm(inp, 1);
4982 count = smb_GetSMBParm(inp, 10);
4983 offset.HighPart = 0; /* too bad */
4984 offset.LowPart = smb_GetSMBParm(inp, 3) | (smb_GetSMBParm(inp, 4) << 16);
4985 writeMode = smb_GetSMBParm(inp, 7);
4987 op = (char *) inp->data;
4988 op += smb_GetSMBParm(inp, 11);
4991 "smb_ReceiveCoreWriteRaw fd %d, off 0x%x, size 0x%x, WriteMode 0x%x",
4992 fd, offset.LowPart, count, writeMode);
4994 fd = smb_ChainFID(fd, inp);
4995 fidp = smb_FindFID(vcp, fd, 0);
4997 return CM_ERROR_BADFD;
5000 userp = smb_GetUser(vcp, inp);
5003 * Work around bug in NT client
5005 * When copying a file, the NT client should first copy the data,
5006 * then copy the last write time. But sometimes the NT client does
5007 * these in the wrong order, so the data copies would inadvertently
5008 * cause the last write time to be overwritten. We try to detect this,
5009 * and don't set client mod time if we think that would go against the
5012 if ((fidp->flags & SMB_FID_LOOKSLIKECOPY) != SMB_FID_LOOKSLIKECOPY) {
5013 fidp->scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
5014 fidp->scp->clientModTime = time(NULL);
5018 code = smb_WriteData(fidp, &offset, count, op, userp, &written);
5020 code = smb_WriteData(fidp, &offset, count, op, userp, &written, FALSE);
5022 if (code == 0 && written < count)
5023 code = CM_ERROR_PARTIALWRITE;
5025 /* Get a raw buffer */
5028 lock_ObtainMutex(&smb_RawBufLock);
5030 /* Get a raw buf, from head of list */
5031 rawBuf = smb_RawBufs;
5033 smb_RawBufs = *(char **)smb_RawBufs;
5035 smb_RawBufs = _farpeekl(_dos_ds, smb_RawBufs);
5039 code = CM_ERROR_USESTD;
5041 lock_ReleaseMutex(&smb_RawBufLock);
5044 /* Don't allow a premature Close */
5045 if (code == 0 && (writeMode & 1) == 0) {
5046 lock_ObtainMutex(&fidp->mx);
5047 fidp->raw_writers++;
5048 thrd_ResetEvent(fidp->raw_write_event);
5049 lock_ReleaseMutex(&fidp->mx);
5052 smb_ReleaseFID(fidp);
5053 cm_ReleaseUser(userp);
5056 smb_SetSMBParm(outp, 0, written);
5057 smb_SetSMBDataLength(outp, 0);
5058 ((smb_t *)outp)->com = 0x20; /* SMB_COM_WRITE_COMPLETE */
5065 rwcp->offset.HighPart = 0;
5066 rwcp->offset.LowPart = offset.LowPart + count;
5067 rwcp->count = totalCount - count;
5068 rwcp->writeMode = writeMode;
5069 rwcp->alreadyWritten = written;
5071 /* set the packet data length to 3 bytes for the data block header,
5072 * plus the size of the data.
5074 smb_SetSMBParm(outp, 0, 0xffff);
5075 smb_SetSMBDataLength(outp, 0);
5080 long smb_ReceiveCoreRead(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5083 long count, finalCount;
5090 fd = smb_GetSMBParm(inp, 0);
5091 count = smb_GetSMBParm(inp, 1);
5092 offset.HighPart = 0; /* too bad */
5093 offset.LowPart = smb_GetSMBParm(inp, 2) | (smb_GetSMBParm(inp, 3) << 16);
5095 osi_Log3(afsd_logp, "smb_ReceiveCoreRead fd %d, off 0x%x, size 0x%x",
5096 fd, offset.LowPart, count);
5098 fd = smb_ChainFID(fd, inp);
5099 fidp = smb_FindFID(vcp, fd, 0);
5101 return CM_ERROR_BADFD;
5104 if (fidp->flags & SMB_FID_IOCTL) {
5105 return smb_IoctlRead(fidp, vcp, inp, outp);
5108 userp = smb_GetUser(vcp, inp);
5110 /* remember this for final results */
5111 smb_SetSMBParm(outp, 0, count);
5112 smb_SetSMBParm(outp, 1, 0);
5113 smb_SetSMBParm(outp, 2, 0);
5114 smb_SetSMBParm(outp, 3, 0);
5115 smb_SetSMBParm(outp, 4, 0);
5117 /* set the packet data length to 3 bytes for the data block header,
5118 * plus the size of the data.
5120 smb_SetSMBDataLength(outp, count+3);
5122 /* get op ptr after putting in the parms, since otherwise we don't
5123 * know where the data really is.
5125 op = smb_GetSMBData(outp, NULL);
5127 /* now emit the data block header: 1 byte of type and 2 bytes of length */
5128 *op++ = 1; /* data block marker */
5129 *op++ = (unsigned char) (count & 0xff);
5130 *op++ = (unsigned char) ((count >> 8) & 0xff);
5133 code = smb_ReadData(fidp, &offset, count, op, userp, &finalCount);
5135 code = smb_ReadData(fidp, &offset, count, op, userp, &finalCount, FALSE);
5138 /* fix some things up */
5139 smb_SetSMBParm(outp, 0, finalCount);
5140 smb_SetSMBDataLength(outp, finalCount+3);
5142 smb_ReleaseFID(fidp);
5144 cm_ReleaseUser(userp);
5148 long smb_ReceiveCoreMakeDir(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5155 cm_scache_t *dscp; /* dir we're dealing with */
5156 cm_scache_t *scp; /* file we're creating */
5158 int initialModeBits;
5168 /* compute initial mode bits based on read-only flag in attributes */
5169 initialModeBits = 0777;
5171 tp = smb_GetSMBData(inp, NULL);
5172 pathp = smb_ParseASCIIBlock(tp, &tp);
5174 if (strcmp(pathp, "\\") == 0)
5175 return CM_ERROR_EXISTS;
5177 spacep = inp->spacep;
5178 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
5180 userp = smb_GetUser(vcp, inp);
5182 caseFold = CM_FLAG_CASEFOLD;
5184 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
5186 code = cm_NameI(cm_rootSCachep, spacep->data,
5187 caseFold | CM_FLAG_FOLLOW | CM_FLAG_CHECKPATH,
5188 userp, tidPathp, &req, &dscp);
5191 cm_ReleaseUser(userp);
5195 /* otherwise, scp points to the parent directory. Do a lookup, and
5196 * fail if we find it. Otherwise, we do the create.
5202 code = cm_Lookup(dscp, lastNamep, caseFold, userp, &req, &scp);
5203 if (scp) cm_ReleaseSCache(scp);
5204 if (code != CM_ERROR_NOSUCHFILE) {
5205 if (code == 0) code = CM_ERROR_EXISTS;
5206 cm_ReleaseSCache(dscp);
5207 cm_ReleaseUser(userp);
5211 setAttr.mask = CM_ATTRMASK_CLIENTMODTIME;
5212 setAttr.clientModTime = time(NULL);
5213 code = cm_MakeDir(dscp, lastNamep, 0, &setAttr, userp, &req);
5214 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
5215 smb_NotifyChange(FILE_ACTION_ADDED,
5216 FILE_NOTIFY_CHANGE_DIR_NAME,
5217 dscp, lastNamep, NULL, TRUE);
5219 /* we don't need this any longer */
5220 cm_ReleaseSCache(dscp);
5223 /* something went wrong creating or truncating the file */
5224 cm_ReleaseUser(userp);
5228 /* otherwise we succeeded */
5229 smb_SetSMBDataLength(outp, 0);
5230 cm_ReleaseUser(userp);
5235 BOOL smb_IsLegalFilename(char *filename)
5238 * Find the longest substring of filename that does not contain
5239 * any of the chars in illegalChars. If that substring is less
5240 * than the length of the whole string, then one or more of the
5241 * illegal chars is in filename.
5243 if (strcspn(filename, illegalChars) < strlen(filename))
5249 long smb_ReceiveCoreCreate(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5257 cm_scache_t *dscp; /* dir we're dealing with */
5258 cm_scache_t *scp; /* file we're creating */
5260 int initialModeBits;
5272 excl = (inp->inCom == 0x03)? 0 : 1;
5274 attributes = smb_GetSMBParm(inp, 0);
5275 dosTime = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
5277 /* compute initial mode bits based on read-only flag in attributes */
5278 initialModeBits = 0666;
5279 if (attributes & 1) initialModeBits &= ~0222;
5281 tp = smb_GetSMBData(inp, NULL);
5282 pathp = smb_ParseASCIIBlock(tp, &tp);
5284 spacep = inp->spacep;
5285 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
5287 userp = smb_GetUser(vcp, inp);
5289 caseFold = CM_FLAG_CASEFOLD;
5291 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
5292 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold | CM_FLAG_FOLLOW,
5293 userp, tidPathp, &req, &dscp);
5296 cm_ReleaseUser(userp);
5300 /* otherwise, scp points to the parent directory. Do a lookup, and
5301 * truncate the file if we find it, otherwise we create the file.
5303 if (!lastNamep) lastNamep = pathp;
5306 if (!smb_IsLegalFilename(lastNamep))
5307 return CM_ERROR_BADNTFILENAME;
5309 osi_Log1(afsd_logp, "SMB receive create [%s]", osi_LogSaveString( afsd_logp, pathp ));
5310 #ifdef DEBUG_VERBOSE
5313 hexp = osi_HexifyString( lastNamep );
5314 DEBUG_EVENT2("AFS", "CoreCreate H[%s] A[%s]", hexp, lastNamep );
5319 code = cm_Lookup(dscp, lastNamep, caseFold, userp, &req, &scp);
5320 if (code && code != CM_ERROR_NOSUCHFILE) {
5321 cm_ReleaseSCache(dscp);
5322 cm_ReleaseUser(userp);
5326 /* if we get here, if code is 0, the file exists and is represented by
5327 * scp. Otherwise, we have to create it.
5331 /* oops, file shouldn't be there */
5332 cm_ReleaseSCache(dscp);
5333 cm_ReleaseSCache(scp);
5334 cm_ReleaseUser(userp);
5335 return CM_ERROR_EXISTS;
5338 setAttr.mask = CM_ATTRMASK_LENGTH;
5339 setAttr.length.LowPart = 0;
5340 setAttr.length.HighPart = 0;
5341 code = cm_SetAttr(scp, &setAttr, userp, &req);
5344 setAttr.mask = CM_ATTRMASK_CLIENTMODTIME;
5345 smb_UnixTimeFromDosUTime(&setAttr.clientModTime, dosTime);
5346 code = cm_Create(dscp, lastNamep, 0, &setAttr, &scp, userp,
5348 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
5349 smb_NotifyChange(FILE_ACTION_ADDED,
5350 FILE_NOTIFY_CHANGE_FILE_NAME,
5351 dscp, lastNamep, NULL, TRUE);
5352 if (!excl && code == CM_ERROR_EXISTS) {
5353 /* not an exclusive create, and someone else tried
5354 * creating it already, then we open it anyway. We
5355 * don't bother retrying after this, since if this next
5356 * fails, that means that the file was deleted after
5357 * we started this call.
5359 code = cm_Lookup(dscp, lastNamep, caseFold, userp,
5362 setAttr.mask = CM_ATTRMASK_LENGTH;
5363 setAttr.length.LowPart = 0;
5364 setAttr.length.HighPart = 0;
5365 code = cm_SetAttr(scp, &setAttr, userp, &req);
5370 /* we don't need this any longer */
5371 cm_ReleaseSCache(dscp);
5374 /* something went wrong creating or truncating the file */
5375 if (scp) cm_ReleaseSCache(scp);
5376 cm_ReleaseUser(userp);
5380 /* make sure we only open files */
5381 if (scp->fileType != CM_SCACHETYPE_FILE) {
5382 cm_ReleaseSCache(scp);
5383 cm_ReleaseUser(userp);
5384 return CM_ERROR_ISDIR;
5387 /* now all we have to do is open the file itself */
5388 fidp = smb_FindFID(vcp, 0, SMB_FLAG_CREATE);
5391 /* save a pointer to the vnode */
5394 /* always create it open for read/write */
5395 fidp->flags |= (SMB_FID_OPENREAD | SMB_FID_OPENWRITE);
5397 smb_ReleaseFID(fidp);
5399 smb_SetSMBParm(outp, 0, fidp->fid);
5400 smb_SetSMBDataLength(outp, 0);
5402 cm_Open(scp, 0, userp);
5404 cm_ReleaseUser(userp);
5405 /* leave scp held since we put it in fidp->scp */
5409 long smb_ReceiveCoreSeek(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5422 fd = smb_GetSMBParm(inp, 0);
5423 whence = smb_GetSMBParm(inp, 1);
5424 offset = smb_GetSMBParm(inp, 2) | (smb_GetSMBParm(inp, 3) << 16);
5426 /* try to find the file descriptor */
5427 fd = smb_ChainFID(fd, inp);
5428 fidp = smb_FindFID(vcp, fd, 0);
5429 if (!fidp || (fidp->flags & SMB_FID_IOCTL)) {
5430 return CM_ERROR_BADFD;
5433 userp = smb_GetUser(vcp, inp);
5435 lock_ObtainMutex(&fidp->mx);
5437 lock_ObtainMutex(&scp->mx);
5438 code = cm_SyncOp(scp, NULL, userp, &req, 0,
5439 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
5442 /* offset from current offset */
5443 offset += fidp->offset;
5445 else if (whence == 2) {
5446 /* offset from current EOF */
5447 offset += scp->length.LowPart;
5449 fidp->offset = offset;
5450 smb_SetSMBParm(outp, 0, offset & 0xffff);
5451 smb_SetSMBParm(outp, 1, (offset>>16) & 0xffff);
5452 smb_SetSMBDataLength(outp, 0);
5454 lock_ReleaseMutex(&scp->mx);
5455 lock_ReleaseMutex(&fidp->mx);
5456 smb_ReleaseFID(fidp);
5457 cm_ReleaseUser(userp);
5461 /* dispatch all of the requests received in a packet. Due to chaining, this may
5462 * be more than one request.
5464 void smb_DispatchPacket(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp,
5465 NCB *ncbp, raw_write_cont_t *rwcp)
5467 static showErrors = 0;
5471 unsigned char *outWctp;
5472 int nparms; /* # of bytes of parameters */
5474 int nbytes; /* bytes of data, excluding count */
5477 unsigned short errCode;
5478 unsigned long NTStatus;
5480 unsigned char errClass;
5481 unsigned int oldGen;
5482 DWORD oldTime, newTime;
5484 /* get easy pointer to the data */
5485 smbp = (smb_t *) inp->data;
5487 if (!(outp->flags & SMB_PACKETFLAG_SUSPENDED)) {
5488 /* setup the basic parms for the initial request in the packet */
5489 inp->inCom = smbp->com;
5490 inp->wctp = &smbp->wct;
5492 inp->ncb_length = ncbp->ncb_length;
5497 if (ncbp->ncb_length < offsetof(struct smb, vdata)) {
5498 /* log it and discard it */
5503 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
5504 sprintf(s, "SMB message too short, len %d", ncbp->ncb_length);
5506 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1007, NULL,
5507 1, ncbp->ncb_length, ptbuf, inp);
5508 DeregisterEventSource(h);
5510 osi_Log1(smb_logp, "SMB message too short, len %d",
5517 /* We are an ongoing op */
5518 thrd_Increment(&ongoingOps);
5520 /* set up response packet for receiving output */
5521 if (!(outp->flags & SMB_PACKETFLAG_SUSPENDED))
5522 smb_FormatResponsePacket(vcp, inp, outp);
5523 outWctp = outp->wctp;
5525 /* Remember session generation number and time */
5526 oldGen = sessionGen;
5527 oldTime = GetCurrentTime();
5529 while(inp->inCom != 0xff) {
5530 dp = &smb_dispatchTable[inp->inCom];
5532 if (outp->flags & SMB_PACKETFLAG_SUSPENDED) {
5533 outp->flags &= ~SMB_PACKETFLAG_SUSPENDED;
5534 code = outp->resumeCode;
5538 /* process each request in the packet; inCom, wctp and inCount
5539 * are already set up.
5541 osi_Log2(afsd_logp, "SMB received op 0x%x lsn %d", inp->inCom,
5544 /* now do the dispatch */
5545 /* start by formatting the response record a little, as a default */
5546 if (dp->flags & SMB_DISPATCHFLAG_CHAINED) {
5548 outWctp[1] = 0xff; /* no operation */
5549 outWctp[2] = 0; /* padding */
5554 /* not a chained request, this is a more reasonable default */
5555 outWctp[0] = 0; /* wct of zero */
5556 outWctp[1] = 0; /* and bcc (word) of zero */
5560 /* once set, stays set. Doesn't matter, since we never chain
5561 * "no response" calls.
5563 if (dp->flags & SMB_DISPATCHFLAG_NORESPONSE)
5567 /* we have a recognized operation */
5569 if (inp->inCom == 0x1d)
5571 code = smb_ReceiveCoreWriteRaw (vcp, inp, outp,
5574 osi_LogEvent("AFS Dispatch %s",(myCrt_Dispatch(inp->inCom)),"vcp[%x] lana[%d] lsn[%d]",(int)vcp,vcp->lana,vcp->lsn);
5575 osi_Log4(afsd_logp,"Dispatch %s vcp[%x] lana[%d] lsn[%d]",(myCrt_Dispatch(inp->inCom)),vcp,vcp->lana,vcp->lsn);
5576 code = (*(dp->procp)) (vcp, inp, outp);
5577 osi_LogEvent("AFS Dispatch return",NULL,"Code[%d]",(code==0)?0:code-CM_ERROR_BASE);
5578 osi_Log1(afsd_logp,"Dispatch return code[%d]",(code==0)?0:code-CM_ERROR_BASE);
5581 if (oldGen != sessionGen) {
5586 newTime = GetCurrentTime();
5587 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
5588 sprintf(s, "Pkt straddled session startup, took %d ms, ncb length %d",
5589 newTime - oldTime, ncbp->ncb_length);
5591 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0,
5592 1005, NULL, 1, ncbp->ncb_length, ptbuf, smbp);
5593 DeregisterEventSource(h);
5595 osi_Log1(afsd_logp, "Pkt straddled session startup, "
5596 "ncb length %d", ncbp->ncb_length);
5601 /* bad opcode, fail the request, after displaying it */
5604 #endif /* NOTSERVICE */
5608 sprintf(tbuffer, "Received bad SMB req 0x%x", inp->inCom);
5609 code = (*smb_MBfunc)(NULL, tbuffer, "Cancel: don't show again",
5611 if (code == IDCANCEL) showErrors = 0;
5614 code = CM_ERROR_BADOP;
5617 /* catastrophic failure: log as much as possible */
5618 if (code == CM_ERROR_BADSMB) {
5625 "Invalid SMB, ncb_length %d",
5628 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
5629 sprintf(s, "Invalid SMB message, length %d",
5632 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1002, NULL,
5633 1, ncbp->ncb_length, ptbuf, smbp);
5634 DeregisterEventSource(h);
5637 #endif /* NOTSERVICE */
5639 osi_Log1(afsd_logp, "Invalid SMB message, length %d",
5643 code = CM_ERROR_INVAL;
5646 if (outp->flags & SMB_PACKETFLAG_NOSEND) {
5647 thrd_Decrement(&ongoingOps);
5652 /* now, if we failed, turn the current response into an empty
5653 * one, and fill in the response packet's error code.
5656 if (vcp->flags & SMB_VCFLAG_STATUS32) {
5657 smb_MapNTError(code, &NTStatus);
5658 outWctp = outp->wctp;
5659 smbp = (smb_t *) &outp->data;
5660 if (code != CM_ERROR_PARTIALWRITE
5661 && code != CM_ERROR_BUFFERTOOSMALL) {
5662 /* nuke wct and bcc. For a partial
5663 * write, assume they're OK.
5669 smbp->rcls = (unsigned char) (NTStatus & 0xff);
5670 smbp->reh = (unsigned char) ((NTStatus >> 8) & 0xff);
5671 smbp->errLow = (unsigned char) ((NTStatus >> 16) & 0xff);
5672 smbp->errHigh = (unsigned char) ((NTStatus >> 24) & 0xff);
5673 smbp->flg2 |= 0x4000;
5677 smb_MapCoreError(code, vcp, &errCode, &errClass);
5678 outWctp = outp->wctp;
5679 smbp = (smb_t *) &outp->data;
5680 if (code != CM_ERROR_PARTIALWRITE) {
5681 /* nuke wct and bcc. For a partial
5682 * write, assume they're OK.
5688 smbp->errLow = (unsigned char) (errCode & 0xff);
5689 smbp->errHigh = (unsigned char) ((errCode >> 8) & 0xff);
5690 smbp->rcls = errClass;
5693 } /* error occurred */
5695 /* if we're here, we've finished one request. Look to see if
5696 * this is a chained opcode. If it is, setup things to process
5697 * the chained request, and setup the output buffer to hold the
5698 * chained response. Start by finding the next input record.
5700 if (!(dp->flags & SMB_DISPATCHFLAG_CHAINED))
5701 break; /* not a chained req */
5702 tp = inp->wctp; /* points to start of last request */
5703 /* in a chained request, the first two
5704 * parm fields are required, and are
5705 * AndXCommand/AndXReserved and
5707 if (tp[0] < 2) break;
5708 if (tp[1] == 0xff) break; /* no more chained opcodes */
5710 inp->wctp = inp->data + tp[3] + (tp[4] << 8);
5713 /* and now append the next output request to the end of this
5714 * last request. Begin by finding out where the last response
5715 * ends, since that's where we'll put our new response.
5717 outWctp = outp->wctp; /* ptr to out parameters */
5718 osi_assert (outWctp[0] >= 2); /* need this for all chained requests */
5719 nparms = outWctp[0] << 1;
5720 tp = outWctp + nparms + 1; /* now points to bcc field */
5721 nbytes = tp[0] + (tp[1] << 8); /* # of data bytes */
5722 tp += 2 /* for the count itself */ + nbytes;
5723 /* tp now points to the new output record; go back and patch the
5724 * second parameter (off2) to point to the new record.
5726 temp = (unsigned int)tp - ((unsigned int) outp->data);
5727 outWctp[3] = (unsigned char) (temp & 0xff);
5728 outWctp[4] = (unsigned char) ((temp >> 8) & 0xff);
5729 outWctp[2] = 0; /* padding */
5730 outWctp[1] = inp->inCom; /* next opcode */
5732 /* finally, setup for the next iteration */
5735 } /* while loop over all requests in the packet */
5737 /* done logging out, turn off logging-out flag */
5738 if (!(inp->flags & SMB_PACKETFLAG_PROFILE_UPDATE_OK)) {
5739 vcp->justLoggedOut = NULL;
5742 free(loggedOutName);
5743 loggedOutName = NULL;
5744 smb_ReleaseUID(loggedOutUserp);
5745 loggedOutUserp = NULL;
5749 /* now send the output packet, and return */
5751 smb_SendPacket(vcp, outp);
5752 thrd_Decrement(&ongoingOps);
5754 if (!(vcp->flags & SMB_VCFLAG_ALREADYDEAD)) {
5756 last_msg_time = GetCurrentTime();
5758 else if (active_vcp == vcp)
5765 /* Wait for Netbios() calls to return, and make the results available to server
5766 * threads. Note that server threads can't wait on the NCBevents array
5767 * themselves, because NCB events are manual-reset, and the servers would race
5768 * each other to reset them.
5770 void smb_ClientWaiter(void *parmp)
5776 code = thrd_WaitForMultipleObjects_Event(numNCBs, NCBevents,
5778 if (code == WAIT_OBJECT_0)
5781 /* error checking */
5782 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numNCBs))
5784 int abandonIdx = code - WAIT_ABANDONED_0;
5785 afsi_log("Error: smb_ClientWaiter event %d abandoned, errno %d\n", abandonIdx, GetLastError());
5788 if (code == WAIT_IO_COMPLETION)
5790 afsi_log("Error: smb_ClientWaiter WAIT_IO_COMPLETION\n");
5794 if (code == WAIT_TIMEOUT)
5796 afsi_log("Error: smb_ClientWaiter WAIT_TIMEOUT, errno %d\n", GetLastError());
5799 if (code == WAIT_FAILED)
5801 afsi_log("Error: smb_ClientWaiter WAIT_FAILED, errno %d\n", GetLastError());
5804 idx = code - WAIT_OBJECT_0;
5806 /* check idx range! */
5807 if (idx < 0 || idx > (sizeof(NCBevents) / sizeof(NCBevents[0])))
5809 /* this is fatal - log as much as possible */
5810 afsi_log("Fatal: NCBevents idx [ %d ] out of range.\n", idx);
5814 thrd_ResetEvent(NCBevents[idx]);
5815 thrd_SetEvent(NCBreturns[0][idx]);
5821 * Try to have one NCBRECV request waiting for every live session. Not more
5822 * than one, because if there is more than one, it's hard to handle Write Raw.
5824 void smb_ServerWaiter(void *parmp)
5827 int idx_session, idx_NCB;
5835 code = thrd_WaitForMultipleObjects_Event(numSessions, SessionEvents,
5837 if (code == WAIT_OBJECT_0)
5840 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numSessions))
5842 int abandonIdx = code - WAIT_ABANDONED_0;
5843 afsi_log("Error: smb_ServerWaiter (SessionEvents) event %d abandoned, errno %d\n", abandonIdx, GetLastError());
5846 if (code == WAIT_IO_COMPLETION)
5848 afsi_log("Error: smb_ServerWaiter (SessionEvents) WAIT_IO_COMPLETION\n");
5852 if (code == WAIT_TIMEOUT)
5854 afsi_log("Error: smb_ServerWaiter (SessionEvents) WAIT_TIMEOUT, errno %d\n", GetLastError());
5857 if (code == WAIT_FAILED)
5859 afsi_log("Error: smb_ServerWaiter (SessionEvents) WAIT_FAILED, errno %d\n", GetLastError());
5862 idx_session = code - WAIT_OBJECT_0;
5864 /* check idx range! */
5865 if (idx_session < 0 || idx_session > (sizeof(SessionEvents) / sizeof(SessionEvents[0])))
5867 /* this is fatal - log as much as possible */
5868 afsi_log("Fatal: session idx [ %d ] out of range.\n", idx_session);
5874 code = thrd_WaitForMultipleObjects_Event(numNCBs, NCBavails,
5876 if (code == WAIT_OBJECT_0)
5879 /* error checking */
5880 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numNCBs))
5882 int abandonIdx = code - WAIT_ABANDONED_0;
5883 afsi_log("Error: smb_ClientWaiter (NCBavails) event %d abandoned, errno %d\n", abandonIdx, GetLastError());
5886 if (code == WAIT_IO_COMPLETION)
5888 afsi_log("Error: smb_ClientWaiter (NCBavails) WAIT_IO_COMPLETION\n");
5892 if (code == WAIT_TIMEOUT)
5894 afsi_log("Error: smb_ClientWaiter (NCBavails) WAIT_TIMEOUT, errno %d\n", GetLastError());
5897 if (code == WAIT_FAILED)
5899 afsi_log("Error: smb_ClientWaiter (NCBavails) WAIT_FAILED, errno %d\n", GetLastError());
5902 idx_NCB = code - WAIT_OBJECT_0;
5904 /* check idx range! */
5905 if (idx_NCB < 0 || idx_NCB > (sizeof(NCBsessions) / sizeof(NCBsessions[0])))
5907 /* this is fatal - log as much as possible */
5908 afsi_log("Fatal: idx_NCB [ %d ] out of range.\n", idx_NCB);
5912 /* Link them together */
5913 NCBsessions[idx_NCB] = idx_session;
5916 ncbp = NCBs[idx_NCB];
5918 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
5920 ncbp->ncb_lsn = (unsigned char) LSNs[idx_session];
5921 ncbp->ncb_command = NCBRECV | ASYNCH;
5922 ncbp->ncb_lana_num = lanas[idx_session];
5924 ncbp->ncb_buffer = (unsigned char *) bufs[idx_NCB];
5925 ncbp->ncb_event = NCBevents[idx_NCB];
5926 ncbp->ncb_length = SMB_PACKETSIZE;
5929 ncbp->ncb_buffer = bufs[idx_NCB]->dos_pkt;
5930 ((smb_ncb_t*)ncbp)->orig_pkt = bufs[idx_NCB];
5931 ncbp->ncb_event = NCBreturns[0][idx_NCB];
5932 ncbp->ncb_length = SMB_PACKETSIZE;
5933 Netbios(ncbp, dos_ncb);
5939 * The top level loop for handling SMB request messages. Each server thread
5940 * has its own NCB and buffer for sending replies (outncbp, outbufp), but the
5941 * NCB and buffer for the incoming request are loaned to us.
5943 * Write Raw trickery starts here. When we get a Write Raw, we are supposed
5944 * to immediately send a request for the rest of the data. This must come
5945 * before any other traffic for that session, so we delay setting the session
5946 * event until that data has come in.
5948 void smb_Server(VOID *parmp)
5950 int myIdx = (int) parmp;
5954 smb_packet_t *outbufp;
5956 int idx_NCB, idx_session;
5965 outbufp = GetPacket();
5966 outbufp->ncbp = outncbp;
5970 /* check for demo expiration */
5972 unsigned long tod = time((void *) 0);
5973 if (tod > EXPIREDATE) {
5974 (*smb_MBfunc)(NULL, "AFS demo expiration",
5976 MB_OK|MB_ICONSTOP|MB_SETFOREGROUND);
5980 #endif /* !NOEXPIRE */
5982 code = thrd_WaitForMultipleObjects_Event(numNCBs, NCBreturns[myIdx],
5984 if (code == WAIT_OBJECT_0) {
5988 /* error checking */
5989 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numNCBs))
5991 int abandonIdx = code - WAIT_ABANDONED_0;
5992 afsi_log("Error: smb_Server ( NCBreturns[%d] ) event %d abandoned, errno %d\n", myIdx, abandonIdx, GetLastError());
5995 if (code == WAIT_IO_COMPLETION)
5997 afsi_log("Error: smb_Server ( NCBreturns[%d] ) WAIT_IO_COMPLETION\n", myIdx);
6001 if (code == WAIT_TIMEOUT)
6003 afsi_log("Error: smb_Server ( NCBreturns[%d] ) WAIT_TIMEOUT, errno %d\n", myIdx, GetLastError());
6006 if (code == WAIT_FAILED)
6008 afsi_log("Error: smb_Server ( NCBreturns[%d] ) WAIT_FAILED, errno %d\n", myIdx, GetLastError());
6011 idx_NCB = code - WAIT_OBJECT_0;
6013 /* check idx range! */
6014 if (idx_NCB < 0 || idx_NCB > (sizeof(NCBs) / sizeof(NCBs[0])))
6016 /* this is fatal - log as much as possible */
6017 afsi_log("Fatal: idx_NCB [ %d ] out of range.\n", idx_NCB);
6021 ncbp = NCBs[idx_NCB];
6023 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6025 idx_session = NCBsessions[idx_NCB];
6026 rc = ncbp->ncb_retcode;
6028 if (rc != NRC_PENDING && rc != NRC_GOODRET)
6029 osi_Log1(afsd_logp, "NCBRECV failure code %d", rc);
6032 case NRC_GOODRET: break;
6035 /* Can this happen? Or is it just my
6042 /* Client closed session */
6043 if (reportSessionStartups)
6045 afsi_log("session [ %d ] closed", idx_session);
6047 dead_sessions[idx_session] = TRUE;
6048 vcp = smb_FindVC(ncbp->ncb_lsn, 0, lanas[idx_session]);
6049 /* Should also release vcp. Also, would do
6050 * sanity check that all TID's are gone.
6052 * TODO: check if we could use LSNs[idx_session] instead,
6053 * also cleanup after dead vcp
6058 "dead_vcp already set, %x",
6060 if (!dead_vcp && !(vcp->flags & SMB_VCFLAG_ALREADYDEAD)) {
6062 "setting dead_vcp %x, user struct %x",
6065 vcp->flags |= SMB_VCFLAG_ALREADYDEAD;
6067 if (vcp->justLoggedOut) {
6069 loggedOutTime = vcp->logoffTime;
6071 strdup(vcp->justLoggedOut->unp->name);
6072 loggedOutUserp = vcp->justLoggedOut;
6073 lock_ObtainWrite(&smb_rctLock);
6074 loggedOutUserp->refCount++;
6075 lock_ReleaseWrite(&smb_rctLock);
6081 /* Treat as transient error */
6088 osi_Log1(smb_logp, "dispatch smb recv failed, message incomplete, ncb_length %d",
6090 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
6091 sprintf(s, "SMB message incomplete, length %d",
6094 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0,
6096 ncbp->ncb_length, ptbuf,
6098 DeregisterEventSource(h);
6101 "dispatch smb recv failed, message incomplete, ncb_length %d",
6104 "SMB message incomplete, "
6105 "length %d", ncbp->ncb_length);
6109 * We used to discard the packet.
6110 * Instead, try handling it normally.
6118 /* A weird error code. Log it, sleep, and
6120 if (vcp->errorCount++ > 3) {
6121 afsi_log("session [ %d ] closed, vcp->errorCount = %d", idx_session, vcp->errorCount);
6122 dead_sessions[idx_session] = TRUE;
6126 thrd_SetEvent(SessionEvents[idx_session]);
6131 /* Success, so now dispatch on all the data in the packet */
6133 smb_concurrentCalls++;
6134 if (smb_concurrentCalls > smb_maxObsConcurrentCalls)
6135 smb_maxObsConcurrentCalls = smb_concurrentCalls;
6137 vcp = smb_FindVC(ncbp->ncb_lsn, 0, ncbp->ncb_lana_num);
6139 * If at this point vcp is NULL (implies that packet was invalid)
6140 * then we are in big trouble. This means either :
6141 * a) we have the wrong NCB.
6142 * b) Netbios screwed up the call.
6143 * Obviously this implies that
6144 * ( LSNs[idx_session] != ncbp->ncb_lsn ||
6145 * lanas[idx_session] != ncbp->ncb_lana_num )
6146 * Either way, we can't do anything with this packet.
6147 * Log, sleep and resume.
6156 "LSNs[idx_session]=[%d],"
6157 "lanas[idx_session]=[%d],"
6158 "ncbp->ncb_lsn=[%d],"
6159 "ncbp->ncb_lana_num=[%d]",
6163 ncbp->ncb_lana_num);
6167 h = RegisterEventSource(NULL,AFS_DAEMON_EVENT_NAME);
6169 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1001, NULL,1,sizeof(*ncbp),ptbuf,(void*)ncbp);
6170 DeregisterEventSource(h);
6173 /* Also log in the trace log. */
6174 osi_Log4(afsd_logp, "Server: BAD VCP!"
6175 "LSNs[idx_session]=[%d],"
6176 "lanas[idx_session]=[%d],"
6177 "ncbp->ncb_lsn=[%d],"
6178 "ncbp->ncb_lana_num=[%d]",
6182 ncbp->ncb_lana_num);
6184 /* thrd_Sleep(1000); Don't bother sleeping */
6185 thrd_SetEvent(SessionEvents[idx_session]);
6186 smb_concurrentCalls--;
6191 vcp->errorCount = 0;
6192 bufp = (struct smb_packet *) ncbp->ncb_buffer;
6194 bufp = ((smb_ncb_t *) ncbp)->orig_pkt;
6195 /* copy whole packet to virtual memory */
6196 /*fprintf(stderr, "smb_Server: copying dos packet at 0x%x, "
6198 bufp->dos_pkt / 16, bufp);*/
6200 dosmemget(bufp->dos_pkt, ncbp->ncb_length, bufp->data);
6202 smbp = (smb_t *)bufp->data;
6205 #if !defined(DJGPP) && !defined(AFS_WIN32_ENV)
6209 if (smbp->com == 0x1d) {
6210 /* Special handling for Write Raw */
6211 raw_write_cont_t rwc;
6212 EVENT_HANDLE rwevent;
6213 char eventName[MAX_PATH];
6215 smb_DispatchPacket(vcp, bufp, outbufp, ncbp, &rwc);
6216 if (rwc.code == 0) {
6217 rwevent = thrd_CreateEvent(NULL, FALSE, FALSE, TEXT("smb_Server() rwevent"));
6218 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6219 afsi_log("Event Object Already Exists: %s", eventName);
6220 ncbp->ncb_command = NCBRECV | ASYNCH;
6221 ncbp->ncb_lsn = (unsigned char) vcp->lsn;
6222 ncbp->ncb_lana_num = vcp->lana;
6223 ncbp->ncb_buffer = rwc.buf;
6224 ncbp->ncb_length = 65535;
6225 ncbp->ncb_event = rwevent;
6229 Netbios(ncbp, dos_ncb);
6231 rcode = thrd_WaitForSingleObject_Event(rwevent, RAWTIMEOUT);
6232 thrd_CloseHandle(rwevent);
6234 thrd_SetEvent(SessionEvents[idx_session]);
6236 smb_CompleteWriteRaw(vcp, bufp, outbufp, ncbp, &rwc);
6237 } else if (smbp->com == 0xa0) {
6239 * Serialize the handling for NT Transact
6242 smb_DispatchPacket(vcp, bufp, outbufp, ncbp, NULL);
6243 thrd_SetEvent(SessionEvents[idx_session]);
6245 thrd_SetEvent(SessionEvents[idx_session]);
6246 /* TODO: what else needs to be serialized? */
6247 smb_DispatchPacket(vcp, bufp, outbufp, ncbp, NULL);
6249 #if !defined(DJGPP) && !defined(AFS_WIN95_ENV)
6251 __except( smb_ServerExceptionFilter() ) {
6255 smb_concurrentCalls--;
6258 thrd_SetEvent(NCBavails[idx_NCB]);
6263 * Exception filter for the server threads. If an exception occurs in the
6264 * dispatch routines, which is where exceptions are most common, then do a
6265 * force trace and give control to upstream exception handlers. Useful for
6268 #if !defined(DJGPP) && !defined(AFS_WIN95_ENV)
6269 DWORD smb_ServerExceptionFilter(void) {
6270 /* While this is not the best time to do a trace, if it succeeds, then
6271 * we have a trace (assuming tracing was enabled). Otherwise, this should
6272 * throw a second exception.
6277 ptbuf[0] = "Unhandled exception forcing trace";
6279 h = RegisterEventSource(NULL,AFS_DAEMON_EVENT_NAME);
6281 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1001, NULL,1,0,ptbuf,NULL);
6282 DeregisterEventSource(h);
6285 afsd_ForceTrace(TRUE);
6286 return EXCEPTION_CONTINUE_SEARCH;
6291 * Create a new NCB and associated events, packet buffer, and "space" buffer.
6292 * If the number of server threads is M, and the number of live sessions is
6293 * N, then the number of NCB's in use at any time either waiting for, or
6294 * holding, received messages is M + N, so that is how many NCB's get created.
6296 void InitNCBslot(int idx)
6298 struct smb_packet *bufp;
6299 EVENT_HANDLE retHandle;
6301 char eventName[MAX_PATH];
6303 osi_assert( idx < (sizeof(NCBs) / sizeof(NCBs[0])) );
6305 NCBs[idx] = GetNCB();
6306 sprintf(eventName,"NCBavails[%d]", idx);
6307 NCBavails[idx] = thrd_CreateEvent(NULL, FALSE, TRUE, eventName);
6308 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6309 afsi_log("Event Object Already Exists: %s", eventName);
6311 sprintf(eventName,"NCBevents[%d]", idx);
6312 NCBevents[idx] = thrd_CreateEvent(NULL, TRUE, FALSE, eventName);
6313 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6314 afsi_log("Event Object Already Exists: %s", eventName);
6316 sprintf(eventName,"NCBReturns[0<=i<smb_NumServerThreads][%d]", idx);
6317 retHandle = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6318 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6319 afsi_log("Event Object Already Exists: %s", eventName);
6320 for (i=0; i<smb_NumServerThreads; i++)
6321 NCBreturns[i][idx] = retHandle;
6323 bufp->spacep = cm_GetSpace();
6327 /* listen for new connections */
6328 void smb_Listener(void *parmp)
6336 char rname[NCBNAMSZ+1];
6337 char cname[MAX_COMPUTERNAME_LENGTH+1];
6338 int cnamelen = MAX_COMPUTERNAME_LENGTH+1;
6343 int lana = (int) parmp;
6347 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6350 /* retrieve computer name */
6351 GetComputerName(cname, &cnamelen);
6355 memset(ncbp, 0, sizeof(NCB));
6359 /* check for demo expiration */
6361 unsigned long tod = time((void *) 0);
6362 if (tod > EXPIREDATE) {
6363 (*smb_MBfunc)(NULL, "AFS demo expiration",
6365 MB_OK|MB_ICONSTOP|MB_SETFOREGROUND);
6373 #endif /* !NOEXPIRE */
6375 ncbp->ncb_command = NCBLISTEN;
6376 ncbp->ncb_rto = 0; /* No receive timeout */
6377 ncbp->ncb_sto = 0; /* No send timeout */
6379 /* pad out with spaces instead of null termination */
6380 len = strlen(smb_localNamep);
6381 strncpy(ncbp->ncb_name, smb_localNamep, NCBNAMSZ);
6382 for(i=len; i<NCBNAMSZ; i++) ncbp->ncb_name[i] = ' ';
6384 strcpy(ncbp->ncb_callname, "*");
6385 for(i=1; i<NCBNAMSZ; i++) ncbp->ncb_callname[i] = ' ';
6387 ncbp->ncb_lana_num = lana;
6390 code = Netbios(ncbp);
6392 code = Netbios(ncbp, dos_ncb);
6397 /* terminate if shutdown flag is set */
6398 if (smbShutdownFlag == 1) {
6409 fprintf(stderr, "NCBLISTEN lana=%d failed with code %d\n",
6410 ncbp->ncb_lana_num, code);
6411 osi_Log2(0, "NCBLISTEN lana=%d failed with code %d",
6412 ncbp->ncb_lana_num, code);
6413 fprintf(stderr, "\nClient exiting due to network failure "
6414 "(possibly due to power-saving mode)\n");
6415 fprintf(stderr, "Please restart client.\n");
6416 afs_exit(AFS_EXITCODE_NETWORK_FAILURE);
6420 /* check for remote conns */
6421 /* first get remote name and insert null terminator */
6422 memcpy(rname, ncbp->ncb_callname, NCBNAMSZ);
6423 for (i=NCBNAMSZ; i>0; i--) {
6424 if (rname[i-1] != ' ' && rname[i-1] != 0) {
6430 /* compare with local name */
6432 if (strncmp(rname, cname, NCBNAMSZ) != 0)
6433 flags |= SMB_VCFLAG_REMOTECONN;
6435 osi_Log1(afsd_logp, "New session lsn %d", ncbp->ncb_lsn);
6437 lock_ObtainMutex(&smb_ListenerLock);
6439 /* New generation */
6442 /* Log session startup */
6444 fprintf(stderr, "New session(ncb_lsn,ncb_lana_num) %d,%d starting from host "
6446 ncbp->ncb_lsn,ncbp->ncb_lana_num, rname);
6448 afsi_log("New session(ncb_lsn,ncb_lana_num) (%d,%d) starting from host %s, %d ongoing ops",
6449 ncbp->ncb_lsn,ncbp->ncb_lana_num, rname, ongoingOps);
6451 if (reportSessionStartups) {
6457 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
6458 sprintf(s, "SMB session startup, %d ongoing ops", ongoingOps);
6460 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1004, NULL,
6462 DeregisterEventSource(h);
6464 afsi_log("NCBLISTEN completed, call from %s",rname);
6465 osi_Log1(afsd_logp, "SMB session startup, %d ongoing ops",
6468 fprintf(stderr, "%s: New session %d starting from host %s\n",
6469 asctime(localtime(&now)), ncbp->ncb_lsn, rname);
6474 /* now ncbp->ncb_lsn is the connection ID */
6475 vcp = smb_FindVC(ncbp->ncb_lsn, SMB_FLAG_CREATE, ncbp->ncb_lana_num);
6476 vcp->flags |= flags;
6477 strcpy(vcp->rname, rname);
6479 /* Allocate slot in session arrays */
6480 /* Re-use dead session if possible, otherwise add one more */
6481 /* But don't look at session[0], it is reserved */
6482 for (i = 1; i < numSessions; i++) {
6483 if (dead_sessions[i]) {
6484 afsi_log("connecting to dead session [ %d ]", i);
6485 dead_sessions[i] = FALSE;
6490 /* assert that we do not exceed the maximum number of sessions or NCBs.
6491 * we should probably want to wait for a session to be freed in case
6495 osi_assert(i < Sessionmax && numNCBs < NCBmax - 1);
6497 LSNs[i] = ncbp->ncb_lsn;
6498 lanas[i] = ncbp->ncb_lana_num;
6500 if (i == numSessions) {
6501 /* Add new NCB for new session */
6502 char eventName[MAX_PATH];
6504 osi_Log1(afsd_logp, "smb_Listener creating new session %d", i);
6506 InitNCBslot(numNCBs);
6508 thrd_SetEvent(NCBavails[0]);
6509 thrd_SetEvent(NCBevents[0]);
6510 for (j = 0; j < smb_NumServerThreads; j++)
6511 thrd_SetEvent(NCBreturns[j][0]);
6512 /* Also add new session event */
6513 sprintf(eventName, "SessionEvents[%d]", i);
6514 SessionEvents[i] = thrd_CreateEvent(NULL, FALSE, TRUE, eventName);
6515 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6516 afsi_log("Event Object Already Exists: %s", eventName);
6518 afsi_log("increasing numNCBs [ %d ] numSessions [ %d ]", numNCBs, numSessions);
6519 thrd_SetEvent(SessionEvents[0]);
6521 thrd_SetEvent(SessionEvents[i]);
6524 lock_ReleaseMutex(&smb_ListenerLock);
6526 } /* dispatch while loop */
6529 /* initialize Netbios */
6530 void smb_NetbiosInit()
6536 int i, lana, code, l;
6538 int delname_tried=0;
6541 OSVERSIONINFO Version;
6543 /* AFAIK, this is the default for the ms loopback adapter.*/
6544 unsigned char kWLA_MAC[6] = { 0x02, 0x00, 0x4c, 0x4f, 0x4f, 0x50 };
6545 /*******************************************************************/
6547 /* Get the version of Windows */
6548 memset(&Version, 0x00, sizeof(Version));
6549 Version.dwOSVersionInfoSize = sizeof(Version);
6550 GetVersionEx(&Version);
6552 /* setup the NCB system */
6555 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6559 if (smb_LANadapter == -1) {
6560 ncbp->ncb_command = NCBENUM;
6561 ncbp->ncb_buffer = (PUCHAR)&lana_list;
6562 ncbp->ncb_length = sizeof(lana_list);
6563 code = Netbios(ncbp);
6565 sprintf(s, "Netbios NCBENUM error code %d", code);
6567 osi_panic(s, __FILE__, __LINE__);
6571 lana_list.length = 1;
6572 lana_list.lana[0] = smb_LANadapter;
6575 for (i = 0; i < lana_list.length; i++) {
6576 /* reset the adaptor: in Win32, this is required for every process, and
6577 * acts as an init call, not as a real hardware reset.
6579 ncbp->ncb_command = NCBRESET;
6580 ncbp->ncb_callname[0] = 100;
6581 ncbp->ncb_callname[2] = 100;
6582 ncbp->ncb_lana_num = lana_list.lana[i];
6583 code = Netbios(ncbp);
6585 code = ncbp->ncb_retcode;
6587 sprintf(s, "Netbios NCBRESET lana %d error code %d", lana_list.lana[i], code);
6589 lana_list.lana[i] = 255; /* invalid lana */
6591 sprintf(s, "Netbios NCBRESET lana %d succeeded", lana_list.lana[i]);
6596 /* for DJGPP, there is no NCBENUM and NCBRESET is a real reset. so
6597 we will just fake the LANA list */
6598 if (smb_LANadapter == -1) {
6599 for (i = 0; i < 8; i++)
6600 lana_list.lana[i] = i;
6601 lana_list.length = 8;
6604 lana_list.length = 1;
6605 lana_list.lana[0] = smb_LANadapter;
6609 /* and declare our name so we can receive connections */
6610 memset(ncbp, 0, sizeof(*ncbp));
6611 len=lstrlen(smb_localNamep);
6612 memset(smb_sharename,' ',NCBNAMSZ);
6613 memcpy(smb_sharename,smb_localNamep,len);
6614 sprintf(s, "lana_list.length %d", lana_list.length);
6617 /* Keep the name so we can unregister it later */
6618 for (l = 0; l < lana_list.length; l++) {
6619 lana = lana_list.lana[l];
6621 ncbp->ncb_command = NCBADDNAME;
6622 ncbp->ncb_lana_num = lana;
6623 memcpy(ncbp->ncb_name,smb_sharename,NCBNAMSZ);
6625 code = Netbios(ncbp);
6627 code = Netbios(ncbp, dos_ncb);
6630 afsi_log("Netbios NCBADDNAME lana=%d code=%d retcode=%d complete=%d",
6631 lana, code, ncbp->ncb_retcode,ncbp->ncb_cmd_cplt);
6633 char name[NCBNAMSZ+1];
6635 memcpy(name,ncbp->ncb_name,NCBNAMSZ);
6636 afsi_log("Netbios NCBADDNAME added new name >%s<",name);
6639 if (code == 0) code = ncbp->ncb_retcode;
6641 afsi_log("Netbios NCBADDNAME succeeded on lana %d\n", lana);
6643 /* we only use one LANA with djgpp */
6644 lana_list.lana[0] = lana;
6645 lana_list.length = 1;
6649 sprintf(s, "Netbios NCBADDNAME lana %d error code %d", lana, code);
6651 if (code == NRC_BRIDGE) { /* invalid LANA num */
6652 lana_list.lana[l] = 255;
6655 else if (code == NRC_DUPNAME) {
6656 afsi_log("Name already exists; try to delete it");
6657 memset(ncbp, 0, sizeof(*ncbp));
6658 ncbp->ncb_command = NCBDELNAME;
6659 memcpy(ncbp->ncb_name,smb_sharename,NCBNAMSZ);
6660 ncbp->ncb_lana_num = lana;
6662 code = Netbios(ncbp);
6664 code = Netbios(ncbp, dos_ncb);
6666 if (code == 0) code = ncbp->ncb_retcode;
6668 sprintf(s, "Netbios NCBDELNAME lana %d error code %d\n", lana, code);
6671 if (code != 0 || delname_tried) {
6672 lana_list.lana[l] = 255;
6674 else if (code == 0) {
6675 if (!delname_tried) {
6683 sprintf(s, "Netbios NCBADDNAME lana %d error code %d", lana, code);
6685 lana_list.lana[l] = 255; /* invalid lana */
6686 osi_panic(s, __FILE__, __LINE__);
6690 lana_found = 1; /* at least one worked */
6697 osi_assert(lana_list.length >= 0);
6699 sprintf(s, "No valid LANA numbers found!");
6700 osi_panic(s, __FILE__, __LINE__);
6703 /* we're done with the NCB now */
6707 void smb_Init(osi_log_t *logp, char *snamep, int useV3, int LANadapt,
6724 EVENT_HANDLE retHandle;
6725 char eventName[MAX_PATH];
6728 smb_MBfunc = aMBfunc;
6732 /* check for demo expiration */
6734 unsigned long tod = time((void *) 0);
6735 if (tod > EXPIREDATE) {
6737 (*smb_MBfunc)(NULL, "AFS demo expiration", "afsd",
6738 MB_OK|MB_ICONSTOP|MB_SETFOREGROUND);
6741 fprintf(stderr, "AFS demo expiration\n");
6746 #endif /* !NOEXPIRE */
6749 smb_LANadapter = LANadapt;
6751 /* Initialize smb_localZero */
6752 myTime.tm_isdst = -1; /* compute whether on DST or not */
6753 myTime.tm_year = 70;
6759 smb_localZero = mktime(&myTime);
6761 /* Initialize kludge-GMT */
6762 smb_CalculateNowTZ();
6764 /* initialize the remote debugging log */
6767 /* remember the name */
6768 len = strlen(snamep);
6769 smb_localNamep = malloc(len+1);
6770 strcpy(smb_localNamep, snamep);
6771 afsi_log("smb_localNamep is >%s<", smb_localNamep);
6773 /* and the global lock */
6774 lock_InitializeRWLock(&smb_globalLock, "smb global lock");
6775 lock_InitializeRWLock(&smb_rctLock, "smb refct and tree struct lock");
6777 /* Raw I/O data structures */
6778 lock_InitializeMutex(&smb_RawBufLock, "smb raw buffer lock");
6780 lock_InitializeMutex(&smb_ListenerLock, "smb listener lock");
6782 /* 4 Raw I/O buffers */
6784 smb_RawBufs = calloc(65536,1);
6785 *((char **)smb_RawBufs) = NULL;
6786 for (i=0; i<3; i++) {
6787 char *rawBuf = calloc(65536,1);
6788 *((char **)rawBuf) = smb_RawBufs;
6789 smb_RawBufs = rawBuf;
6792 npar = 65536 >> 4; /* number of paragraphs */
6793 seg = __dpmi_allocate_dos_memory(npar, &smb_RawBufSel[0]);
6795 afsi_log("Cannot allocate %d paragraphs of DOS memory",
6797 osi_panic("",__FILE__,__LINE__);
6800 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X",
6803 smb_RawBufs = (seg * 16) + 0; /* DOS physical address */
6805 _farpokel(_dos_ds, smb_RawBufs, NULL);
6806 for (i=0; i<SMB_RAW_BUFS-1; i++) {
6807 npar = 65536 >> 4; /* number of paragraphs */
6808 seg = __dpmi_allocate_dos_memory(npar, &smb_RawBufSel[i+1]);
6810 afsi_log("Cannot allocate %d paragraphs of DOS memory",
6812 osi_panic("",__FILE__,__LINE__);
6815 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X",
6818 rawBuf = (seg * 16) + 0; /* DOS physical address */
6819 /*_farpokel(_dos_ds, smb_RawBufs, smb_RawBufs);*/
6820 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
6821 smb_RawBufs = rawBuf;
6825 /* global free lists */
6826 smb_ncbFreeListp = NULL;
6827 smb_packetFreeListp = NULL;
6831 /* Initialize listener and server structures */
6832 memset(dead_sessions, 0, sizeof(dead_sessions));
6833 sprintf(eventName, "SessionEvents[0]");
6834 SessionEvents[0] = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6835 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6836 afsi_log("Event Object Already Exists: %s", eventName);
6838 smb_NumServerThreads = nThreads;
6839 sprintf(eventName, "NCBavails[0]");
6840 NCBavails[0] = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6841 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6842 afsi_log("Event Object Already Exists: %s", eventName);
6843 sprintf(eventName, "NCBevents[0]");
6844 NCBevents[0] = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6845 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6846 afsi_log("Event Object Already Exists: %s", eventName);
6847 NCBreturns = malloc(nThreads * sizeof(EVENT_HANDLE *));
6848 sprintf(eventName, "NCBreturns[0<=i<smb_NumServerThreads][0]");
6849 retHandle = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6850 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6851 afsi_log("Event Object Already Exists: %s", eventName);
6852 for (i = 0; i < smb_NumServerThreads; i++) {
6853 NCBreturns[i] = malloc(NCBmax * sizeof(EVENT_HANDLE));
6854 NCBreturns[i][0] = retHandle;
6856 for (i = 1; i <= nThreads; i++)
6858 numNCBs = nThreads + 1;
6860 /* Initialize dispatch table */
6861 memset(&smb_dispatchTable, 0, sizeof(smb_dispatchTable));
6862 smb_dispatchTable[0x00].procp = smb_ReceiveCoreMakeDir;
6863 smb_dispatchTable[0x01].procp = smb_ReceiveCoreRemoveDir;
6864 smb_dispatchTable[0x02].procp = smb_ReceiveCoreOpen;
6865 smb_dispatchTable[0x03].procp = smb_ReceiveCoreCreate;
6866 smb_dispatchTable[0x04].procp = smb_ReceiveCoreClose;
6867 smb_dispatchTable[0x05].procp = smb_ReceiveCoreFlush;
6868 smb_dispatchTable[0x06].procp = smb_ReceiveCoreUnlink;
6869 smb_dispatchTable[0x07].procp = smb_ReceiveCoreRename;
6870 smb_dispatchTable[0x08].procp = smb_ReceiveCoreGetFileAttributes;
6871 smb_dispatchTable[0x09].procp = smb_ReceiveCoreSetFileAttributes;
6872 smb_dispatchTable[0x0a].procp = smb_ReceiveCoreRead;
6873 smb_dispatchTable[0x0b].procp = smb_ReceiveCoreWrite;
6874 smb_dispatchTable[0x0c].procp = smb_ReceiveCoreLockRecord;
6875 smb_dispatchTable[0x0d].procp = smb_ReceiveCoreUnlockRecord;
6876 smb_dispatchTable[0x0e].procp = smb_SendCoreBadOp; /* create temporary */
6877 smb_dispatchTable[0x0f].procp = smb_ReceiveCoreCreate;
6878 smb_dispatchTable[0x10].procp = smb_ReceiveCoreCheckPath;
6879 smb_dispatchTable[0x11].procp = smb_SendCoreBadOp; /* process exit */
6880 smb_dispatchTable[0x12].procp = smb_ReceiveCoreSeek;
6881 smb_dispatchTable[0x1a].procp = smb_ReceiveCoreReadRaw;
6882 /* Set NORESPONSE because smb_ReceiveCoreReadRaw() does the responses itself */
6883 smb_dispatchTable[0x1a].flags |= SMB_DISPATCHFLAG_NORESPONSE;
6884 smb_dispatchTable[0x1d].procp = smb_ReceiveCoreWriteRawDummy;
6885 smb_dispatchTable[0x22].procp = smb_ReceiveV3SetAttributes;
6886 smb_dispatchTable[0x23].procp = smb_ReceiveV3GetAttributes;
6887 smb_dispatchTable[0x24].procp = smb_ReceiveV3LockingX;
6888 smb_dispatchTable[0x24].flags |= SMB_DISPATCHFLAG_CHAINED;
6889 smb_dispatchTable[0x29].procp = smb_SendCoreBadOp; /* copy file */
6890 smb_dispatchTable[0x2b].procp = smb_ReceiveCoreEcho;
6891 /* Set NORESPONSE because smb_ReceiveCoreEcho() does the responses itself */
6892 smb_dispatchTable[0x2b].flags |= SMB_DISPATCHFLAG_NORESPONSE;
6893 smb_dispatchTable[0x2d].procp = smb_ReceiveV3OpenX;
6894 smb_dispatchTable[0x2d].flags |= SMB_DISPATCHFLAG_CHAINED;
6895 smb_dispatchTable[0x2e].procp = smb_ReceiveV3ReadX;
6896 smb_dispatchTable[0x2e].flags |= SMB_DISPATCHFLAG_CHAINED;
6897 smb_dispatchTable[0x32].procp = smb_ReceiveV3Tran2A; /* both are same */
6898 smb_dispatchTable[0x32].flags |= SMB_DISPATCHFLAG_NORESPONSE;
6899 smb_dispatchTable[0x33].procp = smb_ReceiveV3Tran2A;
6900 smb_dispatchTable[0x33].flags |= SMB_DISPATCHFLAG_NORESPONSE;
6901 smb_dispatchTable[0x34].procp = smb_ReceiveV3FindClose;
6902 smb_dispatchTable[0x35].procp = smb_ReceiveV3FindNotifyClose;
6903 smb_dispatchTable[0x70].procp = smb_ReceiveCoreTreeConnect;
6904 smb_dispatchTable[0x71].procp = smb_ReceiveCoreTreeDisconnect;
6905 smb_dispatchTable[0x72].procp = smb_ReceiveNegotiate;
6906 smb_dispatchTable[0x73].procp = smb_ReceiveV3SessionSetupX;
6907 smb_dispatchTable[0x73].flags |= SMB_DISPATCHFLAG_CHAINED;
6908 smb_dispatchTable[0x74].procp = smb_ReceiveV3UserLogoffX;
6909 smb_dispatchTable[0x74].flags |= SMB_DISPATCHFLAG_CHAINED;
6910 smb_dispatchTable[0x75].procp = smb_ReceiveV3TreeConnectX;
6911 smb_dispatchTable[0x75].flags |= SMB_DISPATCHFLAG_CHAINED;
6912 smb_dispatchTable[0x80].procp = smb_ReceiveCoreGetDiskAttributes;
6913 smb_dispatchTable[0x81].procp = smb_ReceiveCoreSearchDir;
6914 smb_dispatchTable[0xA0].procp = smb_ReceiveNTTransact;
6915 smb_dispatchTable[0xA2].procp = smb_ReceiveNTCreateX;
6916 smb_dispatchTable[0xA2].flags |= SMB_DISPATCHFLAG_CHAINED;
6917 smb_dispatchTable[0xA4].procp = smb_ReceiveNTCancel;
6918 smb_dispatchTable[0xA4].flags |= SMB_DISPATCHFLAG_NORESPONSE;
6919 smb_dispatchTable[0xc0].procp = smb_SendCoreBadOp;
6920 smb_dispatchTable[0xc1].procp = smb_SendCoreBadOp;
6921 smb_dispatchTable[0xc2].procp = smb_SendCoreBadOp;
6922 smb_dispatchTable[0xc3].procp = smb_SendCoreBadOp;
6923 for(i=0xd0; i<= 0xd7; i++) {
6924 smb_dispatchTable[i].procp = smb_SendCoreBadOp;
6927 /* setup tran 2 dispatch table */
6928 smb_tran2DispatchTable[0].procp = smb_ReceiveTran2Open;
6929 smb_tran2DispatchTable[1].procp = smb_ReceiveTran2SearchDir; /* FindFirst */
6930 smb_tran2DispatchTable[2].procp = smb_ReceiveTran2SearchDir; /* FindNext */
6931 smb_tran2DispatchTable[3].procp = smb_ReceiveTran2QFSInfo;
6932 smb_tran2DispatchTable[4].procp = smb_ReceiveTran2SetFSInfo;
6933 smb_tran2DispatchTable[5].procp = smb_ReceiveTran2QPathInfo;
6934 smb_tran2DispatchTable[6].procp = smb_ReceiveTran2SetPathInfo;
6935 smb_tran2DispatchTable[7].procp = smb_ReceiveTran2QFileInfo;
6936 smb_tran2DispatchTable[8].procp = smb_ReceiveTran2SetFileInfo;
6937 smb_tran2DispatchTable[9].procp = smb_ReceiveTran2FSCTL;
6938 smb_tran2DispatchTable[10].procp = smb_ReceiveTran2IOCTL;
6939 smb_tran2DispatchTable[11].procp = smb_ReceiveTran2FindNotifyFirst;
6940 smb_tran2DispatchTable[12].procp = smb_ReceiveTran2FindNotifyNext;
6941 smb_tran2DispatchTable[13].procp = smb_ReceiveTran2MKDir;
6945 /* Start listeners, waiters, servers, and daemons */
6947 for (i = 0; i < lana_list.length; i++) {
6948 if (lana_list.lana[i] == 255) continue;
6949 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_Listener,
6950 (void*)lana_list.lana[i], 0, &lpid, "smb_Listener");
6951 osi_assert(phandle != NULL);
6952 thrd_CloseHandle(phandle);
6956 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_ClientWaiter,
6957 NULL, 0, &lpid, "smb_ClientWaiter");
6958 osi_assert(phandle != NULL);
6959 thrd_CloseHandle(phandle);
6962 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_ServerWaiter,
6963 NULL, 0, &lpid, "smb_ServerWaiter");
6964 osi_assert(phandle != NULL);
6965 thrd_CloseHandle(phandle);
6967 for (i=0; i<nThreads; i++) {
6968 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_Server,
6969 (void *) i, 0, &lpid, "smb_Server");
6970 osi_assert(phandle != NULL);
6971 thrd_CloseHandle(phandle);
6974 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_Daemon,
6975 NULL, 0, &lpid, "smb_Daemon");
6976 osi_assert(phandle != NULL);
6977 thrd_CloseHandle(phandle);
6979 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_WaitingLocksDaemon,
6980 NULL, 0, &lpid, "smb_WaitingLocksDaemon");
6981 osi_assert(phandle != NULL);
6982 thrd_CloseHandle(phandle);
6991 void smb_Shutdown(void)
7000 /*fprintf(stderr, "Entering smb_Shutdown\n");*/
7002 /* setup the NCB system */
7005 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
7008 /* Block new sessions by setting shutdown flag */
7009 smbShutdownFlag = 1;
7011 /* Hang up all sessions */
7012 memset((char *)ncbp, 0, sizeof(NCB));
7013 for (i = 1; i < numSessions; i++)
7015 if (dead_sessions[i])
7018 /*fprintf(stderr, "NCBHANGUP session %d LSN %d\n", i, LSNs[i]);*/
7019 ncbp->ncb_command = NCBHANGUP;
7020 ncbp->ncb_lana_num = lanas[i]; /*smb_LANadapter;*/
7021 ncbp->ncb_lsn = LSNs[i];
7023 code = Netbios(ncbp);
7025 code = Netbios(ncbp, dos_ncb);
7027 /*fprintf(stderr, "returned from NCBHANGUP session %d LSN %d\n", i, LSNs[i]);*/
7028 if (code == 0) code = ncbp->ncb_retcode;
7030 osi_Log1(afsd_logp, "Netbios NCBHANGUP error code %d", code);
7031 fprintf(stderr, "Session %d Netbios NCBHANGUP error code %d", i, code);
7035 /* Delete Netbios name */
7036 memset((char *)ncbp, 0, sizeof(NCB));
7037 for (i = 0; i < lana_list.length; i++) {
7038 if (lana_list.lana[i] == 255) continue;
7039 ncbp->ncb_command = NCBDELNAME;
7040 ncbp->ncb_lana_num = lana_list.lana[i];
7041 memcpy(ncbp->ncb_name,smb_sharename,NCBNAMSZ);
7043 code = Netbios(ncbp);
7045 code = Netbios(ncbp, dos_ncb);
7047 if (code == 0) code = ncbp->ncb_retcode;
7049 fprintf(stderr, "Netbios NCBDELNAME lana %d error code %d",
7050 ncbp->ncb_lana_num, code);
7056 /* Get the UNC \\<servername>\<sharename> prefix. */
7057 char *smb_GetSharename()
7061 /* Make sure we have been properly initialized. */
7062 if (smb_localNamep == NULL)
7065 /* Allocate space for \\<servername>\<sharename>, plus the
7068 name = malloc(strlen(smb_localNamep) + strlen("ALL") + 4);
7069 sprintf(name, "\\\\%s\\%s", smb_localNamep, "ALL");
7075 void smb_LogPacket(smb_packet_t *packet)
7078 unsigned length, paramlen, datalen, i, j;
7080 char hex[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
7084 osi_Log0(afsd_logp, "*** SMB packet dump ***");
7086 vp = (BYTE *) packet->data;
7088 datalen = *((WORD*)(vp + (paramlen = ((unsigned)*(vp+20)) << 1)));
7089 length = paramlen + 2 + datalen;
7092 for(i=0;i < length; i+=16)
7094 memset( buf, ' ', 80 );
7099 buf[strlen(buf)] = ' ';
7101 cp = (BYTE*) buf + 7;
7103 for(j=0;j < 16 && (i+j)<length; j++)
7105 *(cp++) = hex[vp[i+j] >> 4];
7106 *(cp++) = hex[vp[i+j] & 0xf];
7116 for(j=0;j < 16 && (i+j)<length;j++)
7118 *(cp++) = ( 32 <= vp[i+j] && 128 > vp[i+j] )? vp[i+j]:'.';
7129 osi_Log0( afsd_logp, buf );
7132 osi_Log0(afsd_logp, "*** End SMB packet dump ***");
7136 #endif /* NOTSERVICE */
7138 int smb_DumpVCP(FILE *outputFile, char *cookie)
7145 lock_ObtainRead(&smb_rctLock);
7147 for(vcp = smb_allVCsp; vcp; vcp=vcp->nextp)
7151 sprintf(output, "%s vcp=0x%08X, refCount=%d, flags=%d, vcID=%d, lsn=%d, uidCounter=%d, tidCounter=%d, fidCounter=%d\n",
7152 cookie, vcp, vcp->refCount, vcp->flags, vcp->vcID, vcp->lsn, vcp->uidCounter, vcp->tidCounter, vcp->fidCounter);
7153 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7155 for(fidp = vcp->fidsp; fidp; fidp = (smb_fid_t *) osi_QNext(&fidp->q))
7157 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",
7158 cookie, fidp, fidp->refCount, fidp->fid, fidp->vcp, fidp->scp, fidp->ioctlp,
7159 fidp->NTopen_pathp ? fidp->NTopen_pathp : "NULL",
7160 fidp->NTopen_wholepathp ? fidp->NTopen_wholepathp : "NULL");
7161 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7164 sprintf(output, "done dumping fidsp\n");
7165 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7168 lock_ReleaseRead(&smb_rctLock);