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 lock_ObtainWrite(&smb_rctLock);
977 /* figure out if we need to allocate a new file ID */
980 fid = vcp->fidCounter;
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)
1014 vcp->fidCounter = 1;
1017 lock_ReleaseWrite(&smb_rctLock);
1021 void smb_ReleaseFID(smb_fid_t *fidp)
1025 smb_ioctl_t *ioctlp;
1031 lock_ObtainWrite(&smb_rctLock);
1032 osi_assert(fidp->refCount-- > 0);
1033 if (fidp->refCount == 0 && (fidp->flags & SMB_FID_DELETE)) {
1035 if (!(fidp->flags & SMB_FID_IOCTL))
1037 osi_QRemove((osi_queue_t **) &vcp->fidsp, &fidp->q);
1038 thrd_CloseHandle(fidp->raw_write_event);
1040 /* and see if there is ioctl stuff to free */
1041 ioctlp = fidp->ioctlp;
1043 if (ioctlp->prefix) cm_FreeSpace(ioctlp->prefix);
1044 if (ioctlp->inAllocp) free(ioctlp->inAllocp);
1045 if (ioctlp->outAllocp) free(ioctlp->outAllocp);
1051 lock_ReleaseWrite(&smb_rctLock);
1053 /* now release the scache structure */
1055 cm_ReleaseSCache(scp);
1059 * Case-insensitive search for one string in another;
1060 * used to find variable names in submount pathnames.
1062 static char *smb_stristr(char *str1, char *str2)
1066 for (cursor = str1; *cursor; cursor++)
1067 if (stricmp(cursor, str2) == 0)
1074 * Substitute a variable value for its name in a submount pathname. Variable
1075 * name has been identified by smb_stristr() and is in substr. Variable name
1076 * length (plus one) is in substr_size. Variable value is in newstr.
1078 static void smb_subst(char *str1, char *substr, unsigned int substr_size,
1083 strcpy(temp, substr + substr_size - 1);
1084 strcpy(substr, newstr);
1088 char VNUserName[] = "%USERNAME%";
1089 char VNLCUserName[] = "%LCUSERNAME%";
1090 char VNComputerName[] = "%COMPUTERNAME%";
1091 char VNLCComputerName[] = "%LCCOMPUTERNAME%";
1093 /* List available shares */
1094 int smb_ListShares()
1098 char shareBuf[4096];
1106 /*strcpy(shareNameList[num_shares], "all");
1107 strcpy(pathNameList[num_shares++], "/afs");*/
1108 fprintf(stderr, "The following shares are available:\n");
1109 fprintf(stderr, "Share Name (AFS Path)\n");
1110 fprintf(stderr, "---------------------\n");
1111 fprintf(stderr, "\\\\%s\\%-16s (%s)\n", smb_localNamep, "ALL", cm_mountRoot);
1114 code = GetWindowsDirectory(sbmtpath, sizeof(sbmtpath));
1115 if (code == 0 || code > sizeof(sbmtpath)) return -1;
1117 strcpy(sbmtpath, cm_confDir);
1119 strcat(sbmtpath, "/afsdsbmt.ini");
1120 len = GetPrivateProfileString("AFS Submounts", NULL, NULL,
1121 shareBuf, sizeof(shareBuf),
1127 this_share = shareBuf;
1131 /*strcpy(shareNameList[num_shares], this_share);*/
1132 len = GetPrivateProfileString("AFS Submounts", this_share,
1139 if (strncmp(p, cm_mountRoot, strlen(cm_mountRoot)) != 0)
1142 if (*p == '\\') *p = '/'; /* change to / */
1146 fprintf(stderr, "\\\\%s\\%-16s (%s%s)\n",
1147 smb_localNamep, this_share, (print_afs ? cm_mountRoot : "\0"),
1150 while (*this_share != 0) this_share++; /* find next NUL */
1151 this_share++; /* skip past the NUL */
1152 } while (*this_share != 0); /* stop at final NUL */
1157 /* find a shareName in the table of submounts */
1158 int smb_FindShare(smb_vc_t *vcp, smb_packet_t *inp, char *shareName,
1162 char pathName[1024];
1167 char sbmtpath[MAX_PATH];
1171 DWORD allSubmount = 1;
1173 if (strcmp(shareName, "IPC$") == 0) {
1178 /* if allSubmounts == 0, only return the //mountRoot/all share
1179 * if in fact it has been been created in the subMounts table.
1180 * This is to allow sites that want to restrict access to the
1183 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSConfigKeyName,
1184 0, KEY_QUERY_VALUE, &parmKey);
1185 if (code == ERROR_SUCCESS) {
1186 len = sizeof(allSubmount);
1187 code = RegQueryValueEx(parmKey, "AllSubmount", NULL, NULL,
1188 (BYTE *) &allSubmount, &len);
1189 if (code != ERROR_SUCCESS) {
1192 RegCloseKey (parmKey);
1195 if (allSubmount && _stricmp(shareName, "all") == 0) {
1200 /* In case, the all share is disabled we need to still be able
1201 * to handle ioctl requests
1203 if (_stricmp(shareName, "ioctl$") == 0) {
1204 *pathNamep = strdup("/.__ioctl__");
1209 strcpy(sbmtpath, "afsdsbmt.ini");
1211 strcpy(sbmtpath, cm_confDir);
1212 strcat(sbmtpath, "/afsdsbmt.ini");
1214 len = GetPrivateProfileString("AFS Submounts", shareName, "",
1215 pathName, sizeof(pathName), sbmtpath);
1216 if (len != 0 && len != sizeof(pathName) - 1) {
1217 /* We can accept either unix or PC style AFS pathnames. Convert
1218 * Unix-style to PC style here for internal use.
1221 if (strncmp(p, cm_mountRoot, strlen(cm_mountRoot)) == 0)
1222 p += strlen(cm_mountRoot); /* skip mount path */
1225 if (*q == '/') *q = '\\'; /* change to \ */
1231 if (var = smb_stristr(p, VNUserName)) {
1232 uidp = smb_FindUID(vcp, ((smb_t *)inp)->uid, 0);
1233 if (uidp && uidp->unp)
1234 smb_subst(p, var, sizeof(VNUserName),uidp->unp->name);
1236 smb_subst(p, var, sizeof(VNUserName)," ");
1238 smb_ReleaseUID(uidp);
1240 else if (var = smb_stristr(p, VNLCUserName))
1242 uidp = smb_FindUID(vcp, ((smb_t *)inp)->uid, 0);
1243 if (uidp && uidp->unp)
1244 strcpy(temp, uidp->unp->name);
1248 smb_subst(p, var, sizeof(VNLCUserName), temp);
1250 smb_ReleaseUID(uidp);
1252 else if (var = smb_stristr(p, VNComputerName))
1254 sizeTemp = sizeof(temp);
1255 GetComputerName((LPTSTR)temp, &sizeTemp);
1256 smb_subst(p, var, sizeof(VNComputerName), temp);
1258 else if (var = smb_stristr(p, VNLCComputerName))
1260 sizeTemp = sizeof(temp);
1261 GetComputerName((LPTSTR)temp, &sizeTemp);
1263 smb_subst(p, var, sizeof(VNLCComputerName), temp);
1268 *pathNamep = strdup(p);
1271 else /* create \\<netbiosName>\<cellname> */
1273 char * p = shareName;
1280 /* Get the full name for this cell */
1281 code = cm_SearchCellFile(p, temp, 0, 0);
1282 #ifdef AFS_AFSDB_ENV
1283 if (code && cm_dnsEnabled) {
1285 code = cm_SearchCellByDNS(p, temp, &ttl, 0, 0);
1288 /* construct the path */
1290 sprintf(pathName,rw ? "/.%s/" : "/%s/",temp);
1291 *pathNamep = strdup(strlwr(pathName));
1300 /* find a dir search structure by cookie value, and return it held.
1301 * Must be called with smb_globalLock held.
1303 smb_dirSearch_t *smb_FindDirSearchNL(long cookie)
1305 smb_dirSearch_t *dsp;
1307 for(dsp = smb_firstDirSearchp; dsp; dsp = (smb_dirSearch_t *) osi_QNext(&dsp->q)) {
1308 if (dsp->cookie == cookie) {
1309 if (dsp != smb_firstDirSearchp) {
1310 /* move to head of LRU queue, too, if we're not already there */
1311 if (smb_lastDirSearchp == (smb_dirSearch_t *) &dsp->q)
1312 smb_lastDirSearchp = (smb_dirSearch_t *)
1314 osi_QRemove((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1315 osi_QAdd((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1316 if (!smb_lastDirSearchp)
1317 smb_lastDirSearchp = (smb_dirSearch_t *) &dsp->q;
1326 void smb_DeleteDirSearch(smb_dirSearch_t *dsp)
1328 lock_ObtainWrite(&smb_globalLock);
1329 dsp->flags |= SMB_DIRSEARCH_DELETE;
1330 lock_ReleaseWrite(&smb_globalLock);
1331 lock_ObtainMutex(&dsp->mx);
1332 if(dsp->scp != NULL) {
1333 lock_ObtainMutex(&dsp->scp->mx);
1334 if (dsp->flags & SMB_DIRSEARCH_BULKST) {
1335 dsp->flags &= ~SMB_DIRSEARCH_BULKST;
1336 dsp->scp->flags &= ~CM_SCACHEFLAG_BULKSTATTING;
1337 dsp->scp->bulkStatProgress = hones;
1339 lock_ReleaseMutex(&dsp->scp->mx);
1341 lock_ReleaseMutex(&dsp->mx);
1344 void smb_ReleaseDirSearch(smb_dirSearch_t *dsp)
1350 lock_ObtainWrite(&smb_globalLock);
1351 osi_assert(dsp->refCount-- > 0);
1352 if (dsp->refCount == 0 && (dsp->flags & SMB_DIRSEARCH_DELETE)) {
1353 if (&dsp->q == (osi_queue_t *) smb_lastDirSearchp)
1354 smb_lastDirSearchp = (smb_dirSearch_t *) osi_QPrev(&smb_lastDirSearchp->q);
1355 osi_QRemove((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1356 lock_FinalizeMutex(&dsp->mx);
1360 lock_ReleaseWrite(&smb_globalLock);
1362 /* do this now to avoid spurious locking hierarchy creation */
1363 if (scp) cm_ReleaseSCache(scp);
1366 /* find a dir search structure by cookie value, and return it held */
1367 smb_dirSearch_t *smb_FindDirSearch(long cookie)
1369 smb_dirSearch_t *dsp;
1371 lock_ObtainWrite(&smb_globalLock);
1372 dsp = smb_FindDirSearchNL(cookie);
1373 lock_ReleaseWrite(&smb_globalLock);
1377 /* GC some dir search entries, in the address space expected by the specific protocol.
1378 * Must be called with smb_globalLock held; release the lock temporarily.
1380 #define SMB_DIRSEARCH_GCMAX 10 /* how many at once */
1381 void smb_GCDirSearches(int isV3)
1383 smb_dirSearch_t *prevp;
1384 smb_dirSearch_t *tp;
1385 smb_dirSearch_t *victimsp[SMB_DIRSEARCH_GCMAX];
1389 victimCount = 0; /* how many have we got so far */
1390 for(tp = smb_lastDirSearchp; tp; tp=prevp) {
1391 /* we'll move tp from queue, so
1394 prevp = (smb_dirSearch_t *) osi_QPrev(&tp->q);
1395 /* if no one is using this guy, and we're either in the new protocol,
1396 * or we're in the old one and this is a small enough ID to be useful
1397 * to the old protocol, GC this guy.
1399 if (tp->refCount == 0 && (isV3 || tp->cookie <= 255)) {
1400 /* hold and delete */
1401 tp->flags |= SMB_DIRSEARCH_DELETE;
1402 victimsp[victimCount++] = tp;
1406 /* don't do more than this */
1407 if (victimCount >= SMB_DIRSEARCH_GCMAX) break;
1410 /* now release them */
1411 lock_ReleaseWrite(&smb_globalLock);
1412 for(i = 0; i < victimCount; i++) {
1413 smb_ReleaseDirSearch(victimsp[i]);
1415 lock_ObtainWrite(&smb_globalLock);
1418 /* function for allocating a dir search entry. We need these to remember enough context
1419 * since we don't get passed the path from call to call during a directory search.
1421 * Returns a held dir search structure, and bumps the reference count on the vnode,
1422 * since it saves a pointer to the vnode.
1424 smb_dirSearch_t *smb_NewDirSearch(int isV3)
1426 smb_dirSearch_t *dsp;
1430 lock_ObtainWrite(&smb_globalLock);
1433 /* what's the biggest ID allowed in this version of the protocol */
1434 if (isV3) maxAllowed = 65535;
1435 else maxAllowed = 255;
1438 /* twice so we have enough tries to find guys we GC after one pass;
1439 * 10 extra is just in case I mis-counted.
1441 if (++counter > 2*maxAllowed+10) osi_panic("afsd: dir search cookie leak",
1442 __FILE__, __LINE__);
1443 if (smb_dirSearchCounter > maxAllowed) {
1444 smb_dirSearchCounter = 1;
1445 smb_GCDirSearches(isV3); /* GC some (drops global lock) */
1447 dsp = smb_FindDirSearchNL(smb_dirSearchCounter);
1449 /* don't need to watch for refcount zero and deleted, since
1450 * we haven't dropped the global lock.
1453 ++smb_dirSearchCounter;
1457 dsp = malloc(sizeof(*dsp));
1458 memset(dsp, 0, sizeof(*dsp));
1459 osi_QAdd((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1460 if (!smb_lastDirSearchp) smb_lastDirSearchp = (smb_dirSearch_t *) &dsp->q;
1461 dsp->cookie = smb_dirSearchCounter;
1462 ++smb_dirSearchCounter;
1464 lock_InitializeMutex(&dsp->mx, "cm_dirSearch_t");
1465 dsp->lastTime = osi_Time();
1468 lock_ReleaseWrite(&smb_globalLock);
1472 static smb_packet_t *GetPacket(void)
1476 unsigned int npar, seg, tb_sel;
1479 lock_ObtainWrite(&smb_globalLock);
1480 tbp = smb_packetFreeListp;
1482 smb_packetFreeListp = tbp->nextp;
1483 lock_ReleaseWrite(&smb_globalLock);
1486 tbp = calloc(65540,1);
1488 tbp = malloc(sizeof(smb_packet_t));
1490 tbp->magic = SMB_PACKETMAGIC;
1493 tbp->resumeCode = 0;
1499 tbp->ncb_length = 0;
1504 npar = SMB_PACKETSIZE >> 4; /* number of paragraphs */
1507 __dpmi_allocate_dos_memory(npar, &tb_sel); /* DOS segment */
1509 afsi_log("Cannot allocate %d paragraphs of DOS memory",
1511 osi_panic("",__FILE__,__LINE__);
1514 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X",
1519 tbp->dos_pkt = (seg * 16) + 0; /* DOS physical address */
1520 tbp->dos_pkt_sel = tb_sel;
1523 osi_assert(tbp->magic == SMB_PACKETMAGIC);
1528 smb_packet_t *smb_CopyPacket(smb_packet_t *pkt)
1532 memcpy(tbp, pkt, sizeof(smb_packet_t));
1533 tbp->wctp = tbp->data + ((unsigned int)pkt->wctp - (unsigned int)pkt->data);
1537 static NCB *GetNCB(void)
1542 unsigned int npar, seg, tb_sel;
1545 lock_ObtainWrite(&smb_globalLock);
1546 tbp = smb_ncbFreeListp;
1548 smb_ncbFreeListp = tbp->nextp;
1549 lock_ReleaseWrite(&smb_globalLock);
1552 tbp = calloc(sizeof(*tbp),1);
1554 tbp = malloc(sizeof(*tbp));
1555 npar = (sizeof(NCB)+15) >> 4; /* number of paragraphs */
1558 __dpmi_allocate_dos_memory(npar, &tb_sel); /* DOS segment */
1560 afsi_log("Cannot allocate %d paragraphs of DOS mem in GetNCB",
1562 osi_panic("",__FILE__,__LINE__);
1564 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X in GetNCB",
1569 tbp->dos_ncb = (seg * 16) + 0; /* DOS physical address */
1570 tbp->dos_ncb_sel = tb_sel;
1572 tbp->magic = SMB_NCBMAGIC;
1575 osi_assert(tbp->magic == SMB_NCBMAGIC);
1577 memset(&tbp->ncb, 0, sizeof(NCB));
1580 dos_memset(tbp->dos_ncb, 0, sizeof(NCB));
1585 void smb_FreePacket(smb_packet_t *tbp)
1587 osi_assert(tbp->magic == SMB_PACKETMAGIC);
1589 lock_ObtainWrite(&smb_globalLock);
1590 tbp->nextp = smb_packetFreeListp;
1591 smb_packetFreeListp = tbp;
1592 tbp->magic = SMB_PACKETMAGIC;
1595 tbp->resumeCode = 0;
1601 tbp->ncb_length = 0;
1603 lock_ReleaseWrite(&smb_globalLock);
1606 static void FreeNCB(NCB *bufferp)
1610 tbp = (smb_ncb_t *) bufferp;
1611 osi_assert(tbp->magic == SMB_NCBMAGIC);
1613 lock_ObtainWrite(&smb_globalLock);
1614 tbp->nextp = smb_ncbFreeListp;
1615 smb_ncbFreeListp = tbp;
1616 lock_ReleaseWrite(&smb_globalLock);
1619 /* get a ptr to the data part of a packet, and its count */
1620 unsigned char *smb_GetSMBData(smb_packet_t *smbp, int *nbytesp)
1624 unsigned char *afterParmsp;
1626 parmBytes = *smbp->wctp << 1;
1627 afterParmsp = smbp->wctp + parmBytes + 1;
1629 dataBytes = afterParmsp[0] + (afterParmsp[1]<<8);
1630 if (nbytesp) *nbytesp = dataBytes;
1632 /* don't forget to skip the data byte count, since it follows
1633 * the parameters; that's where the "2" comes from below.
1635 return (unsigned char *) (afterParmsp + 2);
1638 /* must set all the returned parameters before playing around with the
1639 * data region, since the data region is located past the end of the
1640 * variable number of parameters.
1642 void smb_SetSMBDataLength(smb_packet_t *smbp, unsigned int dsize)
1644 unsigned char *afterParmsp;
1646 afterParmsp = smbp->wctp + ((*smbp->wctp)<<1) + 1;
1648 *afterParmsp++ = dsize & 0xff;
1649 *afterParmsp = (dsize>>8) & 0xff;
1652 /* return the parm'th parameter in the smbp packet */
1653 unsigned int smb_GetSMBParm(smb_packet_t *smbp, int parm)
1656 unsigned char *parmDatap;
1658 parmCount = *smbp->wctp;
1660 if (parm >= parmCount) {
1665 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
1666 sprintf(s, "Bad SMB param %d out of %d, ncb len %d",
1667 parm, parmCount, smbp->ncb_length);
1669 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1006, NULL,
1670 1, smbp->ncb_length, ptbuf, smbp);
1671 DeregisterEventSource(h);
1675 sprintf(s, "Bad SMB param %d out of %d, ncb len %d",
1676 parm, parmCount, smbp->ncb_length);
1677 osi_Log0(afsd_logp, s);
1679 osi_panic(s, __FILE__, __LINE__);
1681 parmDatap = smbp->wctp + (2*parm) + 1;
1683 return parmDatap[0] + (parmDatap[1] << 8);
1686 /* return the parm'th parameter in the smbp packet */
1687 unsigned int smb_GetSMBOffsetParm(smb_packet_t *smbp, int parm, int offset)
1690 unsigned char *parmDatap;
1692 parmCount = *smbp->wctp;
1694 if (parm * 2 + offset >= parmCount * 2) {
1699 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
1700 sprintf(s, "Bad SMB param %d offset %d out of %d, ncb len %d",
1701 parm, offset, parmCount, smbp->ncb_length);
1703 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1006, NULL,
1704 1, smbp->ncb_length, ptbuf, smbp);
1705 DeregisterEventSource(h);
1709 sprintf(s, "Bad SMB param %d offset %d out of %d, "
1711 parm, offset, parmCount, smbp->ncb_length);
1712 osi_Log0(afsd_logp, s);
1715 osi_panic(s, __FILE__, __LINE__);
1717 parmDatap = smbp->wctp + (2*parm) + 1 + offset;
1719 return parmDatap[0] + (parmDatap[1] << 8);
1722 void smb_SetSMBParm(smb_packet_t *smbp, int slot, unsigned int parmValue)
1726 /* make sure we have enough slots */
1727 if (*smbp->wctp <= slot) *smbp->wctp = slot+1;
1729 parmDatap = smbp->wctp + 2*slot + 1 + smbp->oddByte;
1730 *parmDatap++ = parmValue & 0xff;
1731 *parmDatap = (parmValue>>8) & 0xff;
1734 void smb_SetSMBParmLong(smb_packet_t *smbp, int slot, unsigned int parmValue)
1738 /* make sure we have enough slots */
1739 if (*smbp->wctp <= slot) *smbp->wctp = slot+2;
1741 parmDatap = smbp->wctp + 2*slot + 1 + smbp->oddByte;
1742 *parmDatap++ = parmValue & 0xff;
1743 *parmDatap++ = (parmValue>>8) & 0xff;
1744 *parmDatap++ = (parmValue>>16) & 0xff;
1745 *parmDatap++ = (parmValue>>24) & 0xff;
1748 void smb_SetSMBParmDouble(smb_packet_t *smbp, int slot, char *parmValuep)
1753 /* make sure we have enough slots */
1754 if (*smbp->wctp <= slot) *smbp->wctp = slot+4;
1756 parmDatap = smbp->wctp + 2*slot + 1 + smbp->oddByte;
1758 *parmDatap++ = *parmValuep++;
1761 void smb_SetSMBParmByte(smb_packet_t *smbp, int slot, unsigned int parmValue)
1765 /* make sure we have enough slots */
1766 if (*smbp->wctp <= slot) {
1767 if (smbp->oddByte) {
1769 *smbp->wctp = slot+1;
1774 parmDatap = smbp->wctp + 2*slot + 1 + (1 - smbp->oddByte);
1775 *parmDatap++ = parmValue & 0xff;
1778 void smb_StripLastComponent(char *outPathp, char **lastComponentp, char *inPathp)
1782 lastSlashp = strrchr(inPathp, '\\');
1784 *lastComponentp = lastSlashp;
1787 if (inPathp == lastSlashp)
1789 *outPathp++ = *inPathp++;
1798 unsigned char *smb_ParseASCIIBlock(unsigned char *inp, char **chainpp)
1803 *chainpp = inp + strlen(inp) + 1; /* skip over null-terminated string */
1808 unsigned char *smb_ParseVblBlock(unsigned char *inp, char **chainpp, int *lengthp)
1814 tlen = inp[0] + (inp[1]<<8);
1815 inp += 2; /* skip length field */
1818 *chainpp = inp + tlen;
1827 /* format a packet as a response */
1828 void smb_FormatResponsePacket(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *op)
1833 outp = (smb_t *) op;
1835 /* zero the basic structure through the smb_wct field, and zero the data
1836 * size field, assuming that wct stays zero; otherwise, you have to
1837 * explicitly set the data size field, too.
1839 inSmbp = (smb_t *) inp;
1840 memset(outp, 0, sizeof(smb_t)+2);
1846 outp->com = inSmbp->com;
1847 outp->tid = inSmbp->tid;
1848 outp->pid = inSmbp->pid;
1849 outp->uid = inSmbp->uid;
1850 outp->mid = inSmbp->mid;
1851 outp->res[0] = inSmbp->res[0];
1852 outp->res[1] = inSmbp->res[1];
1853 op->inCom = inSmbp->com;
1855 outp->reb = 0x80; /* SERVER_RESP */
1856 outp->flg2 = 0x1; /* KNOWS_LONG_NAMES */
1858 /* copy fields in generic packet area */
1859 op->wctp = &outp->wct;
1862 /* send a (probably response) packet; vcp tells us to whom to send it.
1863 * we compute the length by looking at wct and bcc fields.
1865 void smb_SendPacket(smb_vc_t *vcp, smb_packet_t *inp)
1882 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
1885 memset((char *)ncbp, 0, sizeof(NCB));
1887 extra = 2 * (*inp->wctp); /* space used by parms, in bytes */
1888 tp = inp->wctp + 1+ extra; /* points to count of data bytes */
1889 extra += tp[0] + (tp[1]<<8);
1890 extra += ((unsigned int)inp->wctp - (unsigned int)inp->data); /* distance to last wct field */
1891 extra += 3; /* wct and length fields */
1893 ncbp->ncb_length = extra; /* bytes to send */
1894 ncbp->ncb_lsn = (unsigned char) vcp->lsn; /* vc to use */
1895 ncbp->ncb_lana_num = vcp->lana;
1896 ncbp->ncb_command = NCBSEND; /* op means send data */
1898 ncbp->ncb_buffer = (char *) inp;/* packet */
1899 code = Netbios(ncbp);
1901 ncbp->ncb_buffer = inp->dos_pkt;/* packet */
1902 ((smb_ncb_t*)ncbp)->orig_pkt = inp;
1904 /* copy header information from virtual to DOS address space */
1905 dosmemput((char*)inp, SMB_PACKETSIZE, inp->dos_pkt);
1906 code = Netbios(ncbp, dos_ncb);
1910 osi_Log1(afsd_logp, "SendPacket failure code %d", code);
1916 void smb_MapNTError(long code, unsigned long *NTStatusp)
1918 unsigned long NTStatus;
1920 /* map CM_ERROR_* errors to NT 32-bit status codes */
1921 if (code == CM_ERROR_NOSUCHCELL) {
1922 NTStatus = 0xC000000FL; /* No such file */
1924 else if (code == CM_ERROR_NOSUCHVOLUME) {
1925 NTStatus = 0xC000000FL; /* No such file */
1927 else if (code == CM_ERROR_TIMEDOUT) {
1928 NTStatus = 0xC00000CFL; /* Sharing Paused */
1930 else if (code == CM_ERROR_RETRY) {
1931 NTStatus = 0xC000022DL; /* Retry */
1933 else if (code == CM_ERROR_NOACCESS) {
1934 NTStatus = 0xC0000022L; /* Access denied */
1936 else if (code == CM_ERROR_READONLY) {
1937 NTStatus = 0xC00000A2L; /* Write protected */
1939 else if (code == CM_ERROR_NOSUCHFILE) {
1940 NTStatus = 0xC000000FL; /* No such file */
1942 else if (code == CM_ERROR_NOSUCHPATH) {
1943 NTStatus = 0xC000003AL; /* Object path not found */
1945 else if (code == CM_ERROR_TOOBIG) {
1946 NTStatus = 0xC000007BL; /* Invalid image format */
1948 else if (code == CM_ERROR_INVAL) {
1949 NTStatus = 0xC000000DL; /* Invalid parameter */
1951 else if (code == CM_ERROR_BADFD) {
1952 NTStatus = 0xC0000008L; /* Invalid handle */
1954 else if (code == CM_ERROR_BADFDOP) {
1955 NTStatus = 0xC0000022L; /* Access denied */
1957 else if (code == CM_ERROR_EXISTS) {
1958 NTStatus = 0xC0000035L; /* Object name collision */
1960 else if (code == CM_ERROR_NOTEMPTY) {
1961 NTStatus = 0xC0000101L; /* Directory not empty */
1963 else if (code == CM_ERROR_CROSSDEVLINK) {
1964 NTStatus = 0xC00000D4L; /* Not same device */
1966 else if (code == CM_ERROR_NOTDIR) {
1967 NTStatus = 0xC0000103L; /* Not a directory */
1969 else if (code == CM_ERROR_ISDIR) {
1970 NTStatus = 0xC00000BAL; /* File is a directory */
1972 else if (code == CM_ERROR_BADOP) {
1973 NTStatus = 0xC09820FFL; /* SMB no support */
1975 else if (code == CM_ERROR_BADSHARENAME) {
1976 NTStatus = 0xC00000CCL; /* Bad network name */
1978 else if (code == CM_ERROR_NOIPC) {
1980 NTStatus = 0xC0000022L; /* Access Denied */
1982 NTStatus = 0xC000013DL; /* Remote Resources */
1985 else if (code == CM_ERROR_CLOCKSKEW) {
1986 NTStatus = 0xC0000133L; /* Time difference at DC */
1988 else if (code == CM_ERROR_BADTID) {
1989 NTStatus = 0xC0982005L; /* SMB bad TID */
1991 else if (code == CM_ERROR_USESTD) {
1992 NTStatus = 0xC09820FBL; /* SMB use standard */
1994 else if (code == CM_ERROR_QUOTA) {
1995 NTStatus = 0xC0000044L; /* Quota exceeded */
1997 else if (code == CM_ERROR_SPACE) {
1998 NTStatus = 0xC000007FL; /* Disk full */
2000 else if (code == CM_ERROR_ATSYS) {
2001 NTStatus = 0xC0000033L; /* Object name invalid */
2003 else if (code == CM_ERROR_BADNTFILENAME) {
2004 NTStatus = 0xC0000033L; /* Object name invalid */
2006 else if (code == CM_ERROR_WOULDBLOCK) {
2007 NTStatus = 0xC0000055L; /* Lock not granted */
2009 else if (code == CM_ERROR_PARTIALWRITE) {
2010 NTStatus = 0xC000007FL; /* Disk full */
2012 else if (code == CM_ERROR_BUFFERTOOSMALL) {
2013 NTStatus = 0xC0000023L; /* Buffer too small */
2016 NTStatus = 0xC0982001L; /* SMB non-specific error */
2019 *NTStatusp = NTStatus;
2020 osi_Log2(afsd_logp, "SMB SEND code %x as NT %x", code, NTStatus);
2023 void smb_MapCoreError(long code, smb_vc_t *vcp, unsigned short *scodep,
2024 unsigned char *classp)
2026 unsigned char class;
2027 unsigned short error;
2029 /* map CM_ERROR_* errors to SMB errors */
2030 if (code == CM_ERROR_NOSUCHCELL) {
2032 error = 3; /* bad path */
2034 else if (code == CM_ERROR_NOSUCHVOLUME) {
2036 error = 3; /* bad path */
2038 else if (code == CM_ERROR_TIMEDOUT) {
2040 error = 81; /* server is paused */
2042 else if (code == CM_ERROR_RETRY) {
2043 class = 2; /* shouldn't happen */
2046 else if (code == CM_ERROR_NOACCESS) {
2048 error = 4; /* bad access */
2050 else if (code == CM_ERROR_READONLY) {
2052 error = 19; /* read only */
2054 else if (code == CM_ERROR_NOSUCHFILE) {
2056 error = 2; /* ENOENT! */
2058 else if (code == CM_ERROR_NOSUCHPATH) {
2060 error = 3; /* Bad path */
2062 else if (code == CM_ERROR_TOOBIG) {
2064 error = 11; /* bad format */
2066 else if (code == CM_ERROR_INVAL) {
2067 class = 2; /* server non-specific error code */
2070 else if (code == CM_ERROR_BADFD) {
2072 error = 6; /* invalid file handle */
2074 else if (code == CM_ERROR_BADFDOP) {
2075 class = 1; /* invalid op on FD */
2078 else if (code == CM_ERROR_EXISTS) {
2080 error = 80; /* file already exists */
2082 else if (code == CM_ERROR_NOTEMPTY) {
2084 error = 5; /* delete directory not empty */
2086 else if (code == CM_ERROR_CROSSDEVLINK) {
2088 error = 17; /* EXDEV */
2090 else if (code == CM_ERROR_NOTDIR) {
2091 class = 1; /* bad path */
2094 else if (code == CM_ERROR_ISDIR) {
2095 class = 1; /* access denied; DOS doesn't have a good match */
2098 else if (code == CM_ERROR_BADOP) {
2102 else if (code == CM_ERROR_BADSHARENAME) {
2106 else if (code == CM_ERROR_NOIPC) {
2108 error = 4; /* bad access */
2110 else if (code == CM_ERROR_CLOCKSKEW) {
2111 class = 1; /* invalid function */
2114 else if (code == CM_ERROR_BADTID) {
2118 else if (code == CM_ERROR_USESTD) {
2122 else if (code == CM_ERROR_REMOTECONN) {
2126 else if (code == CM_ERROR_QUOTA) {
2127 if (vcp->flags & SMB_VCFLAG_USEV3) {
2129 error = 39; /* disk full */
2133 error = 5; /* access denied */
2136 else if (code == CM_ERROR_SPACE) {
2137 if (vcp->flags & SMB_VCFLAG_USEV3) {
2139 error = 39; /* disk full */
2143 error = 5; /* access denied */
2146 else if (code == CM_ERROR_PARTIALWRITE) {
2148 error = 39; /* disk full */
2150 else if (code == CM_ERROR_ATSYS) {
2152 error = 2; /* ENOENT */
2154 else if (code == CM_ERROR_WOULDBLOCK) {
2156 error = 33; /* lock conflict */
2158 else if (code == CM_ERROR_NOFILES) {
2160 error = 18; /* no files in search */
2162 else if (code == CM_ERROR_RENAME_IDENTICAL) {
2164 error = 183; /* Samba uses this */
2173 osi_Log3(afsd_logp, "SMB SEND code %x as SMB %d: %d", code, class, error);
2176 long smb_SendCoreBadOp(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2178 return CM_ERROR_BADOP;
2181 long smb_ReceiveCoreEcho(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2183 unsigned short EchoCount, i;
2184 char *data, *outdata;
2187 EchoCount = (unsigned short) smb_GetSMBParm(inp, 0);
2189 for (i=1; i<=EchoCount; i++) {
2190 data = smb_GetSMBData(inp, &dataSize);
2191 smb_SetSMBParm(outp, 0, i);
2192 smb_SetSMBDataLength(outp, dataSize);
2193 outdata = smb_GetSMBData(outp, NULL);
2194 memcpy(outdata, data, dataSize);
2195 smb_SendPacket(vcp, outp);
2201 long smb_ReceiveCoreReadRaw(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2204 long count, minCount, finalCount;
2208 cm_user_t *userp = NULL;
2212 char *rawBuf = NULL;
2214 dos_ptr rawBuf = NULL;
2221 fd = smb_GetSMBParm(inp, 0);
2222 count = smb_GetSMBParm(inp, 3);
2223 minCount = smb_GetSMBParm(inp, 4);
2224 offset.HighPart = 0; /* too bad */
2225 offset.LowPart = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
2227 osi_Log3(afsd_logp, "smb_ReceieveCoreReadRaw fd %d, off 0x%x, size 0x%x",
2228 fd, offset.LowPart, count);
2230 fidp = smb_FindFID(vcp, fd, 0);
2234 lock_ObtainMutex(&smb_RawBufLock);
2236 /* Get a raw buf, from head of list */
2237 rawBuf = smb_RawBufs;
2239 smb_RawBufs = *(char **)smb_RawBufs;
2241 smb_RawBufs = _farpeekl(_dos_ds, smb_RawBufs);
2244 lock_ReleaseMutex(&smb_RawBufLock);
2248 if (fidp->flags & SMB_FID_IOCTL)
2251 rc = smb_IoctlReadRaw(fidp, vcp, inp, outp);
2253 rc = smb_IoctlReadRaw(fidp, vcp, inp, outp, rawBuf);
2256 /* Give back raw buffer */
2257 lock_ObtainMutex(&smb_RawBufLock);
2259 *((char **) rawBuf) = smb_RawBufs;
2261 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
2264 smb_RawBufs = rawBuf;
2265 lock_ReleaseMutex(&smb_RawBufLock);
2268 smb_ReleaseFID(fidp);
2272 userp = smb_GetUser(vcp, inp);
2275 code = smb_ReadData(fidp, &offset, count, rawBuf, userp, &finalCount);
2277 /* have to give ReadData flag so it will treat buffer as DOS mem. */
2278 code = smb_ReadData(fidp, &offset, count, (unsigned char *)rawBuf,
2279 userp, &finalCount, TRUE /* rawFlag */);
2286 cm_ReleaseUser(userp);
2289 smb_ReleaseFID(fidp);
2294 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
2296 memset((char *)ncbp, 0, sizeof(NCB));
2298 ncbp->ncb_length = (unsigned short) finalCount;
2299 ncbp->ncb_lsn = (unsigned char) vcp->lsn;
2300 ncbp->ncb_lana_num = vcp->lana;
2301 ncbp->ncb_command = NCBSEND;
2302 ncbp->ncb_buffer = rawBuf;
2305 code = Netbios(ncbp);
2307 code = Netbios(ncbp, dos_ncb);
2310 osi_Log1(afsd_logp, "ReadRaw send failure code %d", code);
2313 /* Give back raw buffer */
2314 lock_ObtainMutex(&smb_RawBufLock);
2316 *((char **) rawBuf) = smb_RawBufs;
2318 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
2321 smb_RawBufs = rawBuf;
2322 lock_ReleaseMutex(&smb_RawBufLock);
2328 long smb_ReceiveCoreLockRecord(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2333 long smb_ReceiveCoreUnlockRecord(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2338 long smb_ReceiveNegotiate(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2344 int protoIndex; /* index we're using */
2349 char protocol_array[10][1024]; /* protocol signature of the client */
2352 osi_Log1(afsd_logp, "SMB receive negotiate; %d + 1 ongoing ops",
2356 DWORD now = GetCurrentTime();
2357 if (now - last_msg_time >= 30000
2358 && now - last_msg_time <= 90000) {
2360 "Setting dead_vcp %x", active_vcp);
2361 dead_vcp = active_vcp;
2362 dead_vcp->flags |= SMB_VCFLAG_ALREADYDEAD;
2367 inp->flags |= SMB_PACKETFLAG_PROFILE_UPDATE_OK;
2369 namep = smb_GetSMBData(inp, &dbytes);
2372 coreProtoIndex = -1; /* not found */
2375 while(namex < dbytes) {
2376 osi_Log1(afsd_logp, "Protocol %s",
2377 osi_LogSaveString(afsd_logp, namep+1));
2378 strcpy(protocol_array[tcounter], namep+1);
2380 /* namep points at the first protocol, or really, a 0x02
2381 * byte preceding the null-terminated ASCII name.
2383 if (strcmp("PC NETWORK PROGRAM 1.0", namep+1) == 0) {
2384 coreProtoIndex = tcounter;
2386 else if (smb_useV3 && strcmp("LM1.2X002", namep+1) == 0) {
2387 v3ProtoIndex = tcounter;
2389 else if (smb_useV3 && strcmp("NT LM 0.12", namep+1) == 0) {
2390 NTProtoIndex = tcounter;
2393 /* compute size of protocol entry */
2394 entryLength = strlen(namep+1);
2395 entryLength += 2; /* 0x02 bytes and null termination */
2397 /* advance over this protocol entry */
2398 namex += entryLength;
2399 namep += entryLength;
2400 tcounter++; /* which proto entry we're looking at */
2402 #ifndef NOMOREFILESFIX
2404 * NOTE: We can determine what OS (NT4.0, W2K, W9X, etc)
2405 * the client is running by reading the protocol signature.
2406 * ie. the order in which it sends us the protocol list.
2408 * Special handling for Windows 2000 clients (defect 11765 )
2409 * <asanka:11Jun03> Proto signature is the same for Win XP. </>
2411 if (tcounter == 6) {
2413 smb_t *ip = (smb_t *) inp;
2414 smb_t *op = (smb_t *) outp;
2416 if ((strcmp("PC NETWORK PROGRAM 1.0", protocol_array[0]) == 0) &&
2417 (strcmp("LANMAN1.0", protocol_array[1]) == 0) &&
2418 (strcmp("Windows for Workgroups 3.1a", protocol_array[2]) == 0) &&
2419 (strcmp("LM1.2X002", protocol_array[3]) == 0) &&
2420 (strcmp("LANMAN2.1", protocol_array[4]) == 0) &&
2421 (strcmp("NT LM 0.12", protocol_array[5]) == 0)) {
2422 isWindows2000 = TRUE;
2423 osi_Log0(afsd_logp, "Looks like a Windows 2000 client");
2425 * HACK: for now - just negotiate a lower protocol till we
2426 * figure out which flag/flag2 or some other field
2427 * (capabilities maybe?) to set in order for this to work
2428 * correctly with Windows 2000 clients (defect 11765)
2431 /* Things to try (after looking at tcpdump output could be
2432 * setting flags and flags2 to 0x98 and 0xc853 like this
2433 * op->reb = 0x98; op->flg2 = 0xc853;
2434 * osi_Log2(afsd_logp, "Flags:0x%x Flags2:0x%x", ip->reb, ip->flg2);
2438 #endif /* NOMOREFILESFIX */
2440 if (NTProtoIndex != -1) {
2441 protoIndex = NTProtoIndex;
2442 vcp->flags |= (SMB_VCFLAG_USENT | SMB_VCFLAG_USEV3);
2444 else if (v3ProtoIndex != -1) {
2445 protoIndex = v3ProtoIndex;
2446 vcp->flags |= SMB_VCFLAG_USEV3;
2448 else if (coreProtoIndex != -1) {
2449 protoIndex = coreProtoIndex;
2450 vcp->flags |= SMB_VCFLAG_USECORE;
2452 else protoIndex = -1;
2454 if (protoIndex == -1)
2455 return CM_ERROR_INVAL;
2456 else if (NTProtoIndex != -1) {
2457 smb_SetSMBParm(outp, 0, protoIndex);
2458 smb_SetSMBParmByte(outp, 1, 0); /* share level security, no passwd encrypt */
2459 smb_SetSMBParm(outp, 1, smb_maxMpxRequests); /* max multiplexed requests */
2460 smb_SetSMBParm(outp, 2, smb_maxVCPerServer); /* max VCs per consumer/server connection */
2461 smb_SetSMBParmLong(outp, 3, SMB_PACKETSIZE); /* xmit buffer size */
2462 smb_SetSMBParmLong(outp, 5, 65536); /* raw buffer size */
2463 smb_SetSMBParm(outp, 7, 1); /* next 2: session key */
2464 smb_SetSMBParm(outp, 8, 1);
2466 * Tried changing the capabilities to support for W2K - defect 117695
2467 * Maybe something else needs to be changed here?
2471 smb_SetSMBParmLong(outp, 9, 0x43fd);
2473 smb_SetSMBParmLong(outp, 9, 0x251);
2476 * 32-bit error codes *
2480 smb_SetSMBParmLong(outp, 9, 0x251);
2481 smb_SetSMBParmLong(outp, 11, 0);/* XXX server time: do we need? */
2482 smb_SetSMBParmLong(outp, 13, 0);/* XXX server date: do we need? */
2483 smb_SetSMBParm(outp, 15, 0); /* XXX server tzone: do we need? */
2484 smb_SetSMBParmByte(outp, 16, 0);/* Encryption key length */
2485 smb_SetSMBDataLength(outp, 0); /* perhaps should specify 8 bytes anyway */
2487 else if (v3ProtoIndex != -1) {
2488 smb_SetSMBParm(outp, 0, protoIndex);
2489 smb_SetSMBParm(outp, 1, 0); /* share level security, no passwd encrypt */
2490 smb_SetSMBParm(outp, 2, SMB_PACKETSIZE);
2491 smb_SetSMBParm(outp, 3, smb_maxMpxRequests); /* max multiplexed requests */
2492 smb_SetSMBParm(outp, 4, smb_maxVCPerServer); /* max VCs per consumer/server connection */
2493 smb_SetSMBParm(outp, 5, 0); /* no support of block mode for read or write */
2494 smb_SetSMBParm(outp, 6, 1); /* next 2: session key */
2495 smb_SetSMBParm(outp, 7, 1);
2496 smb_SetSMBParm(outp, 8, 0); /* XXX server time: do we need? */
2497 smb_SetSMBParm(outp, 9, 0); /* XXX server date: do we need? */
2498 smb_SetSMBParm(outp, 10, 0); /* XXX server tzone: do we need? */
2499 smb_SetSMBParm(outp, 11, 0); /* resvd */
2500 smb_SetSMBParm(outp, 12, 0); /* resvd */
2501 smb_SetSMBDataLength(outp, 0); /* perhaps should specify 8 bytes anyway */
2503 else if (coreProtoIndex != -1) {
2504 smb_SetSMBParm(outp, 0, protoIndex);
2505 smb_SetSMBDataLength(outp, 0);
2510 void smb_Daemon(void *parmp)
2517 if ((count % 360) == 0) /* every hour */
2518 smb_CalculateNowTZ();
2519 /* XXX GC dir search entries */
2523 void smb_WaitingLocksDaemon()
2525 smb_waitingLock_t *wL, *nwL;
2528 smb_packet_t *inp, *outp;
2533 lock_ObtainWrite(&smb_globalLock);
2534 nwL = smb_allWaitingLocks;
2536 osi_SleepW((long)&smb_allWaitingLocks, &smb_globalLock);
2545 lock_ObtainWrite(&smb_globalLock);
2547 nwL = (smb_waitingLock_t *) osi_QNext(&wL->q);
2548 lock_ReleaseWrite(&smb_globalLock);
2549 code = cm_RetryLock((cm_file_lock_t *) wL->lockp,
2550 wL->vcp->flags & SMB_VCFLAG_ALREADYDEAD);
2551 if (code == CM_ERROR_WOULDBLOCK) {
2553 if (wL->timeRemaining != 0xffffffff
2554 && (wL->timeRemaining -= 1000) < 0)
2563 ncbp->ncb_length = inp->ncb_length;
2564 inp->spacep = cm_GetSpace();
2566 /* Remove waitingLock from list */
2567 lock_ObtainWrite(&smb_globalLock);
2568 osi_QRemove((osi_queue_t **)&smb_allWaitingLocks,
2570 lock_ReleaseWrite(&smb_globalLock);
2572 /* Resume packet processing */
2574 smb_SetSMBDataLength(outp, 0);
2575 outp->flags |= SMB_PACKETFLAG_SUSPENDED;
2576 outp->resumeCode = code;
2578 smb_DispatchPacket(vcp, inp, outp, ncbp, NULL);
2581 cm_FreeSpace(inp->spacep);
2582 smb_FreePacket(inp);
2583 smb_FreePacket(outp);
2591 long smb_ReceiveCoreGetDiskAttributes(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2593 osi_Log0(afsd_logp, "SMB receive get disk attributes");
2595 smb_SetSMBParm(outp, 0, 32000);
2596 smb_SetSMBParm(outp, 1, 64);
2597 smb_SetSMBParm(outp, 2, 1024);
2598 smb_SetSMBParm(outp, 3, 30000);
2599 smb_SetSMBParm(outp, 4, 0);
2600 smb_SetSMBDataLength(outp, 0);
2604 long smb_ReceiveCoreTreeConnect(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *rsp)
2607 unsigned short newTid;
2608 char shareName[256];
2616 osi_Log0(afsd_logp, "SMB receive tree connect");
2618 /* parse input parameters */
2619 tp = smb_GetSMBData(inp, NULL);
2620 pathp = smb_ParseASCIIBlock(tp, &tp);
2621 passwordp = smb_ParseASCIIBlock(tp, &tp);
2622 tp = strrchr(pathp, '\\');
2624 return CM_ERROR_BADSMB;
2625 strcpy(shareName, tp+1);
2627 userp = smb_GetUser(vcp, inp);
2629 lock_ObtainMutex(&vcp->mx);
2630 newTid = vcp->tidCounter++;
2631 lock_ReleaseMutex(&vcp->mx);
2633 tidp = smb_FindTID(vcp, newTid, SMB_FLAG_CREATE);
2634 shareFound = smb_FindShare(vcp, inp, shareName, &sharePath);
2636 smb_ReleaseTID(tidp);
2637 return CM_ERROR_BADSHARENAME;
2639 lock_ObtainMutex(&tidp->mx);
2640 tidp->userp = userp;
2641 tidp->pathname = sharePath;
2642 lock_ReleaseMutex(&tidp->mx);
2643 smb_ReleaseTID(tidp);
2645 smb_SetSMBParm(rsp, 0, SMB_PACKETSIZE);
2646 smb_SetSMBParm(rsp, 1, newTid);
2647 smb_SetSMBDataLength(rsp, 0);
2649 osi_Log1(afsd_logp, "SMB tree connect created ID %d", newTid);
2653 unsigned char *smb_ParseDataBlock(unsigned char *inp, char **chainpp, int *lengthp)
2657 if (*inp++ != 0x1) return NULL;
2658 tlen = inp[0] + (inp[1]<<8);
2659 inp += 2; /* skip length field */
2662 *chainpp = inp + tlen;
2665 if (lengthp) *lengthp = tlen;
2670 /* set maskp to the mask part of the incoming path.
2671 * Mask is 11 bytes long (8.3 with the dot elided).
2672 * Returns true if succeeds with a valid name, otherwise it does
2673 * its best, but returns false.
2675 int smb_Get8Dot3MaskFromPath(unsigned char *maskp, unsigned char *pathp)
2683 /* starts off valid */
2686 /* mask starts out all blanks */
2687 memset(maskp, ' ', 11);
2689 /* find last backslash, or use whole thing if there is none */
2690 tp = strrchr(pathp, '\\');
2691 if (!tp) tp = pathp;
2692 else tp++; /* skip slash */
2696 /* names starting with a dot are illegal */
2697 if (*tp == '.') valid8Dot3 = 0;
2701 if (tc == 0) return valid8Dot3;
2702 if (tc == '.' || tc == '"') break;
2703 if (i < 8) *up++ = tc;
2704 else valid8Dot3 = 0;
2707 /* if we get here, tp point after the dot */
2708 up = maskp+8; /* ext goes here */
2715 if (tc == '.' || tc == '"')
2718 /* copy extension if not too long */
2728 int smb_Match8Dot3Mask(char *unixNamep, char *maskp)
2738 /* XXX redo this, calling smb_V3MatchMask with a converted mask */
2740 valid = smb_Get8Dot3MaskFromPath(umask, unixNamep);
2744 /* otherwise, we have a valid 8.3 name; see if we have a match,
2745 * treating '?' as a wildcard in maskp (but not in the file name).
2747 tp1 = umask; /* real name, in mask format */
2748 tp2 = maskp; /* mask, in mask format */
2749 for(i=0; i<11; i++) {
2750 tc1 = *tp1++; /* char from real name */
2751 tc2 = *tp2++; /* char from mask */
2752 tc1 = (char) cm_foldUpper[(unsigned char)tc1];
2753 tc2 = (char) cm_foldUpper[(unsigned char)tc2];
2756 if (tc2 == '?' && tc1 != ' ')
2763 /* we got a match */
2767 char *smb_FindMask(char *pathp)
2771 tp = strrchr(pathp, '\\'); /* find last slash */
2774 return tp+1; /* skip the slash */
2776 return pathp; /* no slash, return the entire path */
2779 long smb_ReceiveCoreSearchVolume(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2781 unsigned char *pathp;
2783 unsigned char mask[11];
2784 unsigned char *statBlockp;
2785 unsigned char initStatBlock[21];
2788 osi_Log0(afsd_logp, "SMB receive search volume");
2790 /* pull pathname and stat block out of request */
2791 tp = smb_GetSMBData(inp, NULL);
2792 pathp = smb_ParseASCIIBlock(tp, (char **) &tp);
2793 osi_assert(pathp != NULL);
2794 statBlockp = smb_ParseVblBlock(tp, (char **) &tp, &statLen);
2795 osi_assert(statBlockp != NULL);
2797 statBlockp = initStatBlock;
2801 /* for returning to caller */
2802 smb_Get8Dot3MaskFromPath(mask, pathp);
2804 smb_SetSMBParm(outp, 0, 1); /* we're returning one entry */
2805 tp = smb_GetSMBData(outp, NULL);
2807 *tp++ = 43; /* bytes in a dir entry */
2808 *tp++ = 0; /* high byte in counter */
2810 /* now marshall the dir entry, starting with the search status */
2811 *tp++ = statBlockp[0]; /* Reserved */
2812 memcpy(tp, mask, 11); tp += 11; /* FileName */
2814 /* now pass back server use info, with 1st byte non-zero */
2816 memset(tp, 0, 4); tp += 4; /* reserved for server use */
2818 memcpy(tp, statBlockp+17, 4); tp += 4; /* reserved for consumer */
2820 *tp++ = 0x8; /* attribute: volume */
2830 /* 4 byte file size */
2836 /* finally, null-terminated 8.3 pathname, which we set to AFS */
2837 memset(tp, ' ', 13);
2840 /* set the length of the data part of the packet to 43 + 3, for the dir
2841 * entry plus the 5 and the length fields.
2843 smb_SetSMBDataLength(outp, 46);
2847 long smb_ApplyDirListPatches(smb_dirListPatch_t **dirPatchespp,
2848 cm_user_t *userp, cm_req_t *reqp)
2856 smb_dirListPatch_t *patchp;
2857 smb_dirListPatch_t *npatchp;
2859 for(patchp = *dirPatchespp; patchp; patchp =
2860 (smb_dirListPatch_t *) osi_QNext(&patchp->q)) {
2861 code = cm_GetSCache(&patchp->fid, &scp, userp, reqp);
2863 lock_ObtainMutex(&scp->mx);
2864 code = cm_SyncOp(scp, NULL, userp, reqp, 0,
2865 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2867 lock_ReleaseMutex(&scp->mx);
2868 cm_ReleaseSCache(scp);
2871 dptr = patchp->dptr;
2873 attr = smb_Attributes(scp);
2874 /* check hidden attribute (the flag is only ON when dot file hiding is on ) */
2875 if( patchp->flags & SMB_DIRLISTPATCH_DOTFILE )
2876 attr |= SMB_ATTR_HIDDEN;
2880 smb_SearchTimeFromUnixTime(&dosTime, scp->clientModTime);
2883 shortTemp = dosTime & 0xffff;
2884 *((u_short *)dptr) = shortTemp;
2887 /* and copy out date */
2888 shortTemp = (dosTime>>16) & 0xffff;
2889 *((u_short *)dptr) = shortTemp;
2892 /* copy out file length */
2893 *((u_long *)dptr) = scp->length.LowPart;
2895 lock_ReleaseMutex(&scp->mx);
2896 cm_ReleaseSCache(scp);
2899 /* now free the patches */
2900 for(patchp = *dirPatchespp; patchp; patchp = npatchp) {
2901 npatchp = (smb_dirListPatch_t *) osi_QNext(&patchp->q);
2905 /* and mark the list as empty */
2906 *dirPatchespp = NULL;
2911 long smb_ReceiveCoreSearchDir(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2920 smb_dirListPatch_t *dirListPatchesp;
2921 smb_dirListPatch_t *curPatchp;
2925 osi_hyper_t dirLength;
2926 osi_hyper_t bufferOffset;
2927 osi_hyper_t curOffset;
2929 unsigned char *inCookiep;
2930 smb_dirSearch_t *dsp;
2934 unsigned long clientCookie;
2935 cm_pageHeader_t *pageHeaderp;
2936 cm_user_t *userp = NULL;
2943 long nextEntryCookie;
2944 int numDirChunks; /* # of 32 byte dir chunks in this entry */
2945 char resByte; /* reserved byte from the cookie */
2946 char *op; /* output data ptr */
2947 char *origOp; /* original value of op */
2948 cm_space_t *spacep; /* for pathname buffer */
2959 maxCount = smb_GetSMBParm(inp, 0);
2961 dirListPatchesp = NULL;
2963 caseFold = CM_FLAG_CASEFOLD;
2965 tp = smb_GetSMBData(inp, NULL);
2966 pathp = smb_ParseASCIIBlock(tp, &tp);
2967 inCookiep = smb_ParseVblBlock(tp, &tp, &dataLength);
2969 /* bail out if request looks bad */
2970 if (!tp || !pathp) {
2971 return CM_ERROR_BADSMB;
2974 /* We can handle long names */
2975 if (vcp->flags & SMB_VCFLAG_USENT)
2976 ((smb_t *)outp)->flg2 |= 0x40; /* IS_LONG_NAME */
2978 /* make sure we got a whole search status */
2979 if (dataLength < 21) {
2980 nextCookie = 0; /* start at the beginning of the dir */
2983 attribute = smb_GetSMBParm(inp, 1);
2985 /* handle volume info in another function */
2986 if (attribute & 0x8)
2987 return smb_ReceiveCoreSearchVolume(vcp, inp, outp);
2989 osi_Log2(afsd_logp, "SMB receive search dir count %d [%s]",
2990 maxCount, osi_LogSaveString(afsd_logp, pathp));
2992 if (*pathp == 0) { /* null pathp, treat as root dir */
2993 if (!(attribute & SMB_ATTR_DIRECTORY)) /* exclude dirs */
2994 return CM_ERROR_NOFILES;
2998 dsp = smb_NewDirSearch(0);
2999 dsp->attribute = attribute;
3000 smb_Get8Dot3MaskFromPath(mask, pathp);
3001 memcpy(dsp->mask, mask, 11);
3003 /* track if this is likely to match a lot of entries */
3004 if (smb_IsStarMask(mask)) starPattern = 1;
3005 else starPattern = 0;
3008 /* pull the next cookie value out of the search status block */
3009 nextCookie = inCookiep[13] + (inCookiep[14]<<8) + (inCookiep[15]<<16)
3010 + (inCookiep[16]<<24);
3011 dsp = smb_FindDirSearch(inCookiep[12]);
3013 /* can't find dir search status; fatal error */
3014 return CM_ERROR_BADFD;
3016 attribute = dsp->attribute;
3017 resByte = inCookiep[0];
3019 /* copy out client cookie, in host byte order. Don't bother
3020 * interpreting it, since we're just passing it through, anyway.
3022 memcpy(&clientCookie, &inCookiep[17], 4);
3024 memcpy(mask, dsp->mask, 11);
3026 /* assume we're doing a star match if it has continued for more
3032 osi_Log3(afsd_logp, "SMB dir search cookie 0x%x, connection %d, attr 0x%x",
3033 nextCookie, dsp->cookie, attribute);
3035 userp = smb_GetUser(vcp, inp);
3037 /* try to get the vnode for the path name next */
3038 lock_ObtainMutex(&dsp->mx);
3045 spacep = inp->spacep;
3046 smb_StripLastComponent(spacep->data, NULL, pathp);
3047 lock_ReleaseMutex(&dsp->mx);
3048 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3049 code = cm_NameI(cm_rootSCachep, spacep->data,
3050 caseFold | CM_FLAG_FOLLOW, userp, tidPathp, &req, &scp);
3051 lock_ObtainMutex(&dsp->mx);
3053 if (dsp->scp != 0) cm_ReleaseSCache(dsp->scp);
3055 /* we need one hold for the entry we just stored into,
3056 * and one for our own processing. When we're done with this
3057 * function, we'll drop the one for our own processing.
3058 * We held it once from the namei call, and so we do another hold
3062 lock_ObtainMutex(&scp->mx);
3063 if ((scp->flags & CM_SCACHEFLAG_BULKSTATTING) == 0
3064 && LargeIntegerGreaterOrEqualToZero(scp->bulkStatProgress)) {
3065 scp->flags |= CM_SCACHEFLAG_BULKSTATTING;
3066 dsp->flags |= SMB_DIRSEARCH_BULKST;
3068 lock_ReleaseMutex(&scp->mx);
3071 lock_ReleaseMutex(&dsp->mx);
3073 cm_ReleaseUser(userp);
3074 smb_DeleteDirSearch(dsp);
3075 smb_ReleaseDirSearch(dsp);
3079 /* reserves space for parameter; we'll adjust it again later to the
3080 * real count of the # of entries we returned once we've actually
3081 * assembled the directory listing.
3083 smb_SetSMBParm(outp, 0, 0);
3085 /* get the directory size */
3086 lock_ObtainMutex(&scp->mx);
3087 code = cm_SyncOp(scp, NULL, userp, &req, 0,
3088 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3090 lock_ReleaseMutex(&scp->mx);
3091 cm_ReleaseSCache(scp);
3092 cm_ReleaseUser(userp);
3093 smb_DeleteDirSearch(dsp);
3094 smb_ReleaseDirSearch(dsp);
3098 dirLength = scp->length;
3100 bufferOffset.LowPart = bufferOffset.HighPart = 0;
3101 curOffset.HighPart = 0;
3102 curOffset.LowPart = nextCookie;
3103 origOp = op = smb_GetSMBData(outp, NULL);
3104 /* and write out the basic header */
3105 *op++ = 5; /* variable block */
3106 op += 2; /* skip vbl block length; we'll fill it in later */
3110 /* make sure that curOffset.LowPart doesn't point to the first
3111 * 32 bytes in the 2nd through last dir page, and that it doesn't
3112 * point at the first 13 32-byte chunks in the first dir page,
3113 * since those are dir and page headers, and don't contain useful
3116 temp = curOffset.LowPart & (2048-1);
3117 if (curOffset.HighPart == 0 && curOffset.LowPart < 2048) {
3118 /* we're in the first page */
3119 if (temp < 13*32) temp = 13*32;
3122 /* we're in a later dir page */
3123 if (temp < 32) temp = 32;
3126 /* make sure the low order 5 bits are zero */
3129 /* now put temp bits back ito curOffset.LowPart */
3130 curOffset.LowPart &= ~(2048-1);
3131 curOffset.LowPart |= temp;
3133 /* check if we've returned all the names that will fit in the
3136 if (returnedNames >= maxCount)
3139 /* check if we've passed the dir's EOF */
3140 if (LargeIntegerGreaterThanOrEqualTo(curOffset, dirLength)) break;
3142 /* see if we can use the bufferp we have now; compute in which page
3143 * the current offset would be, and check whether that's the offset
3144 * of the buffer we have. If not, get the buffer.
3146 thyper.HighPart = curOffset.HighPart;
3147 thyper.LowPart = curOffset.LowPart & ~(buf_bufferSize-1);
3148 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
3151 buf_Release(bufferp);
3154 lock_ReleaseMutex(&scp->mx);
3155 lock_ObtainRead(&scp->bufCreateLock);
3156 code = buf_Get(scp, &thyper, &bufferp);
3157 lock_ReleaseRead(&scp->bufCreateLock);
3159 /* now, if we're doing a star match, do bulk fetching of all of
3160 * the status info for files in the dir.
3163 smb_ApplyDirListPatches(&dirListPatchesp, userp,
3165 if ((dsp->flags & SMB_DIRSEARCH_BULKST)
3166 && LargeIntegerGreaterThanOrEqualTo(thyper,
3167 scp->bulkStatProgress)) {
3168 /* Don't bulk stat if risking timeout */
3169 int now = GetCurrentTime();
3170 if (now - req.startTime > 5000) {
3171 scp->bulkStatProgress = thyper;
3172 scp->flags &= ~CM_SCACHEFLAG_BULKSTATTING;
3173 dsp->flags &= ~SMB_DIRSEARCH_BULKST;
3175 cm_TryBulkStat(scp, &thyper, userp, &req);
3179 lock_ObtainMutex(&scp->mx);
3182 bufferOffset = thyper;
3184 /* now get the data in the cache */
3186 code = cm_SyncOp(scp, bufferp, userp, &req,
3188 CM_SCACHESYNC_NEEDCALLBACK
3189 | CM_SCACHESYNC_READ);
3192 if (cm_HaveBuffer(scp, bufferp, 0)) break;
3194 /* otherwise, load the buffer and try again */
3195 code = cm_GetBuffer(scp, bufferp, NULL, userp,
3200 buf_Release(bufferp);
3204 } /* if (wrong buffer) ... */
3206 /* now we have the buffer containing the entry we're interested in; copy
3207 * it out if it represents a non-deleted entry.
3209 entryInDir = curOffset.LowPart & (2048-1);
3210 entryInBuffer = curOffset.LowPart & (buf_bufferSize - 1);
3212 /* page header will help tell us which entries are free. Page header
3213 * can change more often than once per buffer, since AFS 3 dir page size
3214 * may be less than (but not more than a buffer package buffer.
3216 temp = curOffset.LowPart & (buf_bufferSize - 1); /* only look intra-buffer */
3217 temp &= ~(2048 - 1); /* turn off intra-page bits */
3218 pageHeaderp = (cm_pageHeader_t *) (bufferp->datap + temp);
3220 /* now determine which entry we're looking at in the page. If it is
3221 * free (there's a free bitmap at the start of the dir), we should
3222 * skip these 32 bytes.
3224 slotInPage = (entryInDir & 0x7e0) >> 5;
3225 if (!(pageHeaderp->freeBitmap[slotInPage>>3] & (1 << (slotInPage & 0x7)))) {
3226 /* this entry is free */
3227 numDirChunks = 1; /* only skip this guy */
3231 tp = bufferp->datap + entryInBuffer;
3232 dep = (cm_dirEntry_t *) tp; /* now points to AFS3 dir entry */
3234 /* while we're here, compute the next entry's location, too,
3235 * since we'll need it when writing out the cookie into the dir
3238 * XXXX Probably should do more sanity checking.
3240 numDirChunks = cm_NameEntries(dep->name, NULL);
3242 /* compute the offset of the cookie representing the next entry */
3243 nextEntryCookie = curOffset.LowPart + (CM_DIR_CHUNKSIZE * numDirChunks);
3245 /* Compute 8.3 name if necessary */
3246 actualName = dep->name;
3247 if (dep->fid.vnode != 0 && !cm_Is8Dot3(actualName)) {
3248 cm_Gen8Dot3Name(dep, shortName, &shortNameEnd);
3249 actualName = shortName;
3252 if (dep->fid.vnode != 0 && smb_Match8Dot3Mask(actualName, mask)) {
3253 /* this is one of the entries to use: it is not deleted
3254 * and it matches the star pattern we're looking for.
3257 /* Eliminate entries that don't match requested
3260 /* no hidden files */
3261 if(smb_hideDotFiles && !(dsp->attribute & SMB_ATTR_HIDDEN) && smb_IsDotFile(actualName))
3264 if (!(dsp->attribute & SMB_ATTR_DIRECTORY)) /* no directories */
3266 /* We have already done the cm_TryBulkStat above */
3267 fid.cell = scp->fid.cell;
3268 fid.volume = scp->fid.volume;
3269 fid.vnode = ntohl(dep->fid.vnode);
3270 fid.unique = ntohl(dep->fid.unique);
3271 fileType = cm_FindFileType(&fid);
3272 osi_Log2(afsd_logp, "smb_ReceiveCoreSearchDir: file %s "
3273 "has filetype %d", dep->name,
3275 if (fileType == CM_SCACHETYPE_DIRECTORY)
3280 memcpy(op, mask, 11); op += 11;
3281 *op++ = (char) dsp->cookie; /* they say it must be non-zero */
3282 *op++ = nextEntryCookie & 0xff;
3283 *op++ = (nextEntryCookie>>8) & 0xff;
3284 *op++ = (nextEntryCookie>>16) & 0xff;
3285 *op++ = (nextEntryCookie>>24) & 0xff;
3286 memcpy(op, &clientCookie, 4); op += 4;
3288 /* now we emit the attribute. This is sort of tricky,
3289 * since we need to really stat the file to find out
3290 * what type of entry we've got. Right now, we're
3291 * copying out data from a buffer, while holding the
3292 * scp locked, so it isn't really convenient to stat
3293 * something now. We'll put in a place holder now,
3294 * and make a second pass before returning this to get
3295 * the real attributes. So, we just skip the data for
3296 * now, and adjust it later. We allocate a patch
3297 * record to make it easy to find this point later.
3298 * The replay will happen at a time when it is safe to
3299 * unlock the directory.
3301 curPatchp = malloc(sizeof(*curPatchp));
3302 osi_QAdd((osi_queue_t **) &dirListPatchesp, &curPatchp->q);
3303 curPatchp->dptr = op;
3304 curPatchp->fid.cell = scp->fid.cell;
3305 curPatchp->fid.volume = scp->fid.volume;
3306 curPatchp->fid.vnode = ntohl(dep->fid.vnode);
3307 curPatchp->fid.unique = ntohl(dep->fid.unique);
3309 /* do hidden attribute here since name won't be around when applying
3313 if ( smb_hideDotFiles && smb_IsDotFile(actualName) )
3314 curPatchp->flags = SMB_DIRLISTPATCH_DOTFILE;
3316 curPatchp->flags = 0;
3318 op += 9; /* skip attr, time, date and size */
3320 /* zero out name area. The spec says to pad with
3321 * spaces, but Samba doesn't, and neither do we.
3325 /* finally, we get to copy out the name; we know that
3326 * it fits in 8.3 or the pattern wouldn't match, but it
3327 * never hurts to be sure.
3329 strncpy(op, actualName, 13);
3331 /* Uppercase if requested by client */
3332 if ((((smb_t *)inp)->flg2 & 1) == 0)
3337 /* now, adjust the # of entries copied */
3339 } /* if we're including this name */
3342 /* and adjust curOffset to be where the new cookie is */
3343 thyper.HighPart = 0;
3344 thyper.LowPart = CM_DIR_CHUNKSIZE * numDirChunks;
3345 curOffset = LargeIntegerAdd(thyper, curOffset);
3346 } /* while copying data for dir listing */
3348 /* release the mutex */
3349 lock_ReleaseMutex(&scp->mx);
3350 if (bufferp) buf_Release(bufferp);
3352 /* apply and free last set of patches; if not doing a star match, this
3353 * will be empty, but better safe (and freeing everything) than sorry.
3355 smb_ApplyDirListPatches(&dirListPatchesp, userp, &req);
3357 /* special return code for unsuccessful search */
3358 if (code == 0 && dataLength < 21 && returnedNames == 0)
3359 code = CM_ERROR_NOFILES;
3361 osi_Log2(afsd_logp, "SMB search dir done, %d names, code %d",
3362 returnedNames, code);
3365 smb_DeleteDirSearch(dsp);
3366 smb_ReleaseDirSearch(dsp);
3367 cm_ReleaseSCache(scp);
3368 cm_ReleaseUser(userp);
3372 /* finalize the output buffer */
3373 smb_SetSMBParm(outp, 0, returnedNames);
3374 temp = (long) (op - origOp);
3375 smb_SetSMBDataLength(outp, temp);
3377 /* the data area is a variable block, which has a 5 (already there)
3378 * followed by the length of the # of data bytes. We now know this to
3379 * be "temp," although that includes the 3 bytes of vbl block header.
3380 * Deduct for them and fill in the length field.
3382 temp -= 3; /* deduct vbl block info */
3383 osi_assert(temp == (43 * returnedNames));
3384 origOp[1] = temp & 0xff;
3385 origOp[2] = (temp>>8) & 0xff;
3386 if (returnedNames == 0) smb_DeleteDirSearch(dsp);
3387 smb_ReleaseDirSearch(dsp);
3388 cm_ReleaseSCache(scp);
3389 cm_ReleaseUser(userp);
3393 /* verify that this is a valid path to a directory. I don't know why they
3394 * don't use the get file attributes call.
3396 long smb_ReceiveCoreCheckPath(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3400 cm_scache_t *rootScp;
3401 cm_scache_t *newScp;
3410 pathp = smb_GetSMBData(inp, NULL);
3411 pathp = smb_ParseASCIIBlock(pathp, NULL);
3412 osi_Log1(afsd_logp, "SMB receive check path %s",
3413 osi_LogSaveString(afsd_logp, pathp));
3416 return CM_ERROR_BADFD;
3419 rootScp = cm_rootSCachep;
3421 userp = smb_GetUser(vcp, inp);
3423 caseFold = CM_FLAG_CASEFOLD;
3425 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3426 code = cm_NameI(rootScp, pathp,
3427 caseFold | CM_FLAG_FOLLOW | CM_FLAG_CHECKPATH,
3428 userp, tidPathp, &req, &newScp);
3431 cm_ReleaseUser(userp);
3435 /* now lock the vnode with a callback; returns with newScp locked */
3436 lock_ObtainMutex(&newScp->mx);
3437 code = cm_SyncOp(newScp, NULL, userp, &req, PRSFS_LOOKUP,
3438 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
3439 if (code && code != CM_ERROR_NOACCESS) {
3440 lock_ReleaseMutex(&newScp->mx);
3441 cm_ReleaseSCache(newScp);
3442 cm_ReleaseUser(userp);
3446 attrs = smb_Attributes(newScp);
3448 if (!(attrs & 0x10))
3449 code = CM_ERROR_NOTDIR;
3451 lock_ReleaseMutex(&newScp->mx);
3453 cm_ReleaseSCache(newScp);
3454 cm_ReleaseUser(userp);
3458 long smb_ReceiveCoreSetFileAttributes(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3462 cm_scache_t *rootScp;
3463 unsigned short attribute;
3465 cm_scache_t *newScp;
3474 /* decode basic attributes we're passed */
3475 attribute = smb_GetSMBParm(inp, 0);
3476 dosTime = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
3478 pathp = smb_GetSMBData(inp, NULL);
3479 pathp = smb_ParseASCIIBlock(pathp, NULL);
3482 return CM_ERROR_BADSMB;
3485 osi_Log2(afsd_logp, "SMB receive setfile attributes time %d, attr 0x%x",
3486 dosTime, attribute);
3488 rootScp = cm_rootSCachep;
3490 userp = smb_GetUser(vcp, inp);
3492 caseFold = CM_FLAG_CASEFOLD;
3494 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3495 code = cm_NameI(rootScp, pathp, caseFold | CM_FLAG_FOLLOW, userp,
3496 tidPathp, &req, &newScp);
3499 cm_ReleaseUser(userp);
3503 /* now lock the vnode with a callback; returns with newScp locked; we
3504 * need the current status to determine what the new status is, in some
3507 lock_ObtainMutex(&newScp->mx);
3508 code = cm_SyncOp(newScp, NULL, userp, &req, 0,
3509 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
3511 lock_ReleaseMutex(&newScp->mx);
3512 cm_ReleaseSCache(newScp);
3513 cm_ReleaseUser(userp);
3517 /* Check for RO volume */
3518 if (newScp->flags & CM_SCACHEFLAG_RO) {
3519 lock_ReleaseMutex(&newScp->mx);
3520 cm_ReleaseSCache(newScp);
3521 cm_ReleaseUser(userp);
3522 return CM_ERROR_READONLY;
3525 /* prepare for setattr call */
3528 attr.mask |= CM_ATTRMASK_CLIENTMODTIME;
3529 smb_UnixTimeFromDosUTime(&attr.clientModTime, dosTime);
3531 if ((newScp->unixModeBits & 0222) && (attribute & 1) != 0) {
3532 /* we're told to make a writable file read-only */
3533 attr.unixModeBits = newScp->unixModeBits & ~0222;
3534 attr.mask |= CM_ATTRMASK_UNIXMODEBITS;
3536 else if ((newScp->unixModeBits & 0222) == 0 && (attribute & 1) == 0) {
3537 /* we're told to make a read-only file writable */
3538 attr.unixModeBits = newScp->unixModeBits | 0222;
3539 attr.mask |= CM_ATTRMASK_UNIXMODEBITS;
3541 lock_ReleaseMutex(&newScp->mx);
3543 /* now call setattr */
3545 code = cm_SetAttr(newScp, &attr, userp, &req);
3549 cm_ReleaseSCache(newScp);
3550 cm_ReleaseUser(userp);
3555 long smb_ReceiveCoreGetFileAttributes(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3559 cm_scache_t *rootScp;
3560 cm_scache_t *newScp, *dscp;
3572 pathp = smb_GetSMBData(inp, NULL);
3573 pathp = smb_ParseASCIIBlock(pathp, NULL);
3576 return CM_ERROR_BADSMB;
3579 if (*pathp == 0) /* null path */
3582 osi_Log1(afsd_logp, "SMB receive getfile attributes path %s",
3583 osi_LogSaveString(afsd_logp, pathp));
3585 rootScp = cm_rootSCachep;
3587 userp = smb_GetUser(vcp, inp);
3589 /* we shouldn't need this for V3 requests, but we seem to */
3590 caseFold = CM_FLAG_CASEFOLD;
3592 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3595 * XXX Strange hack XXX
3597 * As of Patch 5 (16 July 97), we are having the following problem:
3598 * In NT Explorer 4.0, whenever we click on a directory, AFS gets
3599 * requests to look up "desktop.ini" in all the subdirectories.
3600 * This can cause zillions of timeouts looking up non-existent cells
3601 * and volumes, especially in the top-level directory.
3603 * We have not found any way to avoid this or work around it except
3604 * to explicitly ignore the requests for mount points that haven't
3605 * yet been evaluated and for directories that haven't yet been
3608 * We should modify this hack to provide a fake desktop.ini file
3609 * http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/custom.asp
3611 spacep = inp->spacep;
3612 smb_StripLastComponent(spacep->data, &lastComp, pathp);
3613 if (lastComp && stricmp(lastComp, "\\desktop.ini") == 0) {
3614 code = cm_NameI(rootScp, spacep->data,
3615 caseFold | CM_FLAG_DIRSEARCH | CM_FLAG_FOLLOW,
3616 userp, tidPathp, &req, &dscp);
3618 if (dscp->fileType == CM_SCACHETYPE_MOUNTPOINT
3619 && !dscp->mountRootFidp)
3620 code = CM_ERROR_NOSUCHFILE;
3621 else if (dscp->fileType == CM_SCACHETYPE_DIRECTORY) {
3622 cm_buf_t *bp = buf_Find(dscp, &hzero);
3626 code = CM_ERROR_NOSUCHFILE;
3628 cm_ReleaseSCache(dscp);
3630 cm_ReleaseUser(userp);
3636 code = cm_NameI(rootScp, pathp, caseFold | CM_FLAG_FOLLOW, userp,
3637 tidPathp, &req, &newScp);
3640 cm_ReleaseUser(userp);
3644 /* now lock the vnode with a callback; returns with newScp locked */
3645 lock_ObtainMutex(&newScp->mx);
3646 code = cm_SyncOp(newScp, NULL, userp, &req, 0,
3647 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
3649 lock_ReleaseMutex(&newScp->mx);
3650 cm_ReleaseSCache(newScp);
3651 cm_ReleaseUser(userp);
3656 /* use smb_Attributes instead. Also the fact that a file is
3657 * in a readonly volume doesn't mean it shojuld be marked as RO
3659 if (newScp->fileType == CM_SCACHETYPE_DIRECTORY
3660 || newScp->fileType == CM_SCACHETYPE_MOUNTPOINT)
3661 attrs = SMB_ATTR_DIRECTORY;
3664 if ((newScp->unixModeBits & 0222) == 0 || (newScp->flags & CM_SCACHEFLAG_RO))
3665 attrs |= SMB_ATTR_READONLY; /* turn on read-only flag */
3667 attrs = smb_Attributes(newScp);
3670 smb_SetSMBParm(outp, 0, attrs);
3672 smb_DosUTimeFromUnixTime(&dosTime, newScp->clientModTime);
3673 smb_SetSMBParm(outp, 1, dosTime & 0xffff);
3674 smb_SetSMBParm(outp, 2, (dosTime>>16) & 0xffff);
3675 smb_SetSMBParm(outp, 3, newScp->length.LowPart & 0xffff);
3676 smb_SetSMBParm(outp, 4, (newScp->length.LowPart >> 16) & 0xffff);
3677 smb_SetSMBParm(outp, 5, 0);
3678 smb_SetSMBParm(outp, 6, 0);
3679 smb_SetSMBParm(outp, 7, 0);
3680 smb_SetSMBParm(outp, 8, 0);
3681 smb_SetSMBParm(outp, 9, 0);
3682 smb_SetSMBDataLength(outp, 0);
3683 lock_ReleaseMutex(&newScp->mx);
3685 cm_ReleaseSCache(newScp);
3686 cm_ReleaseUser(userp);
3691 long smb_ReceiveCoreTreeDisconnect(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3695 osi_Log0(afsd_logp, "SMB receive tree disconnect");
3697 /* find the tree and free it */
3698 tidp = smb_FindTID(vcp, ((smb_t *)inp)->tid, 0);
3700 lock_ObtainMutex(&tidp->mx);
3701 tidp->flags |= SMB_TIDFLAG_DELETE;
3702 lock_ReleaseMutex(&tidp->mx);
3703 smb_ReleaseTID(tidp);
3709 long smb_ReceiveCoreOpen(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3727 pathp = smb_GetSMBData(inp, NULL);
3728 pathp = smb_ParseASCIIBlock(pathp, NULL);
3730 osi_Log1(afsd_logp, "SMB receive open file [%s]", osi_LogSaveString(afsd_logp, pathp));
3732 #ifdef DEBUG_VERBOSE
3736 hexpath = osi_HexifyString( pathp );
3737 DEBUG_EVENT2("AFS", "CoreOpen H[%s] A[%s]", hexpath, pathp);
3742 share = smb_GetSMBParm(inp, 0);
3743 attribute = smb_GetSMBParm(inp, 1);
3745 spacep = inp->spacep;
3746 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
3747 if (lastNamep && strcmp(lastNamep, SMB_IOCTL_FILENAME) == 0) {
3748 /* special case magic file name for receiving IOCTL requests
3749 * (since IOCTL calls themselves aren't getting through).
3751 fidp = smb_FindFID(vcp, 0, SMB_FLAG_CREATE);
3752 smb_SetupIoctlFid(fidp, spacep);
3753 smb_SetSMBParm(outp, 0, fidp->fid);
3754 smb_SetSMBParm(outp, 1, 0); /* attrs */
3755 smb_SetSMBParm(outp, 2, 0); /* next 2 are DOS time */
3756 smb_SetSMBParm(outp, 3, 0);
3757 smb_SetSMBParm(outp, 4, 0); /* next 2 are length */
3758 smb_SetSMBParm(outp, 5, 0x7fff);
3759 /* pass the open mode back */
3760 smb_SetSMBParm(outp, 6, (share & 0xf));
3761 smb_SetSMBDataLength(outp, 0);
3762 smb_ReleaseFID(fidp);
3766 userp = smb_GetUser(vcp, inp);
3768 caseFold = CM_FLAG_CASEFOLD;
3770 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3771 code = cm_NameI(cm_rootSCachep, pathp, caseFold | CM_FLAG_FOLLOW, userp,
3772 tidPathp, &req, &scp);
3775 cm_ReleaseUser(userp);
3779 code = cm_CheckOpen(scp, share & 0x7, 0, userp, &req);
3781 cm_ReleaseSCache(scp);
3782 cm_ReleaseUser(userp);
3786 /* don't need callback to check file type, since file types never
3787 * change, and namei and cm_Lookup all stat the object at least once on
3788 * a successful return.
3790 if (scp->fileType != CM_SCACHETYPE_FILE) {
3791 cm_ReleaseSCache(scp);
3792 cm_ReleaseUser(userp);
3793 return CM_ERROR_ISDIR;
3796 fidp = smb_FindFID(vcp, 0, SMB_FLAG_CREATE);
3799 /* save a pointer to the vnode */
3802 if ((share & 0xf) == 0)
3803 fidp->flags |= SMB_FID_OPENREAD;
3804 else if ((share & 0xf) == 1)
3805 fidp->flags |= SMB_FID_OPENWRITE;
3807 fidp->flags |= (SMB_FID_OPENREAD | SMB_FID_OPENWRITE);
3809 lock_ObtainMutex(&scp->mx);
3810 smb_SetSMBParm(outp, 0, fidp->fid);
3811 smb_SetSMBParm(outp, 1, smb_Attributes(scp));
3812 smb_DosUTimeFromUnixTime(&dosTime, scp->clientModTime);
3813 smb_SetSMBParm(outp, 2, dosTime & 0xffff);
3814 smb_SetSMBParm(outp, 3, (dosTime >> 16) & 0xffff);
3815 smb_SetSMBParm(outp, 4, scp->length.LowPart & 0xffff);
3816 smb_SetSMBParm(outp, 5, (scp->length.LowPart >> 16) & 0xffff);
3817 /* pass the open mode back; XXXX add access checks */
3818 smb_SetSMBParm(outp, 6, (share & 0xf));
3819 smb_SetSMBDataLength(outp, 0);
3820 lock_ReleaseMutex(&scp->mx);
3823 cm_Open(scp, 0, userp);
3825 /* send and free packet */
3826 smb_ReleaseFID(fidp);
3827 cm_ReleaseUser(userp);
3828 /* don't release scp, since we've squirreled away the pointer in the fid struct */
3832 typedef struct smb_unlinkRock {
3837 char *maskp; /* pointer to the star pattern */
3842 int smb_UnlinkProc(cm_scache_t *dscp, cm_dirEntry_t *dep, void *vrockp, osi_hyper_t *offp)
3845 smb_unlinkRock_t *rockp;
3853 if (rockp->vcp->flags & SMB_VCFLAG_USEV3)
3854 caseFold = CM_FLAG_CASEFOLD;
3856 caseFold = CM_FLAG_CASEFOLD | CM_FLAG_8DOT3;
3858 matchName = dep->name;
3859 match = smb_V3MatchMask(matchName, rockp->maskp, caseFold);
3862 && !cm_Is8Dot3(dep->name)) {
3863 cm_Gen8Dot3Name(dep, shortName, NULL);
3864 matchName = shortName;
3865 match = smb_V3MatchMask(matchName, rockp->maskp, caseFold);
3868 osi_Log1(smb_logp, "Unlinking %s",
3869 osi_LogSaveString(smb_logp, matchName));
3870 code = cm_Unlink(dscp, dep->name, rockp->userp, rockp->reqp);
3871 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
3872 smb_NotifyChange(FILE_ACTION_REMOVED,
3873 FILE_NOTIFY_CHANGE_FILE_NAME,
3874 dscp, dep->name, NULL, TRUE);
3883 long smb_ReceiveCoreUnlink(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3892 smb_unlinkRock_t rock;
3901 attribute = smb_GetSMBParm(inp, 0);
3903 tp = smb_GetSMBData(inp, NULL);
3904 pathp = smb_ParseASCIIBlock(tp, &tp);
3906 osi_Log1(smb_logp, "SMB receive unlink %s",
3907 osi_LogSaveString(smb_logp, pathp));
3909 spacep = inp->spacep;
3910 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
3912 userp = smb_GetUser(vcp, inp);
3914 caseFold = CM_FLAG_FOLLOW | CM_FLAG_CASEFOLD;
3916 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3917 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold, userp, tidPathp,
3921 cm_ReleaseUser(userp);
3925 /* otherwise, scp points to the parent directory. */
3932 rock.maskp = smb_FindMask(pathp);
3933 rock.hasTilde = ((strchr(rock.maskp, '~') != NULL) ? 1 : 0);
3936 thyper.HighPart = 0;
3941 code = cm_ApplyDir(dscp, smb_UnlinkProc, &rock, &thyper, userp, &req, NULL);
3943 cm_ReleaseUser(userp);
3945 cm_ReleaseSCache(dscp);
3947 if (code == 0 && !rock.any)
3948 code = CM_ERROR_NOSUCHFILE;
3952 typedef struct smb_renameRock {
3953 cm_scache_t *odscp; /* old dir */
3954 cm_scache_t *ndscp; /* new dir */
3955 cm_user_t *userp; /* user */
3956 cm_req_t *reqp; /* request struct */
3957 smb_vc_t *vcp; /* virtual circuit */
3958 char *maskp; /* pointer to star pattern of old file name */
3959 int hasTilde; /* star pattern might be shortname? */
3960 char *newNamep; /* ptr to the new file's name */
3963 int smb_RenameProc(cm_scache_t *dscp, cm_dirEntry_t *dep, void *vrockp, osi_hyper_t *offp)
3966 smb_renameRock_t *rockp;
3973 if (rockp->vcp->flags & SMB_VCFLAG_USEV3)
3974 caseFold = CM_FLAG_CASEFOLD;
3976 caseFold = CM_FLAG_CASEFOLD | CM_FLAG_8DOT3;
3978 match = smb_V3MatchMask(dep->name, rockp->maskp, caseFold);
3981 && !cm_Is8Dot3(dep->name)) {
3982 cm_Gen8Dot3Name(dep, shortName, NULL);
3983 match = smb_V3MatchMask(shortName, rockp->maskp, caseFold);
3986 code = cm_Rename(rockp->odscp, dep->name,
3987 rockp->ndscp, rockp->newNamep, rockp->userp,
3989 /* if the call worked, stop doing the search now, since we
3990 * really only want to rename one file.
3993 code = CM_ERROR_STOPNOW;
4000 long smb_ReceiveCoreRename(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4007 smb_renameRock_t rock;
4008 cm_scache_t *oldDscp;
4009 cm_scache_t *newDscp;
4010 cm_scache_t *tmpscp;
4022 tp = smb_GetSMBData(inp, NULL);
4023 oldPathp = smb_ParseASCIIBlock(tp, &tp);
4024 newPathp = smb_ParseASCIIBlock(tp, &tp);
4026 osi_Log2(afsd_logp, "smb rename %s to %s",
4027 osi_LogSaveString(afsd_logp, oldPathp),
4028 osi_LogSaveString(afsd_logp, newPathp));
4030 spacep = inp->spacep;
4031 smb_StripLastComponent(spacep->data, &oldLastNamep, oldPathp);
4033 userp = smb_GetUser(vcp, inp);
4036 * Changed to use CASEFOLD always. This enables us to rename Foo/baz when
4037 * what actually exists is foo/baz. I don't know why the code used to be
4038 * the way it was. 1/29/96
4040 * caseFold = ((vcp->flags & SMB_VCFLAG_USEV3) ? 0: CM_FLAG_CASEFOLD);
4042 * Changed to use CM_FLAG_FOLLOW. 7/24/96
4044 * caseFold = CM_FLAG_CASEFOLD;
4046 caseFold = CM_FLAG_FOLLOW | CM_FLAG_CASEFOLD;
4048 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
4049 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold,
4050 userp, tidPathp, &req, &oldDscp);
4053 cm_ReleaseUser(userp);
4057 smb_StripLastComponent(spacep->data, &newLastNamep, newPathp);
4058 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold,
4059 userp, tidPathp, &req, &newDscp);
4062 cm_ReleaseSCache(oldDscp);
4063 cm_ReleaseUser(userp);
4067 /* otherwise, oldDscp and newDscp point to the corresponding directories.
4068 * next, get the component names, and lower case them.
4071 /* handle the old name first */
4073 oldLastNamep = oldPathp;
4077 /* and handle the new name, too */
4079 newLastNamep = newPathp;
4083 /* do the vnode call */
4084 rock.odscp = oldDscp;
4085 rock.ndscp = newDscp;
4089 rock.maskp = oldLastNamep;
4090 rock.hasTilde = ((strchr(oldLastNamep, '~') != NULL) ? 1 : 0);
4091 rock.newNamep = newLastNamep;
4093 /* Check if the file already exists; if so return error */
4094 code = cm_Lookup(newDscp,newLastNamep,CM_FLAG_CHECKPATH,userp,&req,&tmpscp);
4095 if((code != CM_ERROR_NOSUCHFILE) && (code != CM_ERROR_NOSUCHPATH) && (code != CM_ERROR_NOSUCHVOLUME) ) {
4096 cm_ReleaseSCache(tmpscp);
4097 return CM_ERROR_EXISTS; /* file exist, do not rename, also
4102 /* Now search the directory for the pattern, and do the appropriate rename when found */
4103 thyper.LowPart = 0; /* search dir from here */
4104 thyper.HighPart = 0;
4106 code = cm_ApplyDir(oldDscp, smb_RenameProc, &rock, &thyper, userp, &req, NULL);
4108 if (code == CM_ERROR_STOPNOW)
4111 code = CM_ERROR_NOSUCHFILE;
4113 /* Handle Change Notification */
4115 * Being lazy, not distinguishing between files and dirs in this
4116 * filter, since we'd have to do a lookup.
4118 filter = FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME;
4119 if (oldDscp == newDscp) {
4120 if (oldDscp->flags & CM_SCACHEFLAG_ANYWATCH)
4121 smb_NotifyChange(FILE_ACTION_RENAMED_OLD_NAME,
4122 filter, oldDscp, oldLastNamep,
4123 newLastNamep, TRUE);
4125 if (oldDscp->flags & CM_SCACHEFLAG_ANYWATCH)
4126 smb_NotifyChange(FILE_ACTION_RENAMED_OLD_NAME,
4127 filter, oldDscp, oldLastNamep,
4129 if (newDscp->flags & CM_SCACHEFLAG_ANYWATCH)
4130 smb_NotifyChange(FILE_ACTION_RENAMED_NEW_NAME,
4131 filter, newDscp, newLastNamep,
4135 cm_ReleaseUser(userp);
4137 cm_ReleaseSCache(oldDscp);
4138 cm_ReleaseSCache(newDscp);
4143 typedef struct smb_rmdirRock {
4147 char *maskp; /* pointer to the star pattern */
4152 int smb_RmdirProc(cm_scache_t *dscp, cm_dirEntry_t *dep, void *vrockp, osi_hyper_t *offp)
4155 smb_rmdirRock_t *rockp;
4162 matchName = dep->name;
4163 match = (cm_stricmp(matchName, rockp->maskp) == 0);
4166 && !cm_Is8Dot3(dep->name)) {
4167 cm_Gen8Dot3Name(dep, shortName, NULL);
4168 matchName = shortName;
4169 match = (cm_stricmp(matchName, rockp->maskp) == 0);
4172 osi_Log1(smb_logp, "Removing directory %s",
4173 osi_LogSaveString(smb_logp, matchName));
4174 code = cm_RemoveDir(dscp, dep->name, rockp->userp, rockp->reqp);
4175 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4176 smb_NotifyChange(FILE_ACTION_REMOVED,
4177 FILE_NOTIFY_CHANGE_DIR_NAME,
4178 dscp, dep->name, NULL, TRUE);
4187 long smb_ReceiveCoreRemoveDir(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4195 smb_rmdirRock_t rock;
4204 tp = smb_GetSMBData(inp, NULL);
4205 pathp = smb_ParseASCIIBlock(tp, &tp);
4207 spacep = inp->spacep;
4208 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
4210 userp = smb_GetUser(vcp, inp);
4212 caseFold = CM_FLAG_CASEFOLD;
4214 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
4215 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold | CM_FLAG_FOLLOW,
4216 userp, tidPathp, &req, &dscp);
4219 cm_ReleaseUser(userp);
4223 /* otherwise, scp points to the parent directory. */
4230 rock.maskp = lastNamep;
4231 rock.hasTilde = ((strchr(rock.maskp, '~') != NULL) ? 1 : 0);
4234 thyper.HighPart = 0;
4238 code = cm_ApplyDir(dscp, smb_RmdirProc, &rock, &thyper, userp, &req, NULL);
4240 cm_ReleaseUser(userp);
4242 cm_ReleaseSCache(dscp);
4244 if (code == 0 && !rock.any)
4245 code = CM_ERROR_NOSUCHFILE;
4249 long smb_ReceiveCoreFlush(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4259 fid = smb_GetSMBParm(inp, 0);
4261 osi_Log1(afsd_logp, "SMB flush fid %d", fid);
4263 fid = smb_ChainFID(fid, inp);
4264 fidp = smb_FindFID(vcp, fid, 0);
4265 if (!fidp || (fidp->flags & SMB_FID_IOCTL)) {
4267 smb_ReleaseFID(fidp);
4268 return CM_ERROR_BADFD;
4271 userp = smb_GetUser(vcp, inp);
4273 lock_ObtainMutex(&fidp->mx);
4274 if (fidp->flags & SMB_FID_OPENWRITE)
4275 code = cm_FSync(fidp->scp, userp, &req);
4278 lock_ReleaseMutex(&fidp->mx);
4280 smb_ReleaseFID(fidp);
4282 cm_ReleaseUser(userp);
4287 struct smb_FullNameRock {
4293 int smb_FullNameProc(cm_scache_t *scp, cm_dirEntry_t *dep, void *rockp,
4297 struct smb_FullNameRock *vrockp;
4301 if (!cm_Is8Dot3(dep->name)) {
4302 cm_Gen8Dot3Name(dep, shortName, NULL);
4304 if (strcmp(shortName, vrockp->name) == 0) {
4305 vrockp->fullName = strdup(dep->name);
4306 return CM_ERROR_STOPNOW;
4309 if (stricmp(dep->name, vrockp->name) == 0
4310 && ntohl(dep->fid.vnode) == vrockp->vnode->fid.vnode
4311 && ntohl(dep->fid.unique) == vrockp->vnode->fid.unique) {
4312 vrockp->fullName = strdup(dep->name);
4313 return CM_ERROR_STOPNOW;
4318 void smb_FullName(cm_scache_t *dscp, cm_scache_t *scp, char *pathp,
4319 char **newPathp, cm_user_t *userp, cm_req_t *reqp)
4321 struct smb_FullNameRock rock;
4327 code = cm_ApplyDir(dscp, smb_FullNameProc, &rock, NULL,
4329 if (code == CM_ERROR_STOPNOW)
4330 *newPathp = rock.fullName;
4332 *newPathp = strdup(pathp);
4335 long smb_ReceiveCoreClose(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4346 fid = smb_GetSMBParm(inp, 0);
4347 dosTime = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
4349 osi_Log1(afsd_logp, "SMB close fid %d", fid);
4351 fid = smb_ChainFID(fid, inp);
4352 fidp = smb_FindFID(vcp, fid, 0);
4354 return CM_ERROR_BADFD;
4357 userp = smb_GetUser(vcp, inp);
4359 lock_ObtainMutex(&fidp->mx);
4361 /* Don't jump the gun on an async raw write */
4362 while (fidp->raw_writers) {
4363 lock_ReleaseMutex(&fidp->mx);
4364 thrd_WaitForSingleObject_Event(fidp->raw_write_event, RAWTIMEOUT);
4365 lock_ObtainMutex(&fidp->mx);
4368 fidp->flags |= SMB_FID_DELETE;
4370 /* watch for ioctl closes, and read-only opens */
4371 if (fidp->scp != NULL
4372 && (fidp->flags & (SMB_FID_OPENWRITE | SMB_FID_DELONCLOSE))
4373 == SMB_FID_OPENWRITE) {
4374 if (dosTime != 0 && dosTime != -1) {
4375 fidp->scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
4376 /* This fixes defect 10958 */
4377 CompensateForSmbClientLastWriteTimeBugs(&dosTime);
4378 smb_UnixTimeFromDosUTime(&fidp->scp->clientModTime, dosTime);
4380 code = cm_FSync(fidp->scp, userp, &req);
4385 if (fidp->flags & SMB_FID_DELONCLOSE) {
4386 cm_scache_t *dscp = fidp->NTopen_dscp;
4387 char *pathp = fidp->NTopen_pathp;
4390 smb_FullName(dscp, fidp->scp, pathp, &fullPathp, userp, &req);
4391 if (fidp->scp->fileType == CM_SCACHETYPE_DIRECTORY) {
4392 code = cm_RemoveDir(dscp, fullPathp, userp, &req);
4393 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4394 smb_NotifyChange(FILE_ACTION_REMOVED,
4395 FILE_NOTIFY_CHANGE_DIR_NAME,
4396 dscp, fullPathp, NULL, TRUE);
4400 code = cm_Unlink(dscp, fullPathp, userp, &req);
4401 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4402 smb_NotifyChange(FILE_ACTION_REMOVED,
4403 FILE_NOTIFY_CHANGE_FILE_NAME,
4404 dscp, fullPathp, NULL, TRUE);
4408 lock_ReleaseMutex(&fidp->mx);
4410 if (fidp->flags & SMB_FID_NTOPEN) {
4411 cm_ReleaseSCache(fidp->NTopen_dscp);
4412 free(fidp->NTopen_pathp);
4414 if (fidp->NTopen_wholepathp)
4415 free(fidp->NTopen_wholepathp);
4417 smb_ReleaseFID(fidp);
4418 cm_ReleaseUser(userp);
4423 * smb_ReadData -- common code for Read, Read And X, and Raw Read
4426 long smb_ReadData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4427 cm_user_t *userp, long *readp)
4429 long smb_ReadData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4430 cm_user_t *userp, long *readp, int dosflag)
4437 osi_hyper_t fileLength;
4439 osi_hyper_t lastByte;
4440 osi_hyper_t bufferOffset;
4441 long bufIndex, nbytes;
4451 lock_ObtainMutex(&fidp->mx);
4453 lock_ObtainMutex(&scp->mx);
4455 if (offset.HighPart == 0) {
4456 chunk = offset.LowPart >> cm_logChunkSize;
4457 if (chunk != fidp->curr_chunk) {
4458 fidp->prev_chunk = fidp->curr_chunk;
4459 fidp->curr_chunk = chunk;
4461 if (fidp->curr_chunk == fidp->prev_chunk + 1)
4465 /* start by looking up the file's end */
4466 code = cm_SyncOp(scp, NULL, userp, &req, 0,
4467 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
4468 if (code) goto done;
4470 /* now we have the entry locked, look up the length */
4471 fileLength = scp->length;
4473 /* adjust count down so that it won't go past EOF */
4474 thyper.LowPart = count;
4475 thyper.HighPart = 0;
4476 thyper = LargeIntegerAdd(offset, thyper); /* where read should end */
4478 if (LargeIntegerGreaterThan(thyper, fileLength)) {
4479 /* we'd read past EOF, so just stop at fileLength bytes.
4480 * Start by computing how many bytes remain in the file.
4482 thyper = LargeIntegerSubtract(fileLength, offset);
4484 /* if we are past EOF, read 0 bytes */
4485 if (LargeIntegerLessThanZero(thyper))
4488 count = thyper.LowPart;
4493 /* now, copy the data one buffer at a time,
4494 * until we've filled the request packet
4497 /* if we've copied all the data requested, we're done */
4498 if (count <= 0) break;
4500 /* otherwise, load up a buffer of data */
4501 thyper.HighPart = offset.HighPart;
4502 thyper.LowPart = offset.LowPart & ~(buf_bufferSize-1);
4503 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
4506 buf_Release(bufferp);
4509 lock_ReleaseMutex(&scp->mx);
4511 lock_ObtainRead(&scp->bufCreateLock);
4512 code = buf_Get(scp, &thyper, &bufferp);
4513 lock_ReleaseRead(&scp->bufCreateLock);
4515 lock_ObtainMutex(&scp->mx);
4516 if (code) goto done;
4517 bufferOffset = thyper;
4519 /* now get the data in the cache */
4521 code = cm_SyncOp(scp, bufferp, userp, &req, 0,
4522 CM_SCACHESYNC_NEEDCALLBACK
4523 | CM_SCACHESYNC_READ);
4524 if (code) goto done;
4526 if (cm_HaveBuffer(scp, bufferp, 0)) break;
4528 /* otherwise, load the buffer and try again */
4529 code = cm_GetBuffer(scp, bufferp, NULL, userp, &req);
4533 buf_Release(bufferp);
4537 } /* if (wrong buffer) ... */
4539 /* now we have the right buffer loaded. Copy out the
4540 * data from here to the user's buffer.
4542 bufIndex = offset.LowPart & (buf_bufferSize - 1);
4544 /* and figure out how many bytes we want from this buffer */
4545 nbytes = buf_bufferSize - bufIndex; /* what remains in buffer */
4546 if (nbytes > count) nbytes = count; /* don't go past EOF */
4548 /* now copy the data */
4551 dosmemput(bufferp->datap + bufIndex, nbytes, (dos_ptr)op);
4554 memcpy(op, bufferp->datap + bufIndex, nbytes);
4556 /* adjust counters, pointers, etc. */
4559 thyper.LowPart = nbytes;
4560 thyper.HighPart = 0;
4561 offset = LargeIntegerAdd(thyper, offset);
4565 lock_ReleaseMutex(&scp->mx);
4566 lock_ReleaseMutex(&fidp->mx);
4568 buf_Release(bufferp);
4570 if (code == 0 && sequential)
4571 cm_ConsiderPrefetch(scp, &lastByte, userp, &req);
4577 * smb_WriteData -- common code for Write and Raw Write
4580 long smb_WriteData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4581 cm_user_t *userp, long *writtenp)
4583 long smb_WriteData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4584 cm_user_t *userp, long *writtenp, int dosflag)
4591 osi_hyper_t fileLength; /* file's length at start of write */
4592 osi_hyper_t minLength; /* don't read past this */
4593 long nbytes; /* # of bytes to transfer this iteration */
4595 osi_hyper_t thyper; /* hyper tmp variable */
4596 osi_hyper_t bufferOffset;
4597 long bufIndex; /* index in buffer where our data is */
4599 osi_hyper_t writeBackOffset; /* offset of region to write back when
4610 lock_ObtainMutex(&fidp->mx);
4612 lock_ObtainMutex(&scp->mx);
4614 /* start by looking up the file's end */
4615 code = cm_SyncOp(scp, NULL, userp, &req, 0,
4616 CM_SCACHESYNC_NEEDCALLBACK
4617 | CM_SCACHESYNC_SETSTATUS
4618 | CM_SCACHESYNC_GETSTATUS);
4622 /* make sure we have a writable FD */
4623 if (!(fidp->flags & SMB_FID_OPENWRITE)) {
4624 code = CM_ERROR_BADFDOP;
4628 /* now we have the entry locked, look up the length */
4629 fileLength = scp->length;
4630 minLength = fileLength;
4631 if (LargeIntegerGreaterThan(minLength, scp->serverLength))
4632 minLength = scp->serverLength;
4634 /* adjust file length if we extend past EOF */
4635 thyper.LowPart = count;
4636 thyper.HighPart = 0;
4637 thyper = LargeIntegerAdd(offset, thyper); /* where write should end */
4638 if (LargeIntegerGreaterThan(thyper, fileLength)) {
4639 /* we'd write past EOF, so extend the file */
4640 scp->mask |= CM_SCACHEMASK_LENGTH;
4641 scp->length = thyper;
4642 filter |= (FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE);
4644 filter |= FILE_NOTIFY_CHANGE_LAST_WRITE;
4646 /* now, if the new position (thyper) and the old (offset) are in
4647 * different storeback windows, remember to store back the previous
4648 * storeback window when we're done with the write.
4650 if ((thyper.LowPart & (-cm_chunkSize)) !=
4651 (offset.LowPart & (-cm_chunkSize))) {
4652 /* they're different */
4654 writeBackOffset.HighPart = offset.HighPart;
4655 writeBackOffset.LowPart = offset.LowPart & (-cm_chunkSize);
4660 /* now, copy the data one buffer at a time, until we've filled the
4663 /* if we've copied all the data requested, we're done */
4664 if (count <= 0) break;
4666 /* handle over quota or out of space */
4667 if (scp->flags & (CM_SCACHEFLAG_OVERQUOTA | CM_SCACHEFLAG_OUTOFSPACE)) {
4668 *writtenp = written;
4672 /* otherwise, load up a buffer of data */
4673 thyper.HighPart = offset.HighPart;
4674 thyper.LowPart = offset.LowPart & ~(buf_bufferSize-1);
4675 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
4678 lock_ReleaseMutex(&bufferp->mx);
4679 buf_Release(bufferp);
4682 lock_ReleaseMutex(&scp->mx);
4684 lock_ObtainRead(&scp->bufCreateLock);
4685 code = buf_Get(scp, &thyper, &bufferp);
4686 lock_ReleaseRead(&scp->bufCreateLock);
4688 lock_ObtainMutex(&bufferp->mx);
4689 lock_ObtainMutex(&scp->mx);
4690 if (code) goto done;
4692 bufferOffset = thyper;
4694 /* now get the data in the cache */
4696 code = cm_SyncOp(scp, bufferp, userp, &req, 0,
4697 CM_SCACHESYNC_NEEDCALLBACK
4698 | CM_SCACHESYNC_WRITE
4699 | CM_SCACHESYNC_BUFLOCKED);
4703 /* If we're overwriting the entire buffer, or
4704 * if we're writing at or past EOF, mark the
4705 * buffer as current so we don't call
4706 * cm_GetBuffer. This skips the fetch from the
4707 * server in those cases where we're going to
4708 * obliterate all the data in the buffer anyway,
4709 * or in those cases where there is no useful
4710 * data at the server to start with.
4712 * Use minLength instead of scp->length, since
4713 * the latter has already been updated by this
4716 if (LargeIntegerGreaterThanOrEqualTo(
4717 bufferp->offset, minLength)
4718 || LargeIntegerEqualTo(offset, bufferp->offset)
4719 && (count >= buf_bufferSize
4720 || LargeIntegerGreaterThanOrEqualTo(
4721 LargeIntegerAdd(offset,
4722 ConvertLongToLargeInteger(count)),
4724 if (count < buf_bufferSize
4725 && bufferp->dataVersion == -1)
4726 memset(bufferp->datap, 0,
4728 bufferp->dataVersion = scp->dataVersion;
4731 if (cm_HaveBuffer(scp, bufferp, 1)) break;
4733 /* otherwise, load the buffer and try again */
4734 lock_ReleaseMutex(&bufferp->mx);
4735 code = cm_GetBuffer(scp, bufferp, NULL, userp,
4737 lock_ReleaseMutex(&scp->mx);
4738 lock_ObtainMutex(&bufferp->mx);
4739 lock_ObtainMutex(&scp->mx);
4743 lock_ReleaseMutex(&bufferp->mx);
4744 buf_Release(bufferp);
4748 } /* if (wrong buffer) ... */
4750 /* now we have the right buffer loaded. Copy out the
4751 * data from here to the user's buffer.
4753 bufIndex = offset.LowPart & (buf_bufferSize - 1);
4755 /* and figure out how many bytes we want from this buffer */
4756 nbytes = buf_bufferSize - bufIndex; /* what remains in buffer */
4758 nbytes = count; /* don't go past end of request */
4760 /* now copy the data */
4763 dosmemget((dos_ptr)op, nbytes, bufferp->datap + bufIndex);
4766 memcpy(bufferp->datap + bufIndex, op, nbytes);
4767 buf_SetDirty(bufferp);
4769 /* and record the last writer */
4770 if (bufferp->userp != userp) {
4773 cm_ReleaseUser(bufferp->userp);
4774 bufferp->userp = userp;
4777 /* adjust counters, pointers, etc. */
4781 thyper.LowPart = nbytes;
4782 thyper.HighPart = 0;
4783 offset = LargeIntegerAdd(thyper, offset);
4787 lock_ReleaseMutex(&scp->mx);
4788 lock_ReleaseMutex(&fidp->mx);
4790 lock_ReleaseMutex(&bufferp->mx);
4791 buf_Release(bufferp);
4794 if (code == 0 && filter != 0 && (fidp->flags & SMB_FID_NTOPEN)
4795 && (fidp->NTopen_dscp->flags & CM_SCACHEFLAG_ANYWATCH)) {
4796 smb_NotifyChange(FILE_ACTION_MODIFIED, filter,
4797 fidp->NTopen_dscp, fidp->NTopen_pathp,
4801 if (code == 0 && doWriteBack) {
4802 lock_ObtainMutex(&scp->mx);
4803 cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_ASYNCSTORE);
4804 lock_ReleaseMutex(&scp->mx);
4805 cm_QueueBKGRequest(scp, cm_BkgStore, writeBackOffset.LowPart,
4806 writeBackOffset.HighPart, cm_chunkSize, 0, userp);
4812 long smb_ReceiveCoreWrite(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4815 long count, written = 0;
4820 cm_attr_t truncAttr; /* attribute struct used for truncating file */
4822 int inDataBlockCount;
4824 fd = smb_GetSMBParm(inp, 0);
4825 count = smb_GetSMBParm(inp, 1);
4826 offset.HighPart = 0; /* too bad */
4827 offset.LowPart = smb_GetSMBParm(inp, 2) | (smb_GetSMBParm(inp, 3) << 16);
4829 op = smb_GetSMBData(inp, NULL);
4830 op = smb_ParseDataBlock(op, NULL, &inDataBlockCount);
4832 osi_Log3(afsd_logp, "smb_ReceiveCoreWrite fd %d, off 0x%x, size 0x%x",
4833 fd, offset.LowPart, count);
4835 fd = smb_ChainFID(fd, inp);
4836 fidp = smb_FindFID(vcp, fd, 0);
4838 return CM_ERROR_BADFD;
4841 if (fidp->flags & SMB_FID_IOCTL)
4842 return smb_IoctlWrite(fidp, vcp, inp, outp);
4844 userp = smb_GetUser(vcp, inp);
4846 /* special case: 0 bytes transferred means truncate to this position */
4852 truncAttr.mask = CM_ATTRMASK_LENGTH;
4853 truncAttr.length.LowPart = offset.LowPart;
4854 truncAttr.length.HighPart = 0;
4855 lock_ObtainMutex(&fidp->mx);
4856 code = cm_SetAttr(fidp->scp, &truncAttr, userp, &req);
4857 lock_ReleaseMutex(&fidp->mx);
4858 smb_SetSMBParm(outp, 0, /* count */ 0);
4859 smb_SetSMBDataLength(outp, 0);
4860 fidp->flags |= SMB_FID_LENGTHSETDONE;
4865 * Work around bug in NT client
4867 * When copying a file, the NT client should first copy the data,
4868 * then copy the last write time. But sometimes the NT client does
4869 * these in the wrong order, so the data copies would inadvertently
4870 * cause the last write time to be overwritten. We try to detect this,
4871 * and don't set client mod time if we think that would go against the
4874 if ((fidp->flags & SMB_FID_MTIMESETDONE) != SMB_FID_MTIMESETDONE) {
4875 fidp->scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
4876 fidp->scp->clientModTime = time(NULL);
4880 code = smb_WriteData(fidp, &offset, count, op, userp, &written);
4882 code = smb_WriteData(fidp, &offset, count, op, userp, &written, FALSE);
4884 if (code == 0 && written < count)
4885 code = CM_ERROR_PARTIALWRITE;
4887 /* set the packet data length to 3 bytes for the data block header,
4888 * plus the size of the data.
4890 smb_SetSMBParm(outp, 0, written);
4891 smb_SetSMBDataLength(outp, 0);
4894 smb_ReleaseFID(fidp);
4895 cm_ReleaseUser(userp);
4900 void smb_CompleteWriteRaw(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp,
4901 NCB *ncbp, raw_write_cont_t *rwcp)
4914 fd = smb_GetSMBParm(inp, 0);
4915 fidp = smb_FindFID(vcp, fd, 0);
4917 osi_Log2(afsd_logp, "Completing Raw Write offset %x count %x",
4918 rwcp->offset.LowPart, rwcp->count);
4920 userp = smb_GetUser(vcp, inp);
4924 code = smb_WriteData(fidp, &rwcp->offset, rwcp->count, rawBuf, userp,
4927 rawBuf = (dos_ptr) rwcp->buf;
4928 code = smb_WriteData(fidp, &rwcp->offset, rwcp->count,
4929 (unsigned char *) rawBuf, userp,
4933 if (rwcp->writeMode & 0x1) { /* synchronous */
4936 smb_FormatResponsePacket(vcp, inp, outp);
4937 op = (smb_t *) outp;
4938 op->com = 0x20; /* SMB_COM_WRITE_COMPLETE */
4939 smb_SetSMBParm(outp, 0, written + rwcp->alreadyWritten);
4940 smb_SetSMBDataLength(outp, 0);
4941 smb_SendPacket(vcp, outp);
4942 smb_FreePacket(outp);
4944 else { /* asynchronous */
4945 lock_ObtainMutex(&fidp->mx);
4946 fidp->raw_writers--;
4947 if (fidp->raw_writers == 0)
4948 thrd_SetEvent(fidp->raw_write_event);
4949 lock_ReleaseMutex(&fidp->mx);
4952 /* Give back raw buffer */
4953 lock_ObtainMutex(&smb_RawBufLock);
4955 *((char **)rawBuf) = smb_RawBufs;
4957 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
4959 smb_RawBufs = rawBuf;
4960 lock_ReleaseMutex(&smb_RawBufLock);
4962 smb_ReleaseFID(fidp);
4963 cm_ReleaseUser(userp);
4966 long smb_ReceiveCoreWriteRawDummy(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4971 long smb_ReceiveCoreWriteRaw(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp, raw_write_cont_t *rwcp)
4974 long count, written = 0;
4981 unsigned short writeMode;
4988 fd = smb_GetSMBParm(inp, 0);
4989 totalCount = smb_GetSMBParm(inp, 1);
4990 count = smb_GetSMBParm(inp, 10);
4991 offset.HighPart = 0; /* too bad */
4992 offset.LowPart = smb_GetSMBParm(inp, 3) | (smb_GetSMBParm(inp, 4) << 16);
4993 writeMode = smb_GetSMBParm(inp, 7);
4995 op = (char *) inp->data;
4996 op += smb_GetSMBParm(inp, 11);
4999 "smb_ReceiveCoreWriteRaw fd %d, off 0x%x, size 0x%x, WriteMode 0x%x",
5000 fd, offset.LowPart, count, writeMode);
5002 fd = smb_ChainFID(fd, inp);
5003 fidp = smb_FindFID(vcp, fd, 0);
5005 return CM_ERROR_BADFD;
5008 userp = smb_GetUser(vcp, inp);
5011 * Work around bug in NT client
5013 * When copying a file, the NT client should first copy the data,
5014 * then copy the last write time. But sometimes the NT client does
5015 * these in the wrong order, so the data copies would inadvertently
5016 * cause the last write time to be overwritten. We try to detect this,
5017 * and don't set client mod time if we think that would go against the
5020 if ((fidp->flags & SMB_FID_LOOKSLIKECOPY) != SMB_FID_LOOKSLIKECOPY) {
5021 fidp->scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
5022 fidp->scp->clientModTime = time(NULL);
5026 code = smb_WriteData(fidp, &offset, count, op, userp, &written);
5028 code = smb_WriteData(fidp, &offset, count, op, userp, &written, FALSE);
5030 if (code == 0 && written < count)
5031 code = CM_ERROR_PARTIALWRITE;
5033 /* Get a raw buffer */
5036 lock_ObtainMutex(&smb_RawBufLock);
5038 /* Get a raw buf, from head of list */
5039 rawBuf = smb_RawBufs;
5041 smb_RawBufs = *(char **)smb_RawBufs;
5043 smb_RawBufs = _farpeekl(_dos_ds, smb_RawBufs);
5047 code = CM_ERROR_USESTD;
5049 lock_ReleaseMutex(&smb_RawBufLock);
5052 /* Don't allow a premature Close */
5053 if (code == 0 && (writeMode & 1) == 0) {
5054 lock_ObtainMutex(&fidp->mx);
5055 fidp->raw_writers++;
5056 thrd_ResetEvent(fidp->raw_write_event);
5057 lock_ReleaseMutex(&fidp->mx);
5060 smb_ReleaseFID(fidp);
5061 cm_ReleaseUser(userp);
5064 smb_SetSMBParm(outp, 0, written);
5065 smb_SetSMBDataLength(outp, 0);
5066 ((smb_t *)outp)->com = 0x20; /* SMB_COM_WRITE_COMPLETE */
5073 rwcp->offset.HighPart = 0;
5074 rwcp->offset.LowPart = offset.LowPart + count;
5075 rwcp->count = totalCount - count;
5076 rwcp->writeMode = writeMode;
5077 rwcp->alreadyWritten = written;
5079 /* set the packet data length to 3 bytes for the data block header,
5080 * plus the size of the data.
5082 smb_SetSMBParm(outp, 0, 0xffff);
5083 smb_SetSMBDataLength(outp, 0);
5088 long smb_ReceiveCoreRead(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5091 long count, finalCount;
5098 fd = smb_GetSMBParm(inp, 0);
5099 count = smb_GetSMBParm(inp, 1);
5100 offset.HighPart = 0; /* too bad */
5101 offset.LowPart = smb_GetSMBParm(inp, 2) | (smb_GetSMBParm(inp, 3) << 16);
5103 osi_Log3(afsd_logp, "smb_ReceiveCoreRead fd %d, off 0x%x, size 0x%x",
5104 fd, offset.LowPart, count);
5106 fd = smb_ChainFID(fd, inp);
5107 fidp = smb_FindFID(vcp, fd, 0);
5109 return CM_ERROR_BADFD;
5112 if (fidp->flags & SMB_FID_IOCTL) {
5113 return smb_IoctlRead(fidp, vcp, inp, outp);
5116 userp = smb_GetUser(vcp, inp);
5118 /* remember this for final results */
5119 smb_SetSMBParm(outp, 0, count);
5120 smb_SetSMBParm(outp, 1, 0);
5121 smb_SetSMBParm(outp, 2, 0);
5122 smb_SetSMBParm(outp, 3, 0);
5123 smb_SetSMBParm(outp, 4, 0);
5125 /* set the packet data length to 3 bytes for the data block header,
5126 * plus the size of the data.
5128 smb_SetSMBDataLength(outp, count+3);
5130 /* get op ptr after putting in the parms, since otherwise we don't
5131 * know where the data really is.
5133 op = smb_GetSMBData(outp, NULL);
5135 /* now emit the data block header: 1 byte of type and 2 bytes of length */
5136 *op++ = 1; /* data block marker */
5137 *op++ = (unsigned char) (count & 0xff);
5138 *op++ = (unsigned char) ((count >> 8) & 0xff);
5141 code = smb_ReadData(fidp, &offset, count, op, userp, &finalCount);
5143 code = smb_ReadData(fidp, &offset, count, op, userp, &finalCount, FALSE);
5146 /* fix some things up */
5147 smb_SetSMBParm(outp, 0, finalCount);
5148 smb_SetSMBDataLength(outp, finalCount+3);
5150 smb_ReleaseFID(fidp);
5152 cm_ReleaseUser(userp);
5156 long smb_ReceiveCoreMakeDir(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5163 cm_scache_t *dscp; /* dir we're dealing with */
5164 cm_scache_t *scp; /* file we're creating */
5166 int initialModeBits;
5176 /* compute initial mode bits based on read-only flag in attributes */
5177 initialModeBits = 0777;
5179 tp = smb_GetSMBData(inp, NULL);
5180 pathp = smb_ParseASCIIBlock(tp, &tp);
5182 if (strcmp(pathp, "\\") == 0)
5183 return CM_ERROR_EXISTS;
5185 spacep = inp->spacep;
5186 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
5188 userp = smb_GetUser(vcp, inp);
5190 caseFold = CM_FLAG_CASEFOLD;
5192 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
5194 code = cm_NameI(cm_rootSCachep, spacep->data,
5195 caseFold | CM_FLAG_FOLLOW | CM_FLAG_CHECKPATH,
5196 userp, tidPathp, &req, &dscp);
5199 cm_ReleaseUser(userp);
5203 /* otherwise, scp points to the parent directory. Do a lookup, and
5204 * fail if we find it. Otherwise, we do the create.
5210 code = cm_Lookup(dscp, lastNamep, caseFold, userp, &req, &scp);
5211 if (scp) cm_ReleaseSCache(scp);
5212 if (code != CM_ERROR_NOSUCHFILE) {
5213 if (code == 0) code = CM_ERROR_EXISTS;
5214 cm_ReleaseSCache(dscp);
5215 cm_ReleaseUser(userp);
5219 setAttr.mask = CM_ATTRMASK_CLIENTMODTIME;
5220 setAttr.clientModTime = time(NULL);
5221 code = cm_MakeDir(dscp, lastNamep, 0, &setAttr, userp, &req);
5222 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
5223 smb_NotifyChange(FILE_ACTION_ADDED,
5224 FILE_NOTIFY_CHANGE_DIR_NAME,
5225 dscp, lastNamep, NULL, TRUE);
5227 /* we don't need this any longer */
5228 cm_ReleaseSCache(dscp);
5231 /* something went wrong creating or truncating the file */
5232 cm_ReleaseUser(userp);
5236 /* otherwise we succeeded */
5237 smb_SetSMBDataLength(outp, 0);
5238 cm_ReleaseUser(userp);
5243 BOOL smb_IsLegalFilename(char *filename)
5246 * Find the longest substring of filename that does not contain
5247 * any of the chars in illegalChars. If that substring is less
5248 * than the length of the whole string, then one or more of the
5249 * illegal chars is in filename.
5251 if (strcspn(filename, illegalChars) < strlen(filename))
5257 long smb_ReceiveCoreCreate(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5265 cm_scache_t *dscp; /* dir we're dealing with */
5266 cm_scache_t *scp; /* file we're creating */
5268 int initialModeBits;
5280 excl = (inp->inCom == 0x03)? 0 : 1;
5282 attributes = smb_GetSMBParm(inp, 0);
5283 dosTime = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
5285 /* compute initial mode bits based on read-only flag in attributes */
5286 initialModeBits = 0666;
5287 if (attributes & 1) initialModeBits &= ~0222;
5289 tp = smb_GetSMBData(inp, NULL);
5290 pathp = smb_ParseASCIIBlock(tp, &tp);
5292 spacep = inp->spacep;
5293 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
5295 userp = smb_GetUser(vcp, inp);
5297 caseFold = CM_FLAG_CASEFOLD;
5299 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
5300 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold | CM_FLAG_FOLLOW,
5301 userp, tidPathp, &req, &dscp);
5304 cm_ReleaseUser(userp);
5308 /* otherwise, scp points to the parent directory. Do a lookup, and
5309 * truncate the file if we find it, otherwise we create the file.
5311 if (!lastNamep) lastNamep = pathp;
5314 if (!smb_IsLegalFilename(lastNamep))
5315 return CM_ERROR_BADNTFILENAME;
5317 osi_Log1(afsd_logp, "SMB receive create [%s]", osi_LogSaveString( afsd_logp, pathp ));
5318 #ifdef DEBUG_VERBOSE
5321 hexp = osi_HexifyString( lastNamep );
5322 DEBUG_EVENT2("AFS", "CoreCreate H[%s] A[%s]", hexp, lastNamep );
5327 code = cm_Lookup(dscp, lastNamep, caseFold, userp, &req, &scp);
5328 if (code && code != CM_ERROR_NOSUCHFILE) {
5329 cm_ReleaseSCache(dscp);
5330 cm_ReleaseUser(userp);
5334 /* if we get here, if code is 0, the file exists and is represented by
5335 * scp. Otherwise, we have to create it.
5339 /* oops, file shouldn't be there */
5340 cm_ReleaseSCache(dscp);
5341 cm_ReleaseSCache(scp);
5342 cm_ReleaseUser(userp);
5343 return CM_ERROR_EXISTS;
5346 setAttr.mask = CM_ATTRMASK_LENGTH;
5347 setAttr.length.LowPart = 0;
5348 setAttr.length.HighPart = 0;
5349 code = cm_SetAttr(scp, &setAttr, userp, &req);
5352 setAttr.mask = CM_ATTRMASK_CLIENTMODTIME;
5353 smb_UnixTimeFromDosUTime(&setAttr.clientModTime, dosTime);
5354 code = cm_Create(dscp, lastNamep, 0, &setAttr, &scp, userp,
5356 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
5357 smb_NotifyChange(FILE_ACTION_ADDED,
5358 FILE_NOTIFY_CHANGE_FILE_NAME,
5359 dscp, lastNamep, NULL, TRUE);
5360 if (!excl && code == CM_ERROR_EXISTS) {
5361 /* not an exclusive create, and someone else tried
5362 * creating it already, then we open it anyway. We
5363 * don't bother retrying after this, since if this next
5364 * fails, that means that the file was deleted after
5365 * we started this call.
5367 code = cm_Lookup(dscp, lastNamep, caseFold, userp,
5370 setAttr.mask = CM_ATTRMASK_LENGTH;
5371 setAttr.length.LowPart = 0;
5372 setAttr.length.HighPart = 0;
5373 code = cm_SetAttr(scp, &setAttr, userp, &req);
5378 /* we don't need this any longer */
5379 cm_ReleaseSCache(dscp);
5382 /* something went wrong creating or truncating the file */
5383 if (scp) cm_ReleaseSCache(scp);
5384 cm_ReleaseUser(userp);
5388 /* make sure we only open files */
5389 if (scp->fileType != CM_SCACHETYPE_FILE) {
5390 cm_ReleaseSCache(scp);
5391 cm_ReleaseUser(userp);
5392 return CM_ERROR_ISDIR;
5395 /* now all we have to do is open the file itself */
5396 fidp = smb_FindFID(vcp, 0, SMB_FLAG_CREATE);
5399 /* save a pointer to the vnode */
5402 /* always create it open for read/write */
5403 fidp->flags |= (SMB_FID_OPENREAD | SMB_FID_OPENWRITE);
5405 smb_ReleaseFID(fidp);
5407 smb_SetSMBParm(outp, 0, fidp->fid);
5408 smb_SetSMBDataLength(outp, 0);
5410 cm_Open(scp, 0, userp);
5412 cm_ReleaseUser(userp);
5413 /* leave scp held since we put it in fidp->scp */
5417 long smb_ReceiveCoreSeek(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5430 fd = smb_GetSMBParm(inp, 0);
5431 whence = smb_GetSMBParm(inp, 1);
5432 offset = smb_GetSMBParm(inp, 2) | (smb_GetSMBParm(inp, 3) << 16);
5434 /* try to find the file descriptor */
5435 fd = smb_ChainFID(fd, inp);
5436 fidp = smb_FindFID(vcp, fd, 0);
5437 if (!fidp || (fidp->flags & SMB_FID_IOCTL)) {
5438 return CM_ERROR_BADFD;
5441 userp = smb_GetUser(vcp, inp);
5443 lock_ObtainMutex(&fidp->mx);
5445 lock_ObtainMutex(&scp->mx);
5446 code = cm_SyncOp(scp, NULL, userp, &req, 0,
5447 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
5450 /* offset from current offset */
5451 offset += fidp->offset;
5453 else if (whence == 2) {
5454 /* offset from current EOF */
5455 offset += scp->length.LowPart;
5457 fidp->offset = offset;
5458 smb_SetSMBParm(outp, 0, offset & 0xffff);
5459 smb_SetSMBParm(outp, 1, (offset>>16) & 0xffff);
5460 smb_SetSMBDataLength(outp, 0);
5462 lock_ReleaseMutex(&scp->mx);
5463 lock_ReleaseMutex(&fidp->mx);
5464 smb_ReleaseFID(fidp);
5465 cm_ReleaseUser(userp);
5469 /* dispatch all of the requests received in a packet. Due to chaining, this may
5470 * be more than one request.
5472 void smb_DispatchPacket(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp,
5473 NCB *ncbp, raw_write_cont_t *rwcp)
5475 static showErrors = 0;
5478 unsigned long code = 0;
5479 unsigned char *outWctp;
5480 int nparms; /* # of bytes of parameters */
5482 int nbytes; /* bytes of data, excluding count */
5485 unsigned short errCode;
5486 unsigned long NTStatus;
5488 unsigned char errClass;
5489 unsigned int oldGen;
5490 DWORD oldTime, newTime;
5492 /* get easy pointer to the data */
5493 smbp = (smb_t *) inp->data;
5495 if (!(outp->flags & SMB_PACKETFLAG_SUSPENDED)) {
5496 /* setup the basic parms for the initial request in the packet */
5497 inp->inCom = smbp->com;
5498 inp->wctp = &smbp->wct;
5500 inp->ncb_length = ncbp->ncb_length;
5505 if (ncbp->ncb_length < offsetof(struct smb, vdata)) {
5506 /* log it and discard it */
5511 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
5512 sprintf(s, "SMB message too short, len %d", ncbp->ncb_length);
5514 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1007, NULL,
5515 1, ncbp->ncb_length, ptbuf, inp);
5516 DeregisterEventSource(h);
5518 osi_Log1(smb_logp, "SMB message too short, len %d",
5525 /* We are an ongoing op */
5526 thrd_Increment(&ongoingOps);
5528 /* set up response packet for receiving output */
5529 if (!(outp->flags & SMB_PACKETFLAG_SUSPENDED))
5530 smb_FormatResponsePacket(vcp, inp, outp);
5531 outWctp = outp->wctp;
5533 /* Remember session generation number and time */
5534 oldGen = sessionGen;
5535 oldTime = GetCurrentTime();
5537 while(inp->inCom != 0xff) {
5538 dp = &smb_dispatchTable[inp->inCom];
5540 if (outp->flags & SMB_PACKETFLAG_SUSPENDED) {
5541 outp->flags &= ~SMB_PACKETFLAG_SUSPENDED;
5542 code = outp->resumeCode;
5546 /* process each request in the packet; inCom, wctp and inCount
5547 * are already set up.
5549 osi_Log2(afsd_logp, "SMB received op 0x%x lsn %d", inp->inCom,
5552 /* now do the dispatch */
5553 /* start by formatting the response record a little, as a default */
5554 if (dp->flags & SMB_DISPATCHFLAG_CHAINED) {
5556 outWctp[1] = 0xff; /* no operation */
5557 outWctp[2] = 0; /* padding */
5562 /* not a chained request, this is a more reasonable default */
5563 outWctp[0] = 0; /* wct of zero */
5564 outWctp[1] = 0; /* and bcc (word) of zero */
5568 /* once set, stays set. Doesn't matter, since we never chain
5569 * "no response" calls.
5571 if (dp->flags & SMB_DISPATCHFLAG_NORESPONSE)
5575 /* we have a recognized operation */
5577 if (inp->inCom == 0x1d)
5579 code = smb_ReceiveCoreWriteRaw (vcp, inp, outp,
5582 osi_LogEvent("AFS Dispatch %s",(myCrt_Dispatch(inp->inCom)),"vcp[%x] lana[%d] lsn[%d]",(int)vcp,vcp->lana,vcp->lsn);
5583 osi_Log4(afsd_logp,"Dispatch %s vcp[%x] lana[%d] lsn[%d]",(myCrt_Dispatch(inp->inCom)),vcp,vcp->lana,vcp->lsn);
5584 code = (*(dp->procp)) (vcp, inp, outp);
5585 osi_LogEvent("AFS Dispatch return",NULL,"Code[%d]",(code==0)?0:code-CM_ERROR_BASE);
5586 osi_Log1(afsd_logp,"Dispatch return code[%d]",(code==0)?0:code-CM_ERROR_BASE);
5589 if (oldGen != sessionGen) {
5594 newTime = GetCurrentTime();
5595 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
5596 sprintf(s, "Pkt straddled session startup, took %d ms, ncb length %d",
5597 newTime - oldTime, ncbp->ncb_length);
5599 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0,
5600 1005, NULL, 1, ncbp->ncb_length, ptbuf, smbp);
5601 DeregisterEventSource(h);
5603 osi_Log1(afsd_logp, "Pkt straddled session startup, "
5604 "ncb length %d", ncbp->ncb_length);
5609 /* bad opcode, fail the request, after displaying it */
5612 #endif /* NOTSERVICE */
5616 sprintf(tbuffer, "Received bad SMB req 0x%x", inp->inCom);
5617 code = (*smb_MBfunc)(NULL, tbuffer, "Cancel: don't show again",
5619 if (code == IDCANCEL) showErrors = 0;
5622 code = CM_ERROR_BADOP;
5625 /* catastrophic failure: log as much as possible */
5626 if (code == CM_ERROR_BADSMB) {
5633 "Invalid SMB, ncb_length %d",
5636 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
5637 sprintf(s, "Invalid SMB message, length %d",
5640 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1002, NULL,
5641 1, ncbp->ncb_length, ptbuf, smbp);
5642 DeregisterEventSource(h);
5645 #endif /* NOTSERVICE */
5647 osi_Log1(afsd_logp, "Invalid SMB message, length %d",
5651 code = CM_ERROR_INVAL;
5654 if (outp->flags & SMB_PACKETFLAG_NOSEND) {
5655 thrd_Decrement(&ongoingOps);
5660 /* now, if we failed, turn the current response into an empty
5661 * one, and fill in the response packet's error code.
5664 if (vcp->flags & SMB_VCFLAG_STATUS32) {
5665 smb_MapNTError(code, &NTStatus);
5666 outWctp = outp->wctp;
5667 smbp = (smb_t *) &outp->data;
5668 if (code != CM_ERROR_PARTIALWRITE
5669 && code != CM_ERROR_BUFFERTOOSMALL) {
5670 /* nuke wct and bcc. For a partial
5671 * write, assume they're OK.
5677 smbp->rcls = (unsigned char) (NTStatus & 0xff);
5678 smbp->reh = (unsigned char) ((NTStatus >> 8) & 0xff);
5679 smbp->errLow = (unsigned char) ((NTStatus >> 16) & 0xff);
5680 smbp->errHigh = (unsigned char) ((NTStatus >> 24) & 0xff);
5681 smbp->flg2 |= 0x4000;
5685 smb_MapCoreError(code, vcp, &errCode, &errClass);
5686 outWctp = outp->wctp;
5687 smbp = (smb_t *) &outp->data;
5688 if (code != CM_ERROR_PARTIALWRITE) {
5689 /* nuke wct and bcc. For a partial
5690 * write, assume they're OK.
5696 smbp->errLow = (unsigned char) (errCode & 0xff);
5697 smbp->errHigh = (unsigned char) ((errCode >> 8) & 0xff);
5698 smbp->rcls = errClass;
5701 } /* error occurred */
5703 /* if we're here, we've finished one request. Look to see if
5704 * this is a chained opcode. If it is, setup things to process
5705 * the chained request, and setup the output buffer to hold the
5706 * chained response. Start by finding the next input record.
5708 if (!(dp->flags & SMB_DISPATCHFLAG_CHAINED))
5709 break; /* not a chained req */
5710 tp = inp->wctp; /* points to start of last request */
5711 /* in a chained request, the first two
5712 * parm fields are required, and are
5713 * AndXCommand/AndXReserved and
5715 if (tp[0] < 2) break;
5716 if (tp[1] == 0xff) break; /* no more chained opcodes */
5718 inp->wctp = inp->data + tp[3] + (tp[4] << 8);
5721 /* and now append the next output request to the end of this
5722 * last request. Begin by finding out where the last response
5723 * ends, since that's where we'll put our new response.
5725 outWctp = outp->wctp; /* ptr to out parameters */
5726 osi_assert (outWctp[0] >= 2); /* need this for all chained requests */
5727 nparms = outWctp[0] << 1;
5728 tp = outWctp + nparms + 1; /* now points to bcc field */
5729 nbytes = tp[0] + (tp[1] << 8); /* # of data bytes */
5730 tp += 2 /* for the count itself */ + nbytes;
5731 /* tp now points to the new output record; go back and patch the
5732 * second parameter (off2) to point to the new record.
5734 temp = (unsigned int)tp - ((unsigned int) outp->data);
5735 outWctp[3] = (unsigned char) (temp & 0xff);
5736 outWctp[4] = (unsigned char) ((temp >> 8) & 0xff);
5737 outWctp[2] = 0; /* padding */
5738 outWctp[1] = inp->inCom; /* next opcode */
5740 /* finally, setup for the next iteration */
5743 } /* while loop over all requests in the packet */
5745 /* done logging out, turn off logging-out flag */
5746 if (!(inp->flags & SMB_PACKETFLAG_PROFILE_UPDATE_OK)) {
5747 vcp->justLoggedOut = NULL;
5750 free(loggedOutName);
5751 loggedOutName = NULL;
5752 smb_ReleaseUID(loggedOutUserp);
5753 loggedOutUserp = NULL;
5757 /* now send the output packet, and return */
5759 smb_SendPacket(vcp, outp);
5760 thrd_Decrement(&ongoingOps);
5762 if (!(vcp->flags & SMB_VCFLAG_ALREADYDEAD)) {
5764 last_msg_time = GetCurrentTime();
5766 else if (active_vcp == vcp)
5773 /* Wait for Netbios() calls to return, and make the results available to server
5774 * threads. Note that server threads can't wait on the NCBevents array
5775 * themselves, because NCB events are manual-reset, and the servers would race
5776 * each other to reset them.
5778 void smb_ClientWaiter(void *parmp)
5784 code = thrd_WaitForMultipleObjects_Event(numNCBs, NCBevents,
5786 if (code == WAIT_OBJECT_0)
5789 /* error checking */
5790 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numNCBs))
5792 int abandonIdx = code - WAIT_ABANDONED_0;
5793 afsi_log("Error: smb_ClientWaiter event %d abandoned, errno %d\n", abandonIdx, GetLastError());
5796 if (code == WAIT_IO_COMPLETION)
5798 afsi_log("Error: smb_ClientWaiter WAIT_IO_COMPLETION\n");
5802 if (code == WAIT_TIMEOUT)
5804 afsi_log("Error: smb_ClientWaiter WAIT_TIMEOUT, errno %d\n", GetLastError());
5807 if (code == WAIT_FAILED)
5809 afsi_log("Error: smb_ClientWaiter WAIT_FAILED, errno %d\n", GetLastError());
5812 idx = code - WAIT_OBJECT_0;
5814 /* check idx range! */
5815 if (idx < 0 || idx > (sizeof(NCBevents) / sizeof(NCBevents[0])))
5817 /* this is fatal - log as much as possible */
5818 afsi_log("Fatal: NCBevents idx [ %d ] out of range.\n", idx);
5822 thrd_ResetEvent(NCBevents[idx]);
5823 thrd_SetEvent(NCBreturns[0][idx]);
5829 * Try to have one NCBRECV request waiting for every live session. Not more
5830 * than one, because if there is more than one, it's hard to handle Write Raw.
5832 void smb_ServerWaiter(void *parmp)
5835 int idx_session, idx_NCB;
5843 code = thrd_WaitForMultipleObjects_Event(numSessions, SessionEvents,
5845 if (code == WAIT_OBJECT_0)
5848 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numSessions))
5850 int abandonIdx = code - WAIT_ABANDONED_0;
5851 afsi_log("Error: smb_ServerWaiter (SessionEvents) event %d abandoned, errno %d\n", abandonIdx, GetLastError());
5854 if (code == WAIT_IO_COMPLETION)
5856 afsi_log("Error: smb_ServerWaiter (SessionEvents) WAIT_IO_COMPLETION\n");
5860 if (code == WAIT_TIMEOUT)
5862 afsi_log("Error: smb_ServerWaiter (SessionEvents) WAIT_TIMEOUT, errno %d\n", GetLastError());
5865 if (code == WAIT_FAILED)
5867 afsi_log("Error: smb_ServerWaiter (SessionEvents) WAIT_FAILED, errno %d\n", GetLastError());
5870 idx_session = code - WAIT_OBJECT_0;
5872 /* check idx range! */
5873 if (idx_session < 0 || idx_session > (sizeof(SessionEvents) / sizeof(SessionEvents[0])))
5875 /* this is fatal - log as much as possible */
5876 afsi_log("Fatal: session idx [ %d ] out of range.\n", idx_session);
5882 code = thrd_WaitForMultipleObjects_Event(numNCBs, NCBavails,
5884 if (code == WAIT_OBJECT_0)
5887 /* error checking */
5888 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numNCBs))
5890 int abandonIdx = code - WAIT_ABANDONED_0;
5891 afsi_log("Error: smb_ClientWaiter (NCBavails) event %d abandoned, errno %d\n", abandonIdx, GetLastError());
5894 if (code == WAIT_IO_COMPLETION)
5896 afsi_log("Error: smb_ClientWaiter (NCBavails) WAIT_IO_COMPLETION\n");
5900 if (code == WAIT_TIMEOUT)
5902 afsi_log("Error: smb_ClientWaiter (NCBavails) WAIT_TIMEOUT, errno %d\n", GetLastError());
5905 if (code == WAIT_FAILED)
5907 afsi_log("Error: smb_ClientWaiter (NCBavails) WAIT_FAILED, errno %d\n", GetLastError());
5910 idx_NCB = code - WAIT_OBJECT_0;
5912 /* check idx range! */
5913 if (idx_NCB < 0 || idx_NCB > (sizeof(NCBsessions) / sizeof(NCBsessions[0])))
5915 /* this is fatal - log as much as possible */
5916 afsi_log("Fatal: idx_NCB [ %d ] out of range.\n", idx_NCB);
5920 /* Link them together */
5921 NCBsessions[idx_NCB] = idx_session;
5924 ncbp = NCBs[idx_NCB];
5926 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
5928 ncbp->ncb_lsn = (unsigned char) LSNs[idx_session];
5929 ncbp->ncb_command = NCBRECV | ASYNCH;
5930 ncbp->ncb_lana_num = lanas[idx_session];
5932 ncbp->ncb_buffer = (unsigned char *) bufs[idx_NCB];
5933 ncbp->ncb_event = NCBevents[idx_NCB];
5934 ncbp->ncb_length = SMB_PACKETSIZE;
5937 ncbp->ncb_buffer = bufs[idx_NCB]->dos_pkt;
5938 ((smb_ncb_t*)ncbp)->orig_pkt = bufs[idx_NCB];
5939 ncbp->ncb_event = NCBreturns[0][idx_NCB];
5940 ncbp->ncb_length = SMB_PACKETSIZE;
5941 Netbios(ncbp, dos_ncb);
5947 * The top level loop for handling SMB request messages. Each server thread
5948 * has its own NCB and buffer for sending replies (outncbp, outbufp), but the
5949 * NCB and buffer for the incoming request are loaned to us.
5951 * Write Raw trickery starts here. When we get a Write Raw, we are supposed
5952 * to immediately send a request for the rest of the data. This must come
5953 * before any other traffic for that session, so we delay setting the session
5954 * event until that data has come in.
5956 void smb_Server(VOID *parmp)
5958 int myIdx = (int) parmp;
5962 smb_packet_t *outbufp;
5964 int idx_NCB, idx_session;
5973 outbufp = GetPacket();
5974 outbufp->ncbp = outncbp;
5978 /* check for demo expiration */
5980 unsigned long tod = time((void *) 0);
5981 if (tod > EXPIREDATE) {
5982 (*smb_MBfunc)(NULL, "AFS demo expiration",
5984 MB_OK|MB_ICONSTOP|MB_SETFOREGROUND);
5988 #endif /* !NOEXPIRE */
5990 code = thrd_WaitForMultipleObjects_Event(numNCBs, NCBreturns[myIdx],
5992 if (code == WAIT_OBJECT_0) {
5996 /* error checking */
5997 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numNCBs))
5999 int abandonIdx = code - WAIT_ABANDONED_0;
6000 afsi_log("Error: smb_Server ( NCBreturns[%d] ) event %d abandoned, errno %d\n", myIdx, abandonIdx, GetLastError());
6003 if (code == WAIT_IO_COMPLETION)
6005 afsi_log("Error: smb_Server ( NCBreturns[%d] ) WAIT_IO_COMPLETION\n", myIdx);
6009 if (code == WAIT_TIMEOUT)
6011 afsi_log("Error: smb_Server ( NCBreturns[%d] ) WAIT_TIMEOUT, errno %d\n", myIdx, GetLastError());
6014 if (code == WAIT_FAILED)
6016 afsi_log("Error: smb_Server ( NCBreturns[%d] ) WAIT_FAILED, errno %d\n", myIdx, GetLastError());
6019 idx_NCB = code - WAIT_OBJECT_0;
6021 /* check idx range! */
6022 if (idx_NCB < 0 || idx_NCB > (sizeof(NCBs) / sizeof(NCBs[0])))
6024 /* this is fatal - log as much as possible */
6025 afsi_log("Fatal: idx_NCB [ %d ] out of range.\n", idx_NCB);
6029 ncbp = NCBs[idx_NCB];
6031 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6033 idx_session = NCBsessions[idx_NCB];
6034 rc = ncbp->ncb_retcode;
6036 if (rc != NRC_PENDING && rc != NRC_GOODRET)
6037 osi_Log1(afsd_logp, "NCBRECV failure code %d", rc);
6040 case NRC_GOODRET: break;
6043 /* Can this happen? Or is it just my
6050 /* Client closed session */
6051 if (reportSessionStartups)
6053 afsi_log("session [ %d ] closed", idx_session);
6055 dead_sessions[idx_session] = TRUE;
6056 vcp = smb_FindVC(ncbp->ncb_lsn, 0, lanas[idx_session]);
6057 /* Should also release vcp. Also, would do
6058 * sanity check that all TID's are gone.
6060 * TODO: check if we could use LSNs[idx_session] instead,
6061 * also cleanup after dead vcp
6066 "dead_vcp already set, %x",
6068 if (!dead_vcp && !(vcp->flags & SMB_VCFLAG_ALREADYDEAD)) {
6070 "setting dead_vcp %x, user struct %x",
6073 vcp->flags |= SMB_VCFLAG_ALREADYDEAD;
6075 if (vcp->justLoggedOut) {
6077 loggedOutTime = vcp->logoffTime;
6079 strdup(vcp->justLoggedOut->unp->name);
6080 loggedOutUserp = vcp->justLoggedOut;
6081 lock_ObtainWrite(&smb_rctLock);
6082 loggedOutUserp->refCount++;
6083 lock_ReleaseWrite(&smb_rctLock);
6089 /* Treat as transient error */
6096 osi_Log1(smb_logp, "dispatch smb recv failed, message incomplete, ncb_length %d",
6098 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
6099 sprintf(s, "SMB message incomplete, length %d",
6102 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0,
6104 ncbp->ncb_length, ptbuf,
6106 DeregisterEventSource(h);
6109 "dispatch smb recv failed, message incomplete, ncb_length %d",
6112 "SMB message incomplete, "
6113 "length %d", ncbp->ncb_length);
6117 * We used to discard the packet.
6118 * Instead, try handling it normally.
6126 /* A weird error code. Log it, sleep, and
6128 if (vcp->errorCount++ > 3) {
6129 afsi_log("session [ %d ] closed, vcp->errorCount = %d", idx_session, vcp->errorCount);
6130 dead_sessions[idx_session] = TRUE;
6134 thrd_SetEvent(SessionEvents[idx_session]);
6139 /* Success, so now dispatch on all the data in the packet */
6141 smb_concurrentCalls++;
6142 if (smb_concurrentCalls > smb_maxObsConcurrentCalls)
6143 smb_maxObsConcurrentCalls = smb_concurrentCalls;
6145 vcp = smb_FindVC(ncbp->ncb_lsn, 0, ncbp->ncb_lana_num);
6147 * If at this point vcp is NULL (implies that packet was invalid)
6148 * then we are in big trouble. This means either :
6149 * a) we have the wrong NCB.
6150 * b) Netbios screwed up the call.
6151 * Obviously this implies that
6152 * ( LSNs[idx_session] != ncbp->ncb_lsn ||
6153 * lanas[idx_session] != ncbp->ncb_lana_num )
6154 * Either way, we can't do anything with this packet.
6155 * Log, sleep and resume.
6164 "LSNs[idx_session]=[%d],"
6165 "lanas[idx_session]=[%d],"
6166 "ncbp->ncb_lsn=[%d],"
6167 "ncbp->ncb_lana_num=[%d]",
6171 ncbp->ncb_lana_num);
6175 h = RegisterEventSource(NULL,AFS_DAEMON_EVENT_NAME);
6177 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1001, NULL,1,sizeof(*ncbp),ptbuf,(void*)ncbp);
6178 DeregisterEventSource(h);
6181 /* Also log in the trace log. */
6182 osi_Log4(afsd_logp, "Server: BAD VCP!"
6183 "LSNs[idx_session]=[%d],"
6184 "lanas[idx_session]=[%d],"
6185 "ncbp->ncb_lsn=[%d],"
6186 "ncbp->ncb_lana_num=[%d]",
6190 ncbp->ncb_lana_num);
6192 /* thrd_Sleep(1000); Don't bother sleeping */
6193 thrd_SetEvent(SessionEvents[idx_session]);
6194 smb_concurrentCalls--;
6199 vcp->errorCount = 0;
6200 bufp = (struct smb_packet *) ncbp->ncb_buffer;
6202 bufp = ((smb_ncb_t *) ncbp)->orig_pkt;
6203 /* copy whole packet to virtual memory */
6204 /*fprintf(stderr, "smb_Server: copying dos packet at 0x%x, "
6206 bufp->dos_pkt / 16, bufp);*/
6208 dosmemget(bufp->dos_pkt, ncbp->ncb_length, bufp->data);
6210 smbp = (smb_t *)bufp->data;
6213 #if !defined(DJGPP) && !defined(AFS_WIN32_ENV)
6217 if (smbp->com == 0x1d) {
6218 /* Special handling for Write Raw */
6219 raw_write_cont_t rwc;
6220 EVENT_HANDLE rwevent;
6221 char eventName[MAX_PATH];
6223 smb_DispatchPacket(vcp, bufp, outbufp, ncbp, &rwc);
6224 if (rwc.code == 0) {
6225 rwevent = thrd_CreateEvent(NULL, FALSE, FALSE, TEXT("smb_Server() rwevent"));
6226 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6227 afsi_log("Event Object Already Exists: %s", eventName);
6228 ncbp->ncb_command = NCBRECV | ASYNCH;
6229 ncbp->ncb_lsn = (unsigned char) vcp->lsn;
6230 ncbp->ncb_lana_num = vcp->lana;
6231 ncbp->ncb_buffer = rwc.buf;
6232 ncbp->ncb_length = 65535;
6233 ncbp->ncb_event = rwevent;
6237 Netbios(ncbp, dos_ncb);
6239 rcode = thrd_WaitForSingleObject_Event(rwevent, RAWTIMEOUT);
6240 thrd_CloseHandle(rwevent);
6242 thrd_SetEvent(SessionEvents[idx_session]);
6244 smb_CompleteWriteRaw(vcp, bufp, outbufp, ncbp, &rwc);
6245 } else if (smbp->com == 0xa0) {
6247 * Serialize the handling for NT Transact
6250 smb_DispatchPacket(vcp, bufp, outbufp, ncbp, NULL);
6251 thrd_SetEvent(SessionEvents[idx_session]);
6253 thrd_SetEvent(SessionEvents[idx_session]);
6254 /* TODO: what else needs to be serialized? */
6255 smb_DispatchPacket(vcp, bufp, outbufp, ncbp, NULL);
6257 #if !defined(DJGPP) && !defined(AFS_WIN95_ENV)
6259 __except( smb_ServerExceptionFilter() ) {
6263 smb_concurrentCalls--;
6266 thrd_SetEvent(NCBavails[idx_NCB]);
6271 * Exception filter for the server threads. If an exception occurs in the
6272 * dispatch routines, which is where exceptions are most common, then do a
6273 * force trace and give control to upstream exception handlers. Useful for
6276 #if !defined(DJGPP) && !defined(AFS_WIN95_ENV)
6277 DWORD smb_ServerExceptionFilter(void) {
6278 /* While this is not the best time to do a trace, if it succeeds, then
6279 * we have a trace (assuming tracing was enabled). Otherwise, this should
6280 * throw a second exception.
6285 ptbuf[0] = "Unhandled exception forcing trace";
6287 h = RegisterEventSource(NULL,AFS_DAEMON_EVENT_NAME);
6289 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1001, NULL,1,0,ptbuf,NULL);
6290 DeregisterEventSource(h);
6293 afsd_ForceTrace(TRUE);
6294 return EXCEPTION_CONTINUE_SEARCH;
6299 * Create a new NCB and associated events, packet buffer, and "space" buffer.
6300 * If the number of server threads is M, and the number of live sessions is
6301 * N, then the number of NCB's in use at any time either waiting for, or
6302 * holding, received messages is M + N, so that is how many NCB's get created.
6304 void InitNCBslot(int idx)
6306 struct smb_packet *bufp;
6307 EVENT_HANDLE retHandle;
6309 char eventName[MAX_PATH];
6311 osi_assert( idx < (sizeof(NCBs) / sizeof(NCBs[0])) );
6313 NCBs[idx] = GetNCB();
6314 sprintf(eventName,"NCBavails[%d]", idx);
6315 NCBavails[idx] = thrd_CreateEvent(NULL, FALSE, TRUE, eventName);
6316 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6317 afsi_log("Event Object Already Exists: %s", eventName);
6319 sprintf(eventName,"NCBevents[%d]", idx);
6320 NCBevents[idx] = thrd_CreateEvent(NULL, TRUE, FALSE, eventName);
6321 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6322 afsi_log("Event Object Already Exists: %s", eventName);
6324 sprintf(eventName,"NCBReturns[0<=i<smb_NumServerThreads][%d]", idx);
6325 retHandle = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6326 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6327 afsi_log("Event Object Already Exists: %s", eventName);
6328 for (i=0; i<smb_NumServerThreads; i++)
6329 NCBreturns[i][idx] = retHandle;
6331 bufp->spacep = cm_GetSpace();
6335 /* listen for new connections */
6336 void smb_Listener(void *parmp)
6344 char rname[NCBNAMSZ+1];
6345 char cname[MAX_COMPUTERNAME_LENGTH+1];
6346 int cnamelen = MAX_COMPUTERNAME_LENGTH+1;
6351 int lana = (int) parmp;
6355 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6358 /* retrieve computer name */
6359 GetComputerName(cname, &cnamelen);
6363 memset(ncbp, 0, sizeof(NCB));
6367 /* check for demo expiration */
6369 unsigned long tod = time((void *) 0);
6370 if (tod > EXPIREDATE) {
6371 (*smb_MBfunc)(NULL, "AFS demo expiration",
6373 MB_OK|MB_ICONSTOP|MB_SETFOREGROUND);
6381 #endif /* !NOEXPIRE */
6383 ncbp->ncb_command = NCBLISTEN;
6384 ncbp->ncb_rto = 0; /* No receive timeout */
6385 ncbp->ncb_sto = 0; /* No send timeout */
6387 /* pad out with spaces instead of null termination */
6388 len = strlen(smb_localNamep);
6389 strncpy(ncbp->ncb_name, smb_localNamep, NCBNAMSZ);
6390 for(i=len; i<NCBNAMSZ; i++) ncbp->ncb_name[i] = ' ';
6392 strcpy(ncbp->ncb_callname, "*");
6393 for(i=1; i<NCBNAMSZ; i++) ncbp->ncb_callname[i] = ' ';
6395 ncbp->ncb_lana_num = lana;
6398 code = Netbios(ncbp);
6400 code = Netbios(ncbp, dos_ncb);
6405 /* terminate if shutdown flag is set */
6406 if (smbShutdownFlag == 1) {
6417 fprintf(stderr, "NCBLISTEN lana=%d failed with code %d\n",
6418 ncbp->ncb_lana_num, code);
6419 osi_Log2(0, "NCBLISTEN lana=%d failed with code %d",
6420 ncbp->ncb_lana_num, code);
6421 fprintf(stderr, "\nClient exiting due to network failure "
6422 "(possibly due to power-saving mode)\n");
6423 fprintf(stderr, "Please restart client.\n");
6424 afs_exit(AFS_EXITCODE_NETWORK_FAILURE);
6428 /* check for remote conns */
6429 /* first get remote name and insert null terminator */
6430 memcpy(rname, ncbp->ncb_callname, NCBNAMSZ);
6431 for (i=NCBNAMSZ; i>0; i--) {
6432 if (rname[i-1] != ' ' && rname[i-1] != 0) {
6438 /* compare with local name */
6440 if (strncmp(rname, cname, NCBNAMSZ) != 0)
6441 flags |= SMB_VCFLAG_REMOTECONN;
6443 osi_Log1(afsd_logp, "New session lsn %d", ncbp->ncb_lsn);
6445 lock_ObtainMutex(&smb_ListenerLock);
6447 /* New generation */
6450 /* Log session startup */
6452 fprintf(stderr, "New session(ncb_lsn,ncb_lana_num) %d,%d starting from host "
6454 ncbp->ncb_lsn,ncbp->ncb_lana_num, rname);
6456 afsi_log("New session(ncb_lsn,ncb_lana_num) (%d,%d) starting from host %s, %d ongoing ops",
6457 ncbp->ncb_lsn,ncbp->ncb_lana_num, rname, ongoingOps);
6459 if (reportSessionStartups) {
6465 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
6466 sprintf(s, "SMB session startup, %d ongoing ops", ongoingOps);
6468 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1004, NULL,
6470 DeregisterEventSource(h);
6472 afsi_log("NCBLISTEN completed, call from %s",rname);
6473 osi_Log1(afsd_logp, "SMB session startup, %d ongoing ops",
6476 fprintf(stderr, "%s: New session %d starting from host %s\n",
6477 asctime(localtime(&now)), ncbp->ncb_lsn, rname);
6482 /* now ncbp->ncb_lsn is the connection ID */
6483 vcp = smb_FindVC(ncbp->ncb_lsn, SMB_FLAG_CREATE, ncbp->ncb_lana_num);
6484 vcp->flags |= flags;
6485 strcpy(vcp->rname, rname);
6487 /* Allocate slot in session arrays */
6488 /* Re-use dead session if possible, otherwise add one more */
6489 /* But don't look at session[0], it is reserved */
6490 for (i = 1; i < numSessions; i++) {
6491 if (dead_sessions[i]) {
6492 afsi_log("connecting to dead session [ %d ]", i);
6493 dead_sessions[i] = FALSE;
6498 /* assert that we do not exceed the maximum number of sessions or NCBs.
6499 * we should probably want to wait for a session to be freed in case
6503 osi_assert(i < Sessionmax && numNCBs < NCBmax - 1);
6505 LSNs[i] = ncbp->ncb_lsn;
6506 lanas[i] = ncbp->ncb_lana_num;
6508 if (i == numSessions) {
6509 /* Add new NCB for new session */
6510 char eventName[MAX_PATH];
6512 osi_Log1(afsd_logp, "smb_Listener creating new session %d", i);
6514 InitNCBslot(numNCBs);
6516 thrd_SetEvent(NCBavails[0]);
6517 thrd_SetEvent(NCBevents[0]);
6518 for (j = 0; j < smb_NumServerThreads; j++)
6519 thrd_SetEvent(NCBreturns[j][0]);
6520 /* Also add new session event */
6521 sprintf(eventName, "SessionEvents[%d]", i);
6522 SessionEvents[i] = thrd_CreateEvent(NULL, FALSE, TRUE, eventName);
6523 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6524 afsi_log("Event Object Already Exists: %s", eventName);
6526 afsi_log("increasing numNCBs [ %d ] numSessions [ %d ]", numNCBs, numSessions);
6527 thrd_SetEvent(SessionEvents[0]);
6529 thrd_SetEvent(SessionEvents[i]);
6532 lock_ReleaseMutex(&smb_ListenerLock);
6534 } /* dispatch while loop */
6537 /* initialize Netbios */
6538 void smb_NetbiosInit()
6544 int i, lana, code, l;
6546 int delname_tried=0;
6549 OSVERSIONINFO Version;
6551 /* AFAIK, this is the default for the ms loopback adapter.*/
6552 unsigned char kWLA_MAC[6] = { 0x02, 0x00, 0x4c, 0x4f, 0x4f, 0x50 };
6553 /*******************************************************************/
6555 /* Get the version of Windows */
6556 memset(&Version, 0x00, sizeof(Version));
6557 Version.dwOSVersionInfoSize = sizeof(Version);
6558 GetVersionEx(&Version);
6560 /* setup the NCB system */
6563 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6567 if (smb_LANadapter == -1) {
6568 ncbp->ncb_command = NCBENUM;
6569 ncbp->ncb_buffer = (PUCHAR)&lana_list;
6570 ncbp->ncb_length = sizeof(lana_list);
6571 code = Netbios(ncbp);
6573 sprintf(s, "Netbios NCBENUM error code %d", code);
6575 osi_panic(s, __FILE__, __LINE__);
6579 lana_list.length = 1;
6580 lana_list.lana[0] = smb_LANadapter;
6583 for (i = 0; i < lana_list.length; i++) {
6584 /* reset the adaptor: in Win32, this is required for every process, and
6585 * acts as an init call, not as a real hardware reset.
6587 ncbp->ncb_command = NCBRESET;
6588 ncbp->ncb_callname[0] = 100;
6589 ncbp->ncb_callname[2] = 100;
6590 ncbp->ncb_lana_num = lana_list.lana[i];
6591 code = Netbios(ncbp);
6593 code = ncbp->ncb_retcode;
6595 sprintf(s, "Netbios NCBRESET lana %d error code %d", lana_list.lana[i], code);
6597 lana_list.lana[i] = 255; /* invalid lana */
6599 sprintf(s, "Netbios NCBRESET lana %d succeeded", lana_list.lana[i]);
6604 /* for DJGPP, there is no NCBENUM and NCBRESET is a real reset. so
6605 we will just fake the LANA list */
6606 if (smb_LANadapter == -1) {
6607 for (i = 0; i < 8; i++)
6608 lana_list.lana[i] = i;
6609 lana_list.length = 8;
6612 lana_list.length = 1;
6613 lana_list.lana[0] = smb_LANadapter;
6617 /* and declare our name so we can receive connections */
6618 memset(ncbp, 0, sizeof(*ncbp));
6619 len=lstrlen(smb_localNamep);
6620 memset(smb_sharename,' ',NCBNAMSZ);
6621 memcpy(smb_sharename,smb_localNamep,len);
6622 sprintf(s, "lana_list.length %d", lana_list.length);
6625 /* Keep the name so we can unregister it later */
6626 for (l = 0; l < lana_list.length; l++) {
6627 lana = lana_list.lana[l];
6629 ncbp->ncb_command = NCBADDNAME;
6630 ncbp->ncb_lana_num = lana;
6631 memcpy(ncbp->ncb_name,smb_sharename,NCBNAMSZ);
6633 code = Netbios(ncbp);
6635 code = Netbios(ncbp, dos_ncb);
6638 afsi_log("Netbios NCBADDNAME lana=%d code=%d retcode=%d complete=%d",
6639 lana, code, ncbp->ncb_retcode,ncbp->ncb_cmd_cplt);
6641 char name[NCBNAMSZ+1];
6643 memcpy(name,ncbp->ncb_name,NCBNAMSZ);
6644 afsi_log("Netbios NCBADDNAME added new name >%s<",name);
6647 if (code == 0) code = ncbp->ncb_retcode;
6649 afsi_log("Netbios NCBADDNAME succeeded on lana %d\n", lana);
6651 /* we only use one LANA with djgpp */
6652 lana_list.lana[0] = lana;
6653 lana_list.length = 1;
6657 sprintf(s, "Netbios NCBADDNAME lana %d error code %d", lana, code);
6659 if (code == NRC_BRIDGE) { /* invalid LANA num */
6660 lana_list.lana[l] = 255;
6663 else if (code == NRC_DUPNAME) {
6664 afsi_log("Name already exists; try to delete it");
6665 memset(ncbp, 0, sizeof(*ncbp));
6666 ncbp->ncb_command = NCBDELNAME;
6667 memcpy(ncbp->ncb_name,smb_sharename,NCBNAMSZ);
6668 ncbp->ncb_lana_num = lana;
6670 code = Netbios(ncbp);
6672 code = Netbios(ncbp, dos_ncb);
6674 if (code == 0) code = ncbp->ncb_retcode;
6676 sprintf(s, "Netbios NCBDELNAME lana %d error code %d\n", lana, code);
6679 if (code != 0 || delname_tried) {
6680 lana_list.lana[l] = 255;
6682 else if (code == 0) {
6683 if (!delname_tried) {
6691 sprintf(s, "Netbios NCBADDNAME lana %d error code %d", lana, code);
6693 lana_list.lana[l] = 255; /* invalid lana */
6694 osi_panic(s, __FILE__, __LINE__);
6698 lana_found = 1; /* at least one worked */
6705 osi_assert(lana_list.length >= 0);
6707 sprintf(s, "No valid LANA numbers found!");
6708 osi_panic(s, __FILE__, __LINE__);
6711 /* we're done with the NCB now */
6715 void smb_Init(osi_log_t *logp, char *snamep, int useV3, int LANadapt,
6732 EVENT_HANDLE retHandle;
6733 char eventName[MAX_PATH];
6736 smb_MBfunc = aMBfunc;
6740 /* check for demo expiration */
6742 unsigned long tod = time((void *) 0);
6743 if (tod > EXPIREDATE) {
6745 (*smb_MBfunc)(NULL, "AFS demo expiration", "afsd",
6746 MB_OK|MB_ICONSTOP|MB_SETFOREGROUND);
6749 fprintf(stderr, "AFS demo expiration\n");
6754 #endif /* !NOEXPIRE */
6757 smb_LANadapter = LANadapt;
6759 /* Initialize smb_localZero */
6760 myTime.tm_isdst = -1; /* compute whether on DST or not */
6761 myTime.tm_year = 70;
6767 smb_localZero = mktime(&myTime);
6769 /* Initialize kludge-GMT */
6770 smb_CalculateNowTZ();
6772 /* initialize the remote debugging log */
6775 /* remember the name */
6776 len = strlen(snamep);
6777 smb_localNamep = malloc(len+1);
6778 strcpy(smb_localNamep, snamep);
6779 afsi_log("smb_localNamep is >%s<", smb_localNamep);
6781 /* and the global lock */
6782 lock_InitializeRWLock(&smb_globalLock, "smb global lock");
6783 lock_InitializeRWLock(&smb_rctLock, "smb refct and tree struct lock");
6785 /* Raw I/O data structures */
6786 lock_InitializeMutex(&smb_RawBufLock, "smb raw buffer lock");
6788 lock_InitializeMutex(&smb_ListenerLock, "smb listener lock");
6790 /* 4 Raw I/O buffers */
6792 smb_RawBufs = calloc(65536,1);
6793 *((char **)smb_RawBufs) = NULL;
6794 for (i=0; i<3; i++) {
6795 char *rawBuf = calloc(65536,1);
6796 *((char **)rawBuf) = smb_RawBufs;
6797 smb_RawBufs = rawBuf;
6800 npar = 65536 >> 4; /* number of paragraphs */
6801 seg = __dpmi_allocate_dos_memory(npar, &smb_RawBufSel[0]);
6803 afsi_log("Cannot allocate %d paragraphs of DOS memory",
6805 osi_panic("",__FILE__,__LINE__);
6808 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X",
6811 smb_RawBufs = (seg * 16) + 0; /* DOS physical address */
6813 _farpokel(_dos_ds, smb_RawBufs, NULL);
6814 for (i=0; i<SMB_RAW_BUFS-1; i++) {
6815 npar = 65536 >> 4; /* number of paragraphs */
6816 seg = __dpmi_allocate_dos_memory(npar, &smb_RawBufSel[i+1]);
6818 afsi_log("Cannot allocate %d paragraphs of DOS memory",
6820 osi_panic("",__FILE__,__LINE__);
6823 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X",
6826 rawBuf = (seg * 16) + 0; /* DOS physical address */
6827 /*_farpokel(_dos_ds, smb_RawBufs, smb_RawBufs);*/
6828 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
6829 smb_RawBufs = rawBuf;
6833 /* global free lists */
6834 smb_ncbFreeListp = NULL;
6835 smb_packetFreeListp = NULL;
6839 /* Initialize listener and server structures */
6840 memset(dead_sessions, 0, sizeof(dead_sessions));
6841 sprintf(eventName, "SessionEvents[0]");
6842 SessionEvents[0] = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6843 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6844 afsi_log("Event Object Already Exists: %s", eventName);
6846 smb_NumServerThreads = nThreads;
6847 sprintf(eventName, "NCBavails[0]");
6848 NCBavails[0] = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6849 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6850 afsi_log("Event Object Already Exists: %s", eventName);
6851 sprintf(eventName, "NCBevents[0]");
6852 NCBevents[0] = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6853 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6854 afsi_log("Event Object Already Exists: %s", eventName);
6855 NCBreturns = malloc(nThreads * sizeof(EVENT_HANDLE *));
6856 sprintf(eventName, "NCBreturns[0<=i<smb_NumServerThreads][0]");
6857 retHandle = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6858 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6859 afsi_log("Event Object Already Exists: %s", eventName);
6860 for (i = 0; i < smb_NumServerThreads; i++) {
6861 NCBreturns[i] = malloc(NCBmax * sizeof(EVENT_HANDLE));
6862 NCBreturns[i][0] = retHandle;
6864 for (i = 1; i <= nThreads; i++)
6866 numNCBs = nThreads + 1;
6868 /* Initialize dispatch table */
6869 memset(&smb_dispatchTable, 0, sizeof(smb_dispatchTable));
6870 smb_dispatchTable[0x00].procp = smb_ReceiveCoreMakeDir;
6871 smb_dispatchTable[0x01].procp = smb_ReceiveCoreRemoveDir;
6872 smb_dispatchTable[0x02].procp = smb_ReceiveCoreOpen;
6873 smb_dispatchTable[0x03].procp = smb_ReceiveCoreCreate;
6874 smb_dispatchTable[0x04].procp = smb_ReceiveCoreClose;
6875 smb_dispatchTable[0x05].procp = smb_ReceiveCoreFlush;
6876 smb_dispatchTable[0x06].procp = smb_ReceiveCoreUnlink;
6877 smb_dispatchTable[0x07].procp = smb_ReceiveCoreRename;
6878 smb_dispatchTable[0x08].procp = smb_ReceiveCoreGetFileAttributes;
6879 smb_dispatchTable[0x09].procp = smb_ReceiveCoreSetFileAttributes;
6880 smb_dispatchTable[0x0a].procp = smb_ReceiveCoreRead;
6881 smb_dispatchTable[0x0b].procp = smb_ReceiveCoreWrite;
6882 smb_dispatchTable[0x0c].procp = smb_ReceiveCoreLockRecord;
6883 smb_dispatchTable[0x0d].procp = smb_ReceiveCoreUnlockRecord;
6884 smb_dispatchTable[0x0e].procp = smb_SendCoreBadOp; /* create temporary */
6885 smb_dispatchTable[0x0f].procp = smb_ReceiveCoreCreate;
6886 smb_dispatchTable[0x10].procp = smb_ReceiveCoreCheckPath;
6887 smb_dispatchTable[0x11].procp = smb_SendCoreBadOp; /* process exit */
6888 smb_dispatchTable[0x12].procp = smb_ReceiveCoreSeek;
6889 smb_dispatchTable[0x1a].procp = smb_ReceiveCoreReadRaw;
6890 /* Set NORESPONSE because smb_ReceiveCoreReadRaw() does the responses itself */
6891 smb_dispatchTable[0x1a].flags |= SMB_DISPATCHFLAG_NORESPONSE;
6892 smb_dispatchTable[0x1d].procp = smb_ReceiveCoreWriteRawDummy;
6893 smb_dispatchTable[0x22].procp = smb_ReceiveV3SetAttributes;
6894 smb_dispatchTable[0x23].procp = smb_ReceiveV3GetAttributes;
6895 smb_dispatchTable[0x24].procp = smb_ReceiveV3LockingX;
6896 smb_dispatchTable[0x24].flags |= SMB_DISPATCHFLAG_CHAINED;
6897 smb_dispatchTable[0x29].procp = smb_SendCoreBadOp; /* copy file */
6898 smb_dispatchTable[0x2b].procp = smb_ReceiveCoreEcho;
6899 /* Set NORESPONSE because smb_ReceiveCoreEcho() does the responses itself */
6900 smb_dispatchTable[0x2b].flags |= SMB_DISPATCHFLAG_NORESPONSE;
6901 smb_dispatchTable[0x2d].procp = smb_ReceiveV3OpenX;
6902 smb_dispatchTable[0x2d].flags |= SMB_DISPATCHFLAG_CHAINED;
6903 smb_dispatchTable[0x2e].procp = smb_ReceiveV3ReadX;
6904 smb_dispatchTable[0x2e].flags |= SMB_DISPATCHFLAG_CHAINED;
6905 smb_dispatchTable[0x32].procp = smb_ReceiveV3Tran2A; /* both are same */
6906 smb_dispatchTable[0x32].flags |= SMB_DISPATCHFLAG_NORESPONSE;
6907 smb_dispatchTable[0x33].procp = smb_ReceiveV3Tran2A;
6908 smb_dispatchTable[0x33].flags |= SMB_DISPATCHFLAG_NORESPONSE;
6909 smb_dispatchTable[0x34].procp = smb_ReceiveV3FindClose;
6910 smb_dispatchTable[0x35].procp = smb_ReceiveV3FindNotifyClose;
6911 smb_dispatchTable[0x70].procp = smb_ReceiveCoreTreeConnect;
6912 smb_dispatchTable[0x71].procp = smb_ReceiveCoreTreeDisconnect;
6913 smb_dispatchTable[0x72].procp = smb_ReceiveNegotiate;
6914 smb_dispatchTable[0x73].procp = smb_ReceiveV3SessionSetupX;
6915 smb_dispatchTable[0x73].flags |= SMB_DISPATCHFLAG_CHAINED;
6916 smb_dispatchTable[0x74].procp = smb_ReceiveV3UserLogoffX;
6917 smb_dispatchTable[0x74].flags |= SMB_DISPATCHFLAG_CHAINED;
6918 smb_dispatchTable[0x75].procp = smb_ReceiveV3TreeConnectX;
6919 smb_dispatchTable[0x75].flags |= SMB_DISPATCHFLAG_CHAINED;
6920 smb_dispatchTable[0x80].procp = smb_ReceiveCoreGetDiskAttributes;
6921 smb_dispatchTable[0x81].procp = smb_ReceiveCoreSearchDir;
6922 smb_dispatchTable[0xA0].procp = smb_ReceiveNTTransact;
6923 smb_dispatchTable[0xA2].procp = smb_ReceiveNTCreateX;
6924 smb_dispatchTable[0xA2].flags |= SMB_DISPATCHFLAG_CHAINED;
6925 smb_dispatchTable[0xA4].procp = smb_ReceiveNTCancel;
6926 smb_dispatchTable[0xA4].flags |= SMB_DISPATCHFLAG_NORESPONSE;
6927 smb_dispatchTable[0xc0].procp = smb_SendCoreBadOp;
6928 smb_dispatchTable[0xc1].procp = smb_SendCoreBadOp;
6929 smb_dispatchTable[0xc2].procp = smb_SendCoreBadOp;
6930 smb_dispatchTable[0xc3].procp = smb_SendCoreBadOp;
6931 for(i=0xd0; i<= 0xd7; i++) {
6932 smb_dispatchTable[i].procp = smb_SendCoreBadOp;
6935 /* setup tran 2 dispatch table */
6936 smb_tran2DispatchTable[0].procp = smb_ReceiveTran2Open;
6937 smb_tran2DispatchTable[1].procp = smb_ReceiveTran2SearchDir; /* FindFirst */
6938 smb_tran2DispatchTable[2].procp = smb_ReceiveTran2SearchDir; /* FindNext */
6939 smb_tran2DispatchTable[3].procp = smb_ReceiveTran2QFSInfo;
6940 smb_tran2DispatchTable[4].procp = smb_ReceiveTran2SetFSInfo;
6941 smb_tran2DispatchTable[5].procp = smb_ReceiveTran2QPathInfo;
6942 smb_tran2DispatchTable[6].procp = smb_ReceiveTran2SetPathInfo;
6943 smb_tran2DispatchTable[7].procp = smb_ReceiveTran2QFileInfo;
6944 smb_tran2DispatchTable[8].procp = smb_ReceiveTran2SetFileInfo;
6945 smb_tran2DispatchTable[9].procp = smb_ReceiveTran2FSCTL;
6946 smb_tran2DispatchTable[10].procp = smb_ReceiveTran2IOCTL;
6947 smb_tran2DispatchTable[11].procp = smb_ReceiveTran2FindNotifyFirst;
6948 smb_tran2DispatchTable[12].procp = smb_ReceiveTran2FindNotifyNext;
6949 smb_tran2DispatchTable[13].procp = smb_ReceiveTran2MKDir;
6953 /* Start listeners, waiters, servers, and daemons */
6955 for (i = 0; i < lana_list.length; i++) {
6956 if (lana_list.lana[i] == 255) continue;
6957 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_Listener,
6958 (void*)lana_list.lana[i], 0, &lpid, "smb_Listener");
6959 osi_assert(phandle != NULL);
6960 thrd_CloseHandle(phandle);
6964 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_ClientWaiter,
6965 NULL, 0, &lpid, "smb_ClientWaiter");
6966 osi_assert(phandle != NULL);
6967 thrd_CloseHandle(phandle);
6970 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_ServerWaiter,
6971 NULL, 0, &lpid, "smb_ServerWaiter");
6972 osi_assert(phandle != NULL);
6973 thrd_CloseHandle(phandle);
6975 for (i=0; i<nThreads; i++) {
6976 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_Server,
6977 (void *) i, 0, &lpid, "smb_Server");
6978 osi_assert(phandle != NULL);
6979 thrd_CloseHandle(phandle);
6982 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_Daemon,
6983 NULL, 0, &lpid, "smb_Daemon");
6984 osi_assert(phandle != NULL);
6985 thrd_CloseHandle(phandle);
6987 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_WaitingLocksDaemon,
6988 NULL, 0, &lpid, "smb_WaitingLocksDaemon");
6989 osi_assert(phandle != NULL);
6990 thrd_CloseHandle(phandle);
6999 void smb_Shutdown(void)
7008 /*fprintf(stderr, "Entering smb_Shutdown\n");*/
7010 /* setup the NCB system */
7013 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
7016 /* Block new sessions by setting shutdown flag */
7017 smbShutdownFlag = 1;
7019 /* Hang up all sessions */
7020 memset((char *)ncbp, 0, sizeof(NCB));
7021 for (i = 1; i < numSessions; i++)
7023 if (dead_sessions[i])
7026 /*fprintf(stderr, "NCBHANGUP session %d LSN %d\n", i, LSNs[i]);*/
7027 ncbp->ncb_command = NCBHANGUP;
7028 ncbp->ncb_lana_num = lanas[i]; /*smb_LANadapter;*/
7029 ncbp->ncb_lsn = LSNs[i];
7031 code = Netbios(ncbp);
7033 code = Netbios(ncbp, dos_ncb);
7035 /*fprintf(stderr, "returned from NCBHANGUP session %d LSN %d\n", i, LSNs[i]);*/
7036 if (code == 0) code = ncbp->ncb_retcode;
7038 osi_Log1(afsd_logp, "Netbios NCBHANGUP error code %d", code);
7039 fprintf(stderr, "Session %d Netbios NCBHANGUP error code %d", i, code);
7043 /* Delete Netbios name */
7044 memset((char *)ncbp, 0, sizeof(NCB));
7045 for (i = 0; i < lana_list.length; i++) {
7046 if (lana_list.lana[i] == 255) continue;
7047 ncbp->ncb_command = NCBDELNAME;
7048 ncbp->ncb_lana_num = lana_list.lana[i];
7049 memcpy(ncbp->ncb_name,smb_sharename,NCBNAMSZ);
7051 code = Netbios(ncbp);
7053 code = Netbios(ncbp, dos_ncb);
7055 if (code == 0) code = ncbp->ncb_retcode;
7057 fprintf(stderr, "Netbios NCBDELNAME lana %d error code %d",
7058 ncbp->ncb_lana_num, code);
7064 /* Get the UNC \\<servername>\<sharename> prefix. */
7065 char *smb_GetSharename()
7069 /* Make sure we have been properly initialized. */
7070 if (smb_localNamep == NULL)
7073 /* Allocate space for \\<servername>\<sharename>, plus the
7076 name = malloc(strlen(smb_localNamep) + strlen("ALL") + 4);
7077 sprintf(name, "\\\\%s\\%s", smb_localNamep, "ALL");
7083 void smb_LogPacket(smb_packet_t *packet)
7086 unsigned length, paramlen, datalen, i, j;
7088 char hex[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
7092 osi_Log0(afsd_logp, "*** SMB packet dump ***");
7094 vp = (BYTE *) packet->data;
7096 datalen = *((WORD*)(vp + (paramlen = ((unsigned)*(vp+20)) << 1)));
7097 length = paramlen + 2 + datalen;
7100 for(i=0;i < length; i+=16)
7102 memset( buf, ' ', 80 );
7107 buf[strlen(buf)] = ' ';
7109 cp = (BYTE*) buf + 7;
7111 for(j=0;j < 16 && (i+j)<length; j++)
7113 *(cp++) = hex[vp[i+j] >> 4];
7114 *(cp++) = hex[vp[i+j] & 0xf];
7124 for(j=0;j < 16 && (i+j)<length;j++)
7126 *(cp++) = ( 32 <= vp[i+j] && 128 > vp[i+j] )? vp[i+j]:'.';
7137 osi_Log0( afsd_logp, buf );
7140 osi_Log0(afsd_logp, "*** End SMB packet dump ***");
7144 #endif /* NOTSERVICE */
7146 int smb_DumpVCP(FILE *outputFile, char *cookie)
7153 lock_ObtainRead(&smb_rctLock);
7155 for(vcp = smb_allVCsp; vcp; vcp=vcp->nextp)
7159 sprintf(output, "%s vcp=0x%08X, refCount=%d, flags=%d, vcID=%d, lsn=%d, uidCounter=%d, tidCounter=%d, fidCounter=%d\n",
7160 cookie, vcp, vcp->refCount, vcp->flags, vcp->vcID, vcp->lsn, vcp->uidCounter, vcp->tidCounter, vcp->fidCounter);
7161 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7163 for(fidp = vcp->fidsp; fidp; fidp = (smb_fid_t *) osi_QNext(&fidp->q))
7165 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",
7166 cookie, fidp, fidp->refCount, fidp->fid, fidp->vcp, fidp->scp, fidp->ioctlp,
7167 fidp->NTopen_pathp ? fidp->NTopen_pathp : "NULL",
7168 fidp->NTopen_wholepathp ? fidp->NTopen_wholepathp : "NULL");
7169 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7172 sprintf(output, "done dumping fidsp\n");
7173 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7176 lock_ReleaseRead(&smb_rctLock);