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 #include <afs/param.h>
18 #include <sys/timeb.h>
34 #include "lanahelper.h"
36 /* These characters are illegal in Windows filenames */
37 static char *illegalChars = "\\/:*?\"<>|";
38 BOOL isWindows2000 = FALSE;
40 smb_vc_t *dead_vcp = NULL;
41 smb_vc_t *active_vcp = NULL;
43 /* TODO; logout mechanism needs to be thread-safe */
44 char *loggedOutName = NULL;
45 smb_user_t *loggedOutUserp = NULL;
46 unsigned long loggedOutTime;
48 int smbShutdownFlag = 0;
50 int smb_LogoffTokenTransfer;
51 unsigned long smb_LogoffTransferTimeout;
53 DWORD last_msg_time = 0;
57 unsigned int sessionGen = 0;
59 extern void afsi_log(char *pattern, ...);
60 extern HANDLE afsi_file;
62 osi_hyper_t hzero = {0, 0};
63 osi_hyper_t hones = {0xFFFFFFFF, -1};
66 osi_rwlock_t smb_globalLock;
67 osi_rwlock_t smb_rctLock;
68 osi_mutex_t smb_ListenerLock;
71 unsigned char smb_sharename[NCBNAMSZ+1] = {0};
74 long smb_maxObsConcurrentCalls=0;
75 long smb_concurrentCalls=0;
77 smb_dispatch_t smb_dispatchTable[SMB_NOPCODES];
79 smb_packet_t *smb_packetFreeListp;
80 smb_ncb_t *smb_ncbFreeListp;
82 int smb_NumServerThreads;
84 int numNCBs, numSessions, numVCs;
86 int smb_maxVCPerServer;
87 int smb_maxMpxRequests;
89 int smb_authType = SMB_AUTH_EXTENDED; /* type of SMB auth to use. One of SMB_AUTH_* */
91 ULONG smb_lsaSecPackage;
92 LSA_STRING smb_lsaLogonOrigin;
94 #define NCBmax MAXIMUM_WAIT_OBJECTS
95 EVENT_HANDLE NCBavails[NCBmax], NCBevents[NCBmax];
96 EVENT_HANDLE **NCBreturns;
97 DWORD NCBsessions[NCBmax];
99 struct smb_packet *bufs[NCBmax];
101 #define Sessionmax MAXIMUM_WAIT_OBJECTS
102 EVENT_HANDLE SessionEvents[Sessionmax];
103 unsigned short LSNs[Sessionmax];
104 int lanas[Sessionmax];
105 BOOL dead_sessions[Sessionmax];
109 osi_mutex_t smb_RawBufLock;
111 #define SMB_RAW_BUFS 4
113 int smb_RawBufSel[SMB_RAW_BUFS];
118 #define SMB_MASKFLAG_TILDE 1
119 #define SMB_MASKFLAG_CASEFOLD 2
121 #define RAWTIMEOUT INFINITE
124 typedef struct raw_write_cont {
137 /* dir search stuff */
138 long smb_dirSearchCounter = 1;
139 smb_dirSearch_t *smb_firstDirSearchp;
140 smb_dirSearch_t *smb_lastDirSearchp;
142 /* hide dot files? */
143 int smb_hideDotFiles;
145 /* global state about V3 protocols */
146 int smb_useV3; /* try to negotiate V3 */
149 static showErrors = 1;
150 /* MessageBox or something like it */
151 int (_stdcall *smb_MBfunc)(HWND, LPCTSTR, LPCTSTR, UINT) = NULL;
152 extern HANDLE WaitToTerminate;
156 * Time in Unix format of midnight, 1/1/1970 local time.
157 * When added to dosUTime, gives Unix (AFS) time.
161 /* Time difference for converting to kludge-GMT */
164 char *smb_localNamep = NULL;
166 smb_vc_t *smb_allVCsp;
168 smb_username_t *usernamesp = NULL;
170 smb_waitingLock_t *smb_allWaitingLocks;
173 void smb_DispatchPacket(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp,
174 NCB *ncbp, raw_write_cont_t *rwcp);
175 void smb_NetbiosInit();
177 #ifndef AFS_WIN95_ENV
178 DWORD smb_ServerExceptionFilter(void);
181 extern char cm_HostName[];
182 extern char cm_confDir[];
186 #define LPTSTR char *
187 #define GetComputerName(str, sizep) \
188 strcpy((str), cm_HostName); \
189 *(sizep) = strlen(cm_HostName)
192 extern char AFSConfigKeyName[];
194 char smb_ServerDomainName[MAX_COMPUTERNAME_LENGTH + 1] = ""; /* domain name */
195 int smb_ServerDomainNameLength = 0;
196 char smb_ServerOS[] = "Windows 5.0"; /* Faux OS String */
197 int smb_ServerOSLength = sizeof(smb_ServerOS);
198 char smb_ServerLanManager[] = "Windows 2000 LAN Manager"; /* Faux LAN Manager string */
199 int smb_ServerLanManagerLength = sizeof(smb_ServerLanManager);
201 /* Faux server GUID. This is never checked. */
202 GUID smb_ServerGUID = { 0x40015cb8, 0x058a, 0x44fc, { 0xae, 0x7e, 0xbb, 0x29, 0x52, 0xee, 0x7e, 0xff }};
207 * To build an expiring version, comment out the definition of NOEXPIRE,
208 * and set the definition of EXPIREDATE to the desired value.
211 #define EXPIREDATE 834000000 /* Wed Jun 5 1996 */
214 char * myCrt_Dispatch(int i)
219 return "unknown SMB op";
221 return "(00)ReceiveCoreMakeDir";
223 return "(01)ReceiveCoreRemoveDir";
225 return "(02)ReceiveCoreOpen";
227 return "(03)ReceiveCoreCreate";
229 return "(04)ReceiveCoreClose";
231 return "(05)ReceiveCoreFlush";
233 return "(06)ReceiveCoreUnlink";
235 return "(07)ReceiveCoreRename";
237 return "(08)ReceiveCoreGetFileAttributes";
239 return "(09)ReceiveCoreSetFileAttributes";
241 return "(0a)ReceiveCoreRead";
243 return "(0b)ReceiveCoreWrite";
245 return "(0c)ReceiveCoreLockRecord";
247 return "(0d)ReceiveCoreUnlockRecord";
249 return "(0e)SendCoreBadOp";
251 return "(0f)ReceiveCoreCreate";
253 return "(10)ReceiveCoreCheckPath";
255 return "(11)SendCoreBadOp";
257 return "(12)ReceiveCoreSeek";
259 return "(1a)ReceiveCoreReadRaw";
261 return "(1d)ReceiveCoreWriteRawDummy";
263 return "(22)ReceiveV3SetAttributes";
265 return "(23)ReceiveV3GetAttributes";
267 return "(24)ReceiveV3LockingX";
269 return "(25)ReceiveV3Trans";
271 return "(26)ReceiveV3Trans[aux]";
273 return "(29)SendCoreBadOp";
275 return "(2b)ReceiveCoreEcho";
277 return "(2d)ReceiveV3OpenX";
279 return "(2e)ReceiveV3ReadX";
281 return "(32)ReceiveV3Tran2A";
283 return "(33)ReceiveV3Tran2A[aux]";
285 return "(34)ReceiveV3FindClose";
287 return "(35)ReceiveV3FindNotifyClose";
289 return "(70)ReceiveCoreTreeConnect";
291 return "(71)ReceiveCoreTreeDisconnect";
293 return "(72)ReceiveNegotiate";
295 return "(73)ReceiveV3SessionSetupX";
297 return "(74)ReceiveV3UserLogoffX";
299 return "(75)ReceiveV3TreeConnectX";
301 return "(80)ReceiveCoreGetDiskAttributes";
303 return "(81)ReceiveCoreSearchDir";
305 return "(A0)ReceiveNTTransact";
307 return "(A2)ReceiveNTCreateX";
309 return "(A4)ReceiveNTCancel";
311 return "(c0)SendCoreBadOp";
313 return "(c1)SendCoreBadOp";
315 return "(c2)SendCoreBadOp";
317 return "(c3)SendCoreBadOp";
321 char * myCrt_2Dispatch(int i)
326 return "unknown SMB op-2";
328 return "S(00)CreateFile";
330 return "S(01)FindFirst";
332 return "S(02)FindNext"; /* FindNext */
334 return "S(03)QueryFileSystem_ReceiveTran2QFSInfo";
338 return "S(05)QueryFileInfo_ReceiveTran2QPathInfo";
340 return "S(06)SetFileInfo_ReceiveTran2SetPathInfo";
342 return "S(07)SetInfoHandle_ReceiveTran2QFileInfo";
344 return "S(08)??_ReceiveTran2SetFileInfo";
346 return "S(09)??_ReceiveTran2FSCTL";
348 return "S(0a)_ReceiveTran2IOCTL";
350 return "S(0b)_ReceiveTran2FindNotifyFirst";
352 return "S(0c)_ReceiveTran2FindNotifyNext";
354 return "S(0d)CreateDirectory_ReceiveTran2MKDir";
358 char * myCrt_RapDispatch(int i)
363 return "unknown RAP OP";
365 return "RAP(0)NetShareEnum";
367 return "RAP(1)NetShareGetInfo";
369 return "RAP(13)NetServerGetInfo";
371 return "RAP(63)NetWkStaGetInfo";
375 /* scache must be locked */
376 unsigned int smb_Attributes(cm_scache_t *scp)
380 if (scp->fileType == CM_SCACHETYPE_DIRECTORY
381 || scp->fileType == CM_SCACHETYPE_MOUNTPOINT)
382 attrs = SMB_ATTR_DIRECTORY;
387 * We used to mark a file RO if it was in an RO volume, but that
388 * turns out to be impolitic in NT. See defect 10007.
391 if ((scp->unixModeBits & 0222) == 0 || (scp->flags & CM_SCACHEFLAG_RO))
393 if ((scp->unixModeBits & 0222) == 0)
394 attrs |= SMB_ATTR_READONLY; /* turn on read-only flag */
399 /* Check if the named file/dir is a dotfile/dotdir */
400 /* String pointed to by lastComp can have leading slashes, but otherwise should have
401 no other patch components */
402 unsigned int smb_IsDotFile(char *lastComp) {
405 /* skip over slashes */
406 for(s=lastComp;*s && (*s == '\\' || *s == '/'); s++);
411 /* nulls, curdir and parent dir doesn't count */
414 if(!*(s + 1)) return 0;
415 if(*(s+1) == '.' && !*(s + 2)) return 0;
421 static int ExtractBits(WORD bits, short start, short len)
428 num = bits << (16 - end);
429 num = num >> ((16 - end) + start);
435 void ShowUnixTime(char *FuncName, long unixTime)
440 smb_LargeSearchTimeFromUnixTime(&ft, unixTime);
442 if (!FileTimeToDosDateTime(&ft, &wDate, &wTime))
443 osi_Log1(smb_logp, "Failed to convert filetime to dos datetime: %d", GetLastError());
445 int day, month, year, sec, min, hour;
448 day = ExtractBits(wDate, 0, 5);
449 month = ExtractBits(wDate, 5, 4);
450 year = ExtractBits(wDate, 9, 7) + 1980;
452 sec = ExtractBits(wTime, 0, 5);
453 min = ExtractBits(wTime, 5, 6);
454 hour = ExtractBits(wTime, 11, 5);
456 sprintf(msg, "%s = %02d-%02d-%04d %02d:%02d:%02d", FuncName, month, day, year, hour, min, sec);
457 osi_Log1(smb_logp, "%s", osi_LogSaveString(smb_logp, msg));
463 /* Determine if we are observing daylight savings time */
464 void GetTimeZoneInfo(BOOL *pDST, LONG *pDstBias, LONG *pBias)
466 TIME_ZONE_INFORMATION timeZoneInformation;
467 SYSTEMTIME utc, local, localDST;
469 /* Get the time zone info. NT uses this to calc if we are in DST. */
470 GetTimeZoneInformation(&timeZoneInformation);
472 /* Return the daylight bias */
473 *pDstBias = timeZoneInformation.DaylightBias;
475 /* Return the bias */
476 *pBias = timeZoneInformation.Bias;
478 /* Now determine if DST is being observed */
480 /* Get the UTC (GMT) time */
483 /* Convert UTC time to local time using the time zone info. If we are
484 observing DST, the calculated local time will include this.
486 SystemTimeToTzSpecificLocalTime(&timeZoneInformation, &utc, &localDST);
488 /* Set the daylight bias to 0. The daylight bias is the amount of change
489 in time that we use for daylight savings time. By setting this to 0
490 we cause there to be no change in time during daylight savings time.
492 timeZoneInformation.DaylightBias = 0;
494 /* Convert the utc time to local time again, but this time without any
495 adjustment for daylight savings time.
497 SystemTimeToTzSpecificLocalTime(&timeZoneInformation, &utc, &local);
499 /* If the two times are different, then it means that the localDST that
500 we calculated includes the daylight bias, and therefore we are
501 observing daylight savings time.
503 *pDST = localDST.wHour != local.wHour;
506 /* Determine if we are observing daylight savings time */
507 void GetTimeZoneInfo(BOOL *pDST, LONG *pDstBias, LONG *pBias)
513 *pDstBias = -60; /* where can this be different? */
519 void CompensateForSmbClientLastWriteTimeBugs(long *pLastWriteTime)
521 BOOL dst; /* Will be TRUE if observing DST */
522 LONG dstBias; /* Offset from local time if observing DST */
523 LONG bias; /* Offset from GMT for local time */
526 * This function will adjust the last write time to compensate
527 * for two bugs in the smb client:
529 * 1) During Daylight Savings Time, the LastWriteTime is ahead
530 * in time by the DaylightBias (ignoring the sign - the
531 * DaylightBias is always stored as a negative number). If
532 * the DaylightBias is -60, then the LastWriteTime will be
533 * ahead by 60 minutes.
535 * 2) If the local time zone is a positive offset from GMT, then
536 * the LastWriteTime will be the correct local time plus the
537 * Bias (ignoring the sign - a positive offset from GMT is
538 * always stored as a negative Bias). If the Bias is -120,
539 * then the LastWriteTime will be ahead by 120 minutes.
541 * These bugs can occur at the same time.
544 GetTimeZoneInfo(&dst, &dstBias, &bias);
546 /* First adjust for DST */
548 *pLastWriteTime -= (-dstBias * 60); /* Convert dstBias to seconds */
550 /* Now adjust for a positive offset from GMT (a negative bias). */
552 *pLastWriteTime -= (-bias * 60); /* Convert bias to seconds */
556 * Calculate the difference (in seconds) between local time and GMT.
557 * This enables us to convert file times to kludge-GMT.
563 struct tm gmt_tm, local_tm;
564 int days, hours, minutes, seconds;
567 gmt_tm = *(gmtime(&t));
568 local_tm = *(localtime(&t));
570 days = local_tm.tm_yday - gmt_tm.tm_yday;
571 hours = 24 * days + local_tm.tm_hour - gmt_tm.tm_hour
573 /* There is a problem with DST immediately after the time change
574 * which may continue to exist until the machine is rebooted
576 - (local_tm.tm_isdst ? 1 : 0)
579 minutes = 60 * hours + local_tm.tm_min - gmt_tm.tm_min;
580 seconds = 60 * minutes + local_tm.tm_sec - gmt_tm.tm_sec;
586 void smb_LargeSearchTimeFromUnixTime(FILETIME *largeTimep, long unixTime)
591 long ersatz_unixTime;
594 * Must use kludge-GMT instead of real GMT.
595 * kludge-GMT is computed by adding time zone difference to localtime.
598 * ltp = gmtime(&unixTime);
600 ersatz_unixTime = unixTime - smb_NowTZ;
601 ltp = localtime(&ersatz_unixTime);
603 /* if we fail, make up something */
606 localJunk.tm_year = 89 - 20;
607 localJunk.tm_mon = 4;
608 localJunk.tm_mday = 12;
609 localJunk.tm_hour = 0;
610 localJunk.tm_min = 0;
611 localJunk.tm_sec = 0;
614 stm.wYear = ltp->tm_year + 1900;
615 stm.wMonth = ltp->tm_mon + 1;
616 stm.wDayOfWeek = ltp->tm_wday;
617 stm.wDay = ltp->tm_mday;
618 stm.wHour = ltp->tm_hour;
619 stm.wMinute = ltp->tm_min;
620 stm.wSecond = ltp->tm_sec;
621 stm.wMilliseconds = 0;
623 SystemTimeToFileTime(&stm, largeTimep);
626 void smb_LargeSearchTimeFromUnixTime(FILETIME *largeTimep, long unixTime)
628 /* unixTime: seconds since 1/1/1970 00:00:00 GMT */
629 /* FILETIME: 100ns intervals since 1/1/1601 00:00:00 ??? */
630 LARGE_INTEGER *ft = (LARGE_INTEGER *) largeTimep;
632 int leap_years = 89; /* leap years betw 1/1/1601 and 1/1/1970 */
634 /* set ft to number of 100ns intervals betw 1/1/1601 and 1/1/1970 GMT */
635 *ft = ConvertLongToLargeInteger(((EPOCH_YEAR-1601) * 365 + leap_years)
637 *ft = LargeIntegerMultiplyByLong(*ft, 60);
638 *ft = LargeIntegerMultiplyByLong(*ft, 10000000);
641 ut = ConvertLongToLargeInteger(unixTime);
642 ut = LargeIntegerMultiplyByLong(ut, 10000000);
643 *ft = LargeIntegerAdd(*ft, ut);
648 void smb_UnixTimeFromLargeSearchTime(long *unixTimep, FILETIME *largeTimep)
654 FileTimeToSystemTime(largeTimep, &stm);
656 lt.tm_year = stm.wYear - 1900;
657 lt.tm_mon = stm.wMonth - 1;
658 lt.tm_wday = stm.wDayOfWeek;
659 lt.tm_mday = stm.wDay;
660 lt.tm_hour = stm.wHour;
661 lt.tm_min = stm.wMinute;
662 lt.tm_sec = stm.wSecond;
665 save_timezone = _timezone;
666 _timezone += smb_NowTZ;
667 *unixTimep = mktime(<);
668 _timezone = save_timezone;
671 void smb_UnixTimeFromLargeSearchTime(long *unixTimep, FILETIME *largeTimep)
673 /* unixTime: seconds since 1/1/1970 00:00:00 GMT */
674 /* FILETIME: 100ns intervals since 1/1/1601 00:00:00 GMT? */
675 LARGE_INTEGER *ft = (LARGE_INTEGER *) largeTimep;
679 /* set to number of 100ns intervals betw 1/1/1601 and 1/1/1970 */
680 a = ConvertLongToLargeInteger(((EPOCH_YEAR-1601) * 365 + leap_years) * 24 * 60);
681 a = LargeIntegerMultiplyByLong(a, 60);
682 a = LargeIntegerMultiplyByLong(a, 10000000);
684 /* subtract it from ft */
685 a = LargeIntegerSubtract(*ft, a);
687 /* divide down to seconds */
688 *unixTimep = LargeIntegerDivideByLong(a, 10000000);
692 void smb_SearchTimeFromUnixTime(long *dosTimep, long unixTime)
699 ltp = localtime((time_t*) &unixTime);
701 /* if we fail, make up something */
704 localJunk.tm_year = 89 - 20;
705 localJunk.tm_mon = 4;
706 localJunk.tm_mday = 12;
707 localJunk.tm_hour = 0;
708 localJunk.tm_min = 0;
709 localJunk.tm_sec = 0;
712 dosDate = ((ltp->tm_year-80)<<9) | ((ltp->tm_mon+1) << 5) | (ltp->tm_mday);
713 dosTime = (ltp->tm_hour<<11) | (ltp->tm_min << 5) | (ltp->tm_sec / 2);
714 *dosTimep = (dosDate<<16) | dosTime;
717 void smb_UnixTimeFromSearchTime(long *unixTimep, long searchTime)
719 unsigned short dosDate;
720 unsigned short dosTime;
723 dosDate = searchTime & 0xffff;
724 dosTime = (searchTime >> 16) & 0xffff;
726 localTm.tm_year = 80 + ((dosDate>>9) & 0x3f);
727 localTm.tm_mon = ((dosDate >> 5) & 0xf) - 1; /* January is 0 in localTm */
728 localTm.tm_mday = (dosDate) & 0x1f;
729 localTm.tm_hour = (dosTime>>11) & 0x1f;
730 localTm.tm_min = (dosTime >> 5) & 0x3f;
731 localTm.tm_sec = (dosTime & 0x1f) * 2;
732 localTm.tm_isdst = -1; /* compute whether DST in effect */
734 *unixTimep = mktime(&localTm);
737 void smb_DosUTimeFromUnixTime(long *dosUTimep, long unixTime)
739 *dosUTimep = unixTime - smb_localZero;
742 void smb_UnixTimeFromDosUTime(long *unixTimep, long dosTime)
745 *unixTimep = dosTime + smb_localZero;
747 /* dosTime seems to be already adjusted for GMT */
748 *unixTimep = dosTime;
752 smb_vc_t *smb_FindVC(unsigned short lsn, int flags, int lana)
756 lock_ObtainWrite(&smb_rctLock);
757 for(vcp = smb_allVCsp; vcp; vcp=vcp->nextp) {
758 if (lsn == vcp->lsn && lana == vcp->lana) {
763 if (!vcp && (flags & SMB_FLAG_CREATE)) {
764 vcp = malloc(sizeof(*vcp));
765 memset(vcp, 0, sizeof(*vcp));
766 vcp->vcID = numVCs++;
770 vcp->uidCounter = 1; /* UID 0 is reserved for blank user */
771 vcp->nextp = smb_allVCsp;
773 lock_InitializeMutex(&vcp->mx, "vc_t mutex");
778 if (smb_authType == SMB_AUTH_NTLM || smb_authType == SMB_AUTH_EXTENDED) {
779 /* We must obtain a challenge for extended auth
780 * in case the client negotiates smb v3
783 MSV1_0_LM20_CHALLENGE_REQUEST lsaReq;
784 PMSV1_0_LM20_CHALLENGE_RESPONSE lsaResp;
787 lsaReq.MessageType = MsV1_0Lm20ChallengeRequest;
789 nts = LsaCallAuthenticationPackage( smb_lsaHandle,
796 osi_assert(nts == STATUS_SUCCESS); /* this had better work! */
798 memcpy(vcp->encKey, lsaResp->ChallengeToClient, MSV1_0_CHALLENGE_LENGTH);
799 LsaFreeReturnBuffer(lsaResp);
802 memset(vcp->encKey, 0, MSV1_0_CHALLENGE_LENGTH);
804 lock_ReleaseWrite(&smb_rctLock);
808 int smb_IsStarMask(char *maskp)
813 for(i=0; i<11; i++) {
815 if (tc == '?' || tc == '*' || tc == '>') return 1;
820 void smb_ReleaseVC(smb_vc_t *vcp)
822 lock_ObtainWrite(&smb_rctLock);
823 osi_assert(vcp->refCount-- > 0);
824 lock_ReleaseWrite(&smb_rctLock);
827 void smb_HoldVC(smb_vc_t *vcp)
829 lock_ObtainWrite(&smb_rctLock);
831 lock_ReleaseWrite(&smb_rctLock);
834 smb_tid_t *smb_FindTID(smb_vc_t *vcp, unsigned short tid, int flags)
838 lock_ObtainWrite(&smb_rctLock);
839 for(tidp = vcp->tidsp; tidp; tidp = tidp->nextp) {
840 if (tid == tidp->tid) {
845 if (!tidp && (flags & SMB_FLAG_CREATE)) {
846 tidp = malloc(sizeof(*tidp));
847 memset(tidp, 0, sizeof(*tidp));
848 tidp->nextp = vcp->tidsp;
853 lock_InitializeMutex(&tidp->mx, "tid_t mutex");
856 lock_ReleaseWrite(&smb_rctLock);
860 void smb_ReleaseTID(smb_tid_t *tidp)
869 lock_ObtainWrite(&smb_rctLock);
870 osi_assert(tidp->refCount-- > 0);
871 if (tidp->refCount == 0 && (tidp->flags & SMB_TIDFLAG_DELETE)) {
872 ltpp = &tidp->vcp->tidsp;
873 for(tp = *ltpp; tp; ltpp = &tp->nextp, tp = *ltpp) {
874 if (tp == tidp) break;
876 osi_assert(tp != NULL);
878 lock_FinalizeMutex(&tidp->mx);
879 userp = tidp->userp; /* remember to drop ref later */
882 lock_ReleaseWrite(&smb_rctLock);
884 cm_ReleaseUser(userp);
891 smb_user_t *smb_FindUID(smb_vc_t *vcp, unsigned short uid, int flags)
893 smb_user_t *uidp = NULL;
895 lock_ObtainWrite(&smb_rctLock);
896 for(uidp = vcp->usersp; uidp; uidp = uidp->nextp) {
897 if (uid == uidp->userID) {
899 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 : "");
903 if (!uidp && (flags & SMB_FLAG_CREATE)) {
904 uidp = malloc(sizeof(*uidp));
905 memset(uidp, 0, sizeof(*uidp));
906 uidp->nextp = vcp->usersp;
911 lock_InitializeMutex(&uidp->mx, "user_t mutex");
913 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 : ""));
915 lock_ReleaseWrite(&smb_rctLock);
919 smb_username_t *smb_FindUserByName(char *usern, char *machine, int flags)
921 smb_username_t *unp= NULL;
923 lock_ObtainWrite(&smb_rctLock);
924 for(unp = usernamesp; unp; unp = unp->nextp) {
925 if (stricmp(unp->name, usern) == 0 &&
926 stricmp(unp->machine, machine) == 0) {
931 if (!unp && (flags & SMB_FLAG_CREATE)) {
932 unp = malloc(sizeof(*unp));
933 memset(unp, 0, sizeof(*unp));
935 unp->nextp = usernamesp;
936 unp->name = strdup(usern);
937 unp->machine = strdup(machine);
939 lock_InitializeMutex(&unp->mx, "username_t mutex");
941 lock_ReleaseWrite(&smb_rctLock);
945 smb_user_t *smb_FindUserByNameThisSession(smb_vc_t *vcp, char *usern)
947 smb_user_t *uidp= NULL;
949 lock_ObtainWrite(&smb_rctLock);
950 for(uidp = vcp->usersp; uidp; uidp = uidp->nextp) {
953 if (stricmp(uidp->unp->name, usern) == 0) {
955 osi_LogEvent("AFS smb_FindUserByNameThisSession",NULL,"VCP[%x] uid[%d] match-name[%s]",(int)vcp,uidp->userID,usern);
960 lock_ReleaseWrite(&smb_rctLock);
963 void smb_ReleaseUID(smb_user_t *uidp)
972 lock_ObtainWrite(&smb_rctLock);
973 osi_assert(uidp->refCount-- > 0);
974 if (uidp->refCount == 0 && (uidp->flags & SMB_USERFLAG_DELETE)) {
975 lupp = &uidp->vcp->usersp;
976 for(up = *lupp; up; lupp = &up->nextp, up = *lupp) {
977 if (up == uidp) break;
979 osi_assert(up != NULL);
981 lock_FinalizeMutex(&uidp->mx);
983 userp = uidp->unp->userp; /* remember to drop ref later */
984 uidp->unp->userp = NULL;
989 lock_ReleaseWrite(&smb_rctLock);
991 cm_ReleaseUserVCRef(userp);
992 cm_ReleaseUser(userp);
999 /* retrieve a held reference to a user structure corresponding to an incoming
1001 * corresponding release function is cm_ReleaseUser.
1003 cm_user_t *smb_GetUser(smb_vc_t *vcp, smb_packet_t *inp)
1009 smbp = (smb_t *) inp;
1010 uidp = smb_FindUID(vcp, smbp->uid, 0);
1011 if ((!uidp) || (!uidp->unp))
1014 lock_ObtainMutex(&uidp->mx);
1015 up = uidp->unp->userp;
1017 lock_ReleaseMutex(&uidp->mx);
1019 smb_ReleaseUID(uidp);
1025 * Return a pointer to a pathname extracted from a TID structure. The
1026 * TID structure is not held; assume it won't go away.
1028 char *smb_GetTIDPath(smb_vc_t *vcp, unsigned short tid)
1033 tidp = smb_FindTID(vcp, tid, 0);
1036 tpath = tidp->pathname;
1037 smb_ReleaseTID(tidp);
1041 /* check to see if we have a chained fid, that is, a fid that comes from an
1042 * OpenAndX message that ran earlier in this packet. In this case, the fid
1043 * field in a read, for example, request, isn't set, since the value is
1044 * supposed to be inherited from the openAndX call.
1046 int smb_ChainFID(int fid, smb_packet_t *inp)
1048 if (inp->fid == 0 || inp->inCount == 0)
1054 /* are we a priv'd user? What does this mean on NT? */
1055 int smb_SUser(cm_user_t *userp)
1060 /* find a file ID. If we pass in 0 we select an used File ID.
1061 * If the SMB_FLAG_CREATE flag is set, we allocate a new
1062 * smb_fid_t data structure if desired File ID cannot be found.
1064 smb_fid_t *smb_FindFID(smb_vc_t *vcp, unsigned short fid, int flags)
1069 if (fid == 0 && !(flags & SMB_FLAG_CREATE))
1072 lock_ObtainWrite(&smb_rctLock);
1073 /* figure out if we need to allocate a new file ID */
1076 fid = vcp->fidCounter;
1080 for(fidp = vcp->fidsp; fidp; fidp = (smb_fid_t *) osi_QNext(&fidp->q)) {
1081 if (fid == fidp->fid) {
1092 if (!fidp && (flags & SMB_FLAG_CREATE)) {
1093 char eventName[MAX_PATH];
1095 sprintf(eventName,"fid_t event vcp=%d fid=%d", vcp->vcID, fid);
1096 event = thrd_CreateEvent(NULL, FALSE, TRUE, eventName);
1097 if ( GetLastError() == ERROR_ALREADY_EXISTS ) {
1098 afsi_log("Event Object Already Exists: %s", eventName);
1099 thrd_CloseHandle(event);
1106 fidp = malloc(sizeof(*fidp));
1107 memset(fidp, 0, sizeof(*fidp));
1108 osi_QAdd((osi_queue_t **)&vcp->fidsp, &fidp->q);
1112 lock_InitializeMutex(&fidp->mx, "fid_t mutex");
1114 fidp->curr_chunk = fidp->prev_chunk = -2;
1115 fidp->raw_write_event = event;
1117 vcp->fidCounter = fid+1;
1118 if (vcp->fidCounter == 0)
1119 vcp->fidCounter = 1;
1122 lock_ReleaseWrite(&smb_rctLock);
1126 void smb_ReleaseFID(smb_fid_t *fidp)
1129 smb_vc_t *vcp = NULL;
1130 smb_ioctl_t *ioctlp;
1136 lock_ObtainWrite(&smb_rctLock);
1137 osi_assert(fidp->refCount-- > 0);
1138 if (fidp->refCount == 0 && (fidp->flags & SMB_FID_DELETE)) {
1140 if (!(fidp->flags & SMB_FID_IOCTL))
1142 osi_QRemove((osi_queue_t **) &vcp->fidsp, &fidp->q);
1143 thrd_CloseHandle(fidp->raw_write_event);
1145 /* and see if there is ioctl stuff to free */
1146 ioctlp = fidp->ioctlp;
1148 if (ioctlp->prefix) cm_FreeSpace(ioctlp->prefix);
1149 if (ioctlp->inAllocp) free(ioctlp->inAllocp);
1150 if (ioctlp->outAllocp) free(ioctlp->outAllocp);
1156 /* do not call smb_ReleaseVC() because we already have the lock */
1159 lock_ReleaseWrite(&smb_rctLock);
1161 /* now release the scache structure */
1163 cm_ReleaseSCache(scp);
1167 * Case-insensitive search for one string in another;
1168 * used to find variable names in submount pathnames.
1170 static char *smb_stristr(char *str1, char *str2)
1174 for (cursor = str1; *cursor; cursor++)
1175 if (stricmp(cursor, str2) == 0)
1182 * Substitute a variable value for its name in a submount pathname. Variable
1183 * name has been identified by smb_stristr() and is in substr. Variable name
1184 * length (plus one) is in substr_size. Variable value is in newstr.
1186 static void smb_subst(char *str1, char *substr, unsigned int substr_size,
1191 strcpy(temp, substr + substr_size - 1);
1192 strcpy(substr, newstr);
1196 char VNUserName[] = "%USERNAME%";
1197 char VNLCUserName[] = "%LCUSERNAME%";
1198 char VNComputerName[] = "%COMPUTERNAME%";
1199 char VNLCComputerName[] = "%LCCOMPUTERNAME%";
1202 /* List available shares */
1203 int smb_ListShares()
1207 char shareBuf[4096];
1215 /*strcpy(shareNameList[num_shares], "all");
1216 strcpy(pathNameList[num_shares++], "/afs");*/
1217 fprintf(stderr, "The following shares are available:\n");
1218 fprintf(stderr, "Share Name (AFS Path)\n");
1219 fprintf(stderr, "---------------------\n");
1220 fprintf(stderr, "\\\\%s\\%-16s (%s)\n", smb_localNamep, "ALL", cm_mountRoot);
1223 code = GetWindowsDirectory(sbmtpath, sizeof(sbmtpath));
1224 if (code == 0 || code > sizeof(sbmtpath)) return -1;
1226 strcpy(sbmtpath, cm_confDir);
1228 strcat(sbmtpath, "/afsdsbmt.ini");
1229 len = GetPrivateProfileString("AFS Submounts", NULL, NULL,
1230 shareBuf, sizeof(shareBuf),
1236 this_share = shareBuf;
1240 /*strcpy(shareNameList[num_shares], this_share);*/
1241 len = GetPrivateProfileString("AFS Submounts", this_share,
1248 if (strncmp(p, cm_mountRoot, strlen(cm_mountRoot)) != 0)
1251 if (*p == '\\') *p = '/'; /* change to / */
1255 fprintf(stderr, "\\\\%s\\%-16s (%s%s)\n",
1256 smb_localNamep, this_share, (print_afs ? cm_mountRoot : "\0"),
1259 while (*this_share != 0) this_share++; /* find next NUL */
1260 this_share++; /* skip past the NUL */
1261 } while (*this_share != 0); /* stop at final NUL */
1266 /* find a shareName in the table of submounts */
1267 int smb_FindShare(smb_vc_t *vcp, smb_user_t *uidp, char *shareName,
1271 char pathName[1024];
1275 char sbmtpath[MAX_PATH];
1279 DWORD allSubmount = 1;
1281 if (strcmp(shareName, "IPC$") == 0) {
1286 /* if allSubmounts == 0, only return the //mountRoot/all share
1287 * if in fact it has been been created in the subMounts table.
1288 * This is to allow sites that want to restrict access to the
1291 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSConfigKeyName,
1292 0, KEY_QUERY_VALUE, &parmKey);
1293 if (code == ERROR_SUCCESS) {
1294 len = sizeof(allSubmount);
1295 code = RegQueryValueEx(parmKey, "AllSubmount", NULL, NULL,
1296 (BYTE *) &allSubmount, &len);
1297 if (code != ERROR_SUCCESS) {
1300 RegCloseKey (parmKey);
1303 if (allSubmount && _stricmp(shareName, "all") == 0) {
1308 /* In case, the all share is disabled we need to still be able
1309 * to handle ioctl requests
1311 if (_stricmp(shareName, "ioctl$") == 0) {
1312 *pathNamep = strdup("/.__ioctl__");
1317 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\OpenAFS\\Client\\Submounts",
1318 0, KEY_QUERY_VALUE, &parmKey);
1319 if (code == ERROR_SUCCESS) {
1320 len = sizeof(pathName);
1321 code = RegQueryValueEx(parmKey, shareName, NULL, NULL,
1322 (BYTE *) pathName, &len);
1323 if (code != ERROR_SUCCESS)
1325 RegCloseKey (parmKey);
1330 strcpy(sbmtpath, cm_confDir);
1331 strcat(sbmtpath, "/afsdsbmt.ini");
1332 len = GetPrivateProfileString("AFS Submounts", shareName, "",
1333 pathName, sizeof(pathName), sbmtpath);
1335 if (len != 0 && len != sizeof(pathName) - 1) {
1336 /* We can accept either unix or PC style AFS pathnames. Convert
1337 * Unix-style to PC style here for internal use.
1340 if (strncmp(p, cm_mountRoot, strlen(cm_mountRoot)) == 0)
1341 p += strlen(cm_mountRoot); /* skip mount path */
1344 if (*q == '/') *q = '\\'; /* change to \ */
1350 if (var = smb_stristr(p, VNUserName)) {
1351 if (uidp && uidp->unp)
1352 smb_subst(p, var, sizeof(VNUserName),uidp->unp->name);
1354 smb_subst(p, var, sizeof(VNUserName)," ");
1356 else if (var = smb_stristr(p, VNLCUserName))
1358 if (uidp && uidp->unp)
1359 strcpy(temp, uidp->unp->name);
1363 smb_subst(p, var, sizeof(VNLCUserName), temp);
1365 else if (var = smb_stristr(p, VNComputerName))
1367 sizeTemp = sizeof(temp);
1368 GetComputerName((LPTSTR)temp, &sizeTemp);
1369 smb_subst(p, var, sizeof(VNComputerName), temp);
1371 else if (var = smb_stristr(p, VNLCComputerName))
1373 sizeTemp = sizeof(temp);
1374 GetComputerName((LPTSTR)temp, &sizeTemp);
1376 smb_subst(p, var, sizeof(VNLCComputerName), temp);
1381 *pathNamep = strdup(p);
1384 else /* create \\<netbiosName>\<cellname> */
1386 char * p = shareName;
1393 /* Get the full name for this cell */
1394 code = cm_SearchCellFile(p, temp, 0, 0);
1395 #ifdef AFS_AFSDB_ENV
1396 if (code && cm_dnsEnabled) {
1398 code = cm_SearchCellByDNS(p, temp, &ttl, 0, 0);
1401 /* construct the path */
1403 sprintf(pathName,rw ? "/.%s/" : "/%s/",temp);
1404 *pathNamep = strdup(strlwr(pathName));
1413 /* Client-side offline caching policy types */
1414 #define CSC_POLICY_MANUAL 0
1415 #define CSC_POLICY_DOCUMENTS 1
1416 #define CSC_POLICY_PROGRAMS 2
1417 #define CSC_POLICY_DISABLE 3
1419 int smb_FindShareCSCPolicy(char *shareName)
1425 int retval = CSC_POLICY_MANUAL;
1427 RegCreateKeyEx( HKEY_LOCAL_MACHINE,
1428 "SOFTWARE\\OpenAFS\\Client\\CSCPolicy",
1431 REG_OPTION_NON_VOLATILE,
1437 len = sizeof(policy);
1438 if ( RegQueryValueEx( hkCSCPolicy, shareName, 0, &dwType, policy, &len ) ||
1440 retval = CSC_POLICY_MANUAL;
1442 else if (stricmp(policy, "documents") == 0)
1444 retval = CSC_POLICY_DOCUMENTS;
1446 else if (stricmp(policy, "programs") == 0)
1448 retval = CSC_POLICY_PROGRAMS;
1450 else if (stricmp(policy, "disable") == 0)
1452 retval = CSC_POLICY_DISABLE;
1455 RegCloseKey(hkCSCPolicy);
1459 /* find a dir search structure by cookie value, and return it held.
1460 * Must be called with smb_globalLock held.
1462 smb_dirSearch_t *smb_FindDirSearchNL(long cookie)
1464 smb_dirSearch_t *dsp;
1466 for(dsp = smb_firstDirSearchp; dsp; dsp = (smb_dirSearch_t *) osi_QNext(&dsp->q)) {
1467 if (dsp->cookie == cookie) {
1468 if (dsp != smb_firstDirSearchp) {
1469 /* move to head of LRU queue, too, if we're not already there */
1470 if (smb_lastDirSearchp == (smb_dirSearch_t *) &dsp->q)
1471 smb_lastDirSearchp = (smb_dirSearch_t *)
1473 osi_QRemove((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1474 osi_QAdd((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1475 if (!smb_lastDirSearchp)
1476 smb_lastDirSearchp = (smb_dirSearch_t *) &dsp->q;
1485 void smb_DeleteDirSearch(smb_dirSearch_t *dsp)
1487 lock_ObtainWrite(&smb_globalLock);
1488 dsp->flags |= SMB_DIRSEARCH_DELETE;
1489 lock_ReleaseWrite(&smb_globalLock);
1490 lock_ObtainMutex(&dsp->mx);
1491 if(dsp->scp != NULL) {
1492 lock_ObtainMutex(&dsp->scp->mx);
1493 if (dsp->flags & SMB_DIRSEARCH_BULKST) {
1494 dsp->flags &= ~SMB_DIRSEARCH_BULKST;
1495 dsp->scp->flags &= ~CM_SCACHEFLAG_BULKSTATTING;
1496 dsp->scp->bulkStatProgress = hones;
1498 lock_ReleaseMutex(&dsp->scp->mx);
1500 lock_ReleaseMutex(&dsp->mx);
1503 void smb_ReleaseDirSearch(smb_dirSearch_t *dsp)
1509 lock_ObtainWrite(&smb_globalLock);
1510 osi_assert(dsp->refCount-- > 0);
1511 if (dsp->refCount == 0 && (dsp->flags & SMB_DIRSEARCH_DELETE)) {
1512 if (&dsp->q == (osi_queue_t *) smb_lastDirSearchp)
1513 smb_lastDirSearchp = (smb_dirSearch_t *) osi_QPrev(&smb_lastDirSearchp->q);
1514 osi_QRemove((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1515 lock_FinalizeMutex(&dsp->mx);
1519 lock_ReleaseWrite(&smb_globalLock);
1521 /* do this now to avoid spurious locking hierarchy creation */
1522 if (scp) cm_ReleaseSCache(scp);
1525 /* find a dir search structure by cookie value, and return it held */
1526 smb_dirSearch_t *smb_FindDirSearch(long cookie)
1528 smb_dirSearch_t *dsp;
1530 lock_ObtainWrite(&smb_globalLock);
1531 dsp = smb_FindDirSearchNL(cookie);
1532 lock_ReleaseWrite(&smb_globalLock);
1536 /* GC some dir search entries, in the address space expected by the specific protocol.
1537 * Must be called with smb_globalLock held; release the lock temporarily.
1539 #define SMB_DIRSEARCH_GCMAX 10 /* how many at once */
1540 void smb_GCDirSearches(int isV3)
1542 smb_dirSearch_t *prevp;
1543 smb_dirSearch_t *tp;
1544 smb_dirSearch_t *victimsp[SMB_DIRSEARCH_GCMAX];
1548 victimCount = 0; /* how many have we got so far */
1549 for(tp = smb_lastDirSearchp; tp; tp=prevp) {
1550 /* we'll move tp from queue, so
1553 prevp = (smb_dirSearch_t *) osi_QPrev(&tp->q);
1554 /* if no one is using this guy, and we're either in the new protocol,
1555 * or we're in the old one and this is a small enough ID to be useful
1556 * to the old protocol, GC this guy.
1558 if (tp->refCount == 0 && (isV3 || tp->cookie <= 255)) {
1559 /* hold and delete */
1560 tp->flags |= SMB_DIRSEARCH_DELETE;
1561 victimsp[victimCount++] = tp;
1565 /* don't do more than this */
1566 if (victimCount >= SMB_DIRSEARCH_GCMAX) break;
1569 /* now release them */
1570 lock_ReleaseWrite(&smb_globalLock);
1571 for(i = 0; i < victimCount; i++) {
1572 smb_ReleaseDirSearch(victimsp[i]);
1574 lock_ObtainWrite(&smb_globalLock);
1577 /* function for allocating a dir search entry. We need these to remember enough context
1578 * since we don't get passed the path from call to call during a directory search.
1580 * Returns a held dir search structure, and bumps the reference count on the vnode,
1581 * since it saves a pointer to the vnode.
1583 smb_dirSearch_t *smb_NewDirSearch(int isV3)
1585 smb_dirSearch_t *dsp;
1589 lock_ObtainWrite(&smb_globalLock);
1592 /* what's the biggest ID allowed in this version of the protocol */
1593 if (isV3) maxAllowed = 65535;
1594 else maxAllowed = 255;
1597 /* twice so we have enough tries to find guys we GC after one pass;
1598 * 10 extra is just in case I mis-counted.
1600 if (++counter > 2*maxAllowed+10) osi_panic("afsd: dir search cookie leak",
1601 __FILE__, __LINE__);
1602 if (smb_dirSearchCounter > maxAllowed) {
1603 smb_dirSearchCounter = 1;
1604 smb_GCDirSearches(isV3); /* GC some (drops global lock) */
1606 dsp = smb_FindDirSearchNL(smb_dirSearchCounter);
1608 /* don't need to watch for refcount zero and deleted, since
1609 * we haven't dropped the global lock.
1612 ++smb_dirSearchCounter;
1616 dsp = malloc(sizeof(*dsp));
1617 memset(dsp, 0, sizeof(*dsp));
1618 osi_QAdd((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1619 if (!smb_lastDirSearchp) smb_lastDirSearchp = (smb_dirSearch_t *) &dsp->q;
1620 dsp->cookie = smb_dirSearchCounter;
1621 ++smb_dirSearchCounter;
1623 lock_InitializeMutex(&dsp->mx, "cm_dirSearch_t");
1624 dsp->lastTime = osi_Time();
1627 lock_ReleaseWrite(&smb_globalLock);
1631 static smb_packet_t *GetPacket(void)
1635 unsigned int npar, seg, tb_sel;
1638 lock_ObtainWrite(&smb_globalLock);
1639 tbp = smb_packetFreeListp;
1641 smb_packetFreeListp = tbp->nextp;
1642 lock_ReleaseWrite(&smb_globalLock);
1645 tbp = calloc(65540,1);
1647 tbp = malloc(sizeof(smb_packet_t));
1649 tbp->magic = SMB_PACKETMAGIC;
1652 tbp->resumeCode = 0;
1658 tbp->ncb_length = 0;
1663 npar = SMB_PACKETSIZE >> 4; /* number of paragraphs */
1666 __dpmi_allocate_dos_memory(npar, &tb_sel); /* DOS segment */
1668 afsi_log("Cannot allocate %d paragraphs of DOS memory",
1670 osi_panic("",__FILE__,__LINE__);
1673 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X",
1678 tbp->dos_pkt = (seg * 16) + 0; /* DOS physical address */
1679 tbp->dos_pkt_sel = tb_sel;
1682 osi_assert(tbp->magic == SMB_PACKETMAGIC);
1687 smb_packet_t *smb_CopyPacket(smb_packet_t *pkt)
1691 memcpy(tbp, pkt, sizeof(smb_packet_t));
1692 tbp->wctp = tbp->data + ((unsigned int)pkt->wctp - (unsigned int)pkt->data);
1696 static NCB *GetNCB(void)
1701 unsigned int npar, seg, tb_sel;
1704 lock_ObtainWrite(&smb_globalLock);
1705 tbp = smb_ncbFreeListp;
1707 smb_ncbFreeListp = tbp->nextp;
1708 lock_ReleaseWrite(&smb_globalLock);
1711 tbp = calloc(sizeof(*tbp),1);
1713 tbp = malloc(sizeof(*tbp));
1714 npar = (sizeof(NCB)+15) >> 4; /* number of paragraphs */
1717 __dpmi_allocate_dos_memory(npar, &tb_sel); /* DOS segment */
1719 afsi_log("Cannot allocate %d paragraphs of DOS mem in GetNCB",
1721 osi_panic("",__FILE__,__LINE__);
1723 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X in GetNCB",
1728 tbp->dos_ncb = (seg * 16) + 0; /* DOS physical address */
1729 tbp->dos_ncb_sel = tb_sel;
1731 tbp->magic = SMB_NCBMAGIC;
1734 osi_assert(tbp->magic == SMB_NCBMAGIC);
1736 memset(&tbp->ncb, 0, sizeof(NCB));
1739 dos_memset(tbp->dos_ncb, 0, sizeof(NCB));
1744 void smb_FreePacket(smb_packet_t *tbp)
1746 osi_assert(tbp->magic == SMB_PACKETMAGIC);
1748 lock_ObtainWrite(&smb_globalLock);
1749 tbp->nextp = smb_packetFreeListp;
1750 smb_packetFreeListp = tbp;
1751 tbp->magic = SMB_PACKETMAGIC;
1754 tbp->resumeCode = 0;
1760 tbp->ncb_length = 0;
1762 lock_ReleaseWrite(&smb_globalLock);
1765 static void FreeNCB(NCB *bufferp)
1769 tbp = (smb_ncb_t *) bufferp;
1770 osi_assert(tbp->magic == SMB_NCBMAGIC);
1772 lock_ObtainWrite(&smb_globalLock);
1773 tbp->nextp = smb_ncbFreeListp;
1774 smb_ncbFreeListp = tbp;
1775 lock_ReleaseWrite(&smb_globalLock);
1778 /* get a ptr to the data part of a packet, and its count */
1779 unsigned char *smb_GetSMBData(smb_packet_t *smbp, int *nbytesp)
1783 unsigned char *afterParmsp;
1785 parmBytes = *smbp->wctp << 1;
1786 afterParmsp = smbp->wctp + parmBytes + 1;
1788 dataBytes = afterParmsp[0] + (afterParmsp[1]<<8);
1789 if (nbytesp) *nbytesp = dataBytes;
1791 /* don't forget to skip the data byte count, since it follows
1792 * the parameters; that's where the "2" comes from below.
1794 return (unsigned char *) (afterParmsp + 2);
1797 /* must set all the returned parameters before playing around with the
1798 * data region, since the data region is located past the end of the
1799 * variable number of parameters.
1801 void smb_SetSMBDataLength(smb_packet_t *smbp, unsigned int dsize)
1803 unsigned char *afterParmsp;
1805 afterParmsp = smbp->wctp + ((*smbp->wctp)<<1) + 1;
1807 *afterParmsp++ = dsize & 0xff;
1808 *afterParmsp = (dsize>>8) & 0xff;
1811 /* return the parm'th parameter in the smbp packet */
1812 unsigned int smb_GetSMBParm(smb_packet_t *smbp, int parm)
1815 unsigned char *parmDatap;
1817 parmCount = *smbp->wctp;
1819 if (parm >= parmCount) {
1824 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
1825 sprintf(s, "Bad SMB param %d out of %d, ncb len %d",
1826 parm, parmCount, smbp->ncb_length);
1828 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1006, NULL,
1829 1, smbp->ncb_length, ptbuf, smbp);
1830 DeregisterEventSource(h);
1834 sprintf(s, "Bad SMB param %d out of %d, ncb len %d",
1835 parm, parmCount, smbp->ncb_length);
1836 osi_Log0(smb_logp, s);
1838 osi_panic(s, __FILE__, __LINE__);
1840 parmDatap = smbp->wctp + (2*parm) + 1;
1842 return parmDatap[0] + (parmDatap[1] << 8);
1845 /* return the parm'th parameter in the smbp packet */
1846 unsigned int smb_GetSMBOffsetParm(smb_packet_t *smbp, int parm, int offset)
1849 unsigned char *parmDatap;
1851 parmCount = *smbp->wctp;
1853 if (parm * 2 + offset >= parmCount * 2) {
1858 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
1859 sprintf(s, "Bad SMB param %d offset %d out of %d, ncb len %d",
1860 parm, offset, parmCount, smbp->ncb_length);
1862 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1006, NULL,
1863 1, smbp->ncb_length, ptbuf, smbp);
1864 DeregisterEventSource(h);
1868 sprintf(s, "Bad SMB param %d offset %d out of %d, "
1870 parm, offset, parmCount, smbp->ncb_length);
1871 osi_Log0(smb_logp, s);
1874 osi_panic(s, __FILE__, __LINE__);
1876 parmDatap = smbp->wctp + (2*parm) + 1 + offset;
1878 return parmDatap[0] + (parmDatap[1] << 8);
1881 void smb_SetSMBParm(smb_packet_t *smbp, int slot, unsigned int parmValue)
1885 /* make sure we have enough slots */
1886 if (*smbp->wctp <= slot) *smbp->wctp = slot+1;
1888 parmDatap = smbp->wctp + 2*slot + 1 + smbp->oddByte;
1889 *parmDatap++ = parmValue & 0xff;
1890 *parmDatap = (parmValue>>8) & 0xff;
1893 void smb_SetSMBParmLong(smb_packet_t *smbp, int slot, unsigned int parmValue)
1897 /* make sure we have enough slots */
1898 if (*smbp->wctp <= slot) *smbp->wctp = slot+2;
1900 parmDatap = smbp->wctp + 2*slot + 1 + smbp->oddByte;
1901 *parmDatap++ = parmValue & 0xff;
1902 *parmDatap++ = (parmValue>>8) & 0xff;
1903 *parmDatap++ = (parmValue>>16) & 0xff;
1904 *parmDatap++ = (parmValue>>24) & 0xff;
1907 void smb_SetSMBParmDouble(smb_packet_t *smbp, int slot, char *parmValuep)
1912 /* make sure we have enough slots */
1913 if (*smbp->wctp <= slot) *smbp->wctp = slot+4;
1915 parmDatap = smbp->wctp + 2*slot + 1 + smbp->oddByte;
1917 *parmDatap++ = *parmValuep++;
1920 void smb_SetSMBParmByte(smb_packet_t *smbp, int slot, unsigned int parmValue)
1924 /* make sure we have enough slots */
1925 if (*smbp->wctp <= slot) {
1926 if (smbp->oddByte) {
1928 *smbp->wctp = slot+1;
1933 parmDatap = smbp->wctp + 2*slot + 1 + (1 - smbp->oddByte);
1934 *parmDatap++ = parmValue & 0xff;
1937 void smb_StripLastComponent(char *outPathp, char **lastComponentp, char *inPathp)
1941 lastSlashp = strrchr(inPathp, '\\');
1943 *lastComponentp = lastSlashp;
1946 if (inPathp == lastSlashp)
1948 *outPathp++ = *inPathp++;
1957 unsigned char *smb_ParseASCIIBlock(unsigned char *inp, char **chainpp)
1962 *chainpp = inp + strlen(inp) + 1; /* skip over null-terminated string */
1967 unsigned char *smb_ParseVblBlock(unsigned char *inp, char **chainpp, int *lengthp)
1973 tlen = inp[0] + (inp[1]<<8);
1974 inp += 2; /* skip length field */
1977 *chainpp = inp + tlen;
1986 /* format a packet as a response */
1987 void smb_FormatResponsePacket(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *op)
1992 outp = (smb_t *) op;
1994 /* zero the basic structure through the smb_wct field, and zero the data
1995 * size field, assuming that wct stays zero; otherwise, you have to
1996 * explicitly set the data size field, too.
1998 inSmbp = (smb_t *) inp;
1999 memset(outp, 0, sizeof(smb_t)+2);
2005 outp->com = inSmbp->com;
2006 outp->tid = inSmbp->tid;
2007 outp->pid = inSmbp->pid;
2008 outp->uid = inSmbp->uid;
2009 outp->mid = inSmbp->mid;
2010 outp->res[0] = inSmbp->res[0];
2011 outp->res[1] = inSmbp->res[1];
2012 op->inCom = inSmbp->com;
2014 outp->reb = 0x80; /* SERVER_RESP */
2015 outp->flg2 = 0x1; /* KNOWS_LONG_NAMES */
2017 /* copy fields in generic packet area */
2018 op->wctp = &outp->wct;
2021 /* send a (probably response) packet; vcp tells us to whom to send it.
2022 * we compute the length by looking at wct and bcc fields.
2024 void smb_SendPacket(smb_vc_t *vcp, smb_packet_t *inp)
2041 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
2044 memset((char *)ncbp, 0, sizeof(NCB));
2046 extra = 2 * (*inp->wctp); /* space used by parms, in bytes */
2047 tp = inp->wctp + 1+ extra; /* points to count of data bytes */
2048 extra += tp[0] + (tp[1]<<8);
2049 extra += ((unsigned int)inp->wctp - (unsigned int)inp->data); /* distance to last wct field */
2050 extra += 3; /* wct and length fields */
2052 ncbp->ncb_length = extra; /* bytes to send */
2053 ncbp->ncb_lsn = (unsigned char) vcp->lsn; /* vc to use */
2054 ncbp->ncb_lana_num = vcp->lana;
2055 ncbp->ncb_command = NCBSEND; /* op means send data */
2057 ncbp->ncb_buffer = (char *) inp;/* packet */
2058 code = Netbios(ncbp);
2060 ncbp->ncb_buffer = inp->dos_pkt;/* packet */
2061 ((smb_ncb_t*)ncbp)->orig_pkt = inp;
2063 /* copy header information from virtual to DOS address space */
2064 dosmemput((char*)inp, SMB_PACKETSIZE, inp->dos_pkt);
2065 code = Netbios(ncbp, dos_ncb);
2069 osi_Log1(smb_logp, "SendPacket failure code %d", code);
2075 void smb_MapNTError(long code, unsigned long *NTStatusp)
2077 unsigned long NTStatus;
2079 /* map CM_ERROR_* errors to NT 32-bit status codes */
2080 /* NT Status codes are listed in ntstatus.h not winerror.h */
2081 if (code == CM_ERROR_NOSUCHCELL) {
2082 NTStatus = 0xC000000FL; /* No such file */
2084 else if (code == CM_ERROR_NOSUCHVOLUME) {
2085 NTStatus = 0xC000000FL; /* No such file */
2087 else if (code == CM_ERROR_TIMEDOUT) {
2088 NTStatus = 0xC00000CFL; /* Sharing Paused */
2090 else if (code == CM_ERROR_RETRY) {
2091 NTStatus = 0xC000022DL; /* Retry */
2093 else if (code == CM_ERROR_NOACCESS) {
2094 NTStatus = 0xC0000022L; /* Access denied */
2096 else if (code == CM_ERROR_READONLY) {
2097 NTStatus = 0xC00000A2L; /* Write protected */
2099 else if (code == CM_ERROR_NOSUCHFILE) {
2100 NTStatus = 0xC000000FL; /* No such file */
2102 else if (code == CM_ERROR_NOSUCHPATH) {
2103 NTStatus = 0xC000003AL; /* Object path not found */
2105 else if (code == CM_ERROR_TOOBIG) {
2106 NTStatus = 0xC000007BL; /* Invalid image format */
2108 else if (code == CM_ERROR_INVAL) {
2109 NTStatus = 0xC000000DL; /* Invalid parameter */
2111 else if (code == CM_ERROR_BADFD) {
2112 NTStatus = 0xC0000008L; /* Invalid handle */
2114 else if (code == CM_ERROR_BADFDOP) {
2115 NTStatus = 0xC0000022L; /* Access denied */
2117 else if (code == CM_ERROR_EXISTS) {
2118 NTStatus = 0xC0000035L; /* Object name collision */
2120 else if (code == CM_ERROR_NOTEMPTY) {
2121 NTStatus = 0xC0000101L; /* Directory not empty */
2123 else if (code == CM_ERROR_CROSSDEVLINK) {
2124 NTStatus = 0xC00000D4L; /* Not same device */
2126 else if (code == CM_ERROR_NOTDIR) {
2127 NTStatus = 0xC0000103L; /* Not a directory */
2129 else if (code == CM_ERROR_ISDIR) {
2130 NTStatus = 0xC00000BAL; /* File is a directory */
2132 else if (code == CM_ERROR_BADOP) {
2133 NTStatus = 0xC09820FFL; /* SMB no support */
2135 else if (code == CM_ERROR_BADSHARENAME) {
2136 NTStatus = 0xC00000CCL; /* Bad network name */
2138 else if (code == CM_ERROR_NOIPC) {
2140 NTStatus = 0xC0000022L; /* Access Denied */
2142 NTStatus = 0xC000013DL; /* Remote Resources */
2145 else if (code == CM_ERROR_CLOCKSKEW) {
2146 NTStatus = 0xC0000133L; /* Time difference at DC */
2148 else if (code == CM_ERROR_BADTID) {
2149 NTStatus = 0xC0982005L; /* SMB bad TID */
2151 else if (code == CM_ERROR_USESTD) {
2152 NTStatus = 0xC09820FBL; /* SMB use standard */
2154 else if (code == CM_ERROR_QUOTA) {
2155 NTStatus = 0xC0000044L; /* Quota exceeded */
2157 else if (code == CM_ERROR_SPACE) {
2158 NTStatus = 0xC000007FL; /* Disk full */
2160 else if (code == CM_ERROR_ATSYS) {
2161 NTStatus = 0xC0000033L; /* Object name invalid */
2163 else if (code == CM_ERROR_BADNTFILENAME) {
2164 NTStatus = 0xC0000033L; /* Object name invalid */
2166 else if (code == CM_ERROR_WOULDBLOCK) {
2167 NTStatus = 0xC0000055L; /* Lock not granted */
2169 else if (code == CM_ERROR_PARTIALWRITE) {
2170 NTStatus = 0xC000007FL; /* Disk full */
2172 else if (code == CM_ERROR_BUFFERTOOSMALL) {
2173 NTStatus = 0xC0000023L; /* Buffer too small */
2175 else if (code == CM_ERROR_AMBIGUOUS_FILENAME) {
2176 NTStatus = 0xC0000035L; /* Object name collision */
2178 else if (code == CM_ERROR_BADPASSWORD) {
2179 NTStatus = 0xC000006DL; /* unknown username or bad password */
2181 else if (code == CM_ERROR_BADLOGONTYPE) {
2182 NTStatus = 0xC000015BL; /* logon type not granted */
2184 else if (code == CM_ERROR_GSSCONTINUE) {
2185 NTStatus = 0xC0000016L; /* more processing required */
2188 NTStatus = 0xC0982001L; /* SMB non-specific error */
2191 *NTStatusp = NTStatus;
2192 osi_Log2(smb_logp, "SMB SEND code %x as NT %x", code, NTStatus);
2195 void smb_MapCoreError(long code, smb_vc_t *vcp, unsigned short *scodep,
2196 unsigned char *classp)
2198 unsigned char class;
2199 unsigned short error;
2201 /* map CM_ERROR_* errors to SMB errors */
2202 if (code == CM_ERROR_NOSUCHCELL) {
2204 error = 3; /* bad path */
2206 else if (code == CM_ERROR_NOSUCHVOLUME) {
2208 error = 3; /* bad path */
2210 else if (code == CM_ERROR_TIMEDOUT) {
2212 error = 81; /* server is paused */
2214 else if (code == CM_ERROR_RETRY) {
2215 class = 2; /* shouldn't happen */
2218 else if (code == CM_ERROR_NOACCESS) {
2220 error = 4; /* bad access */
2222 else if (code == CM_ERROR_READONLY) {
2224 error = 19; /* read only */
2226 else if (code == CM_ERROR_NOSUCHFILE) {
2228 error = 2; /* ENOENT! */
2230 else if (code == CM_ERROR_NOSUCHPATH) {
2232 error = 3; /* Bad path */
2234 else if (code == CM_ERROR_TOOBIG) {
2236 error = 11; /* bad format */
2238 else if (code == CM_ERROR_INVAL) {
2239 class = 2; /* server non-specific error code */
2242 else if (code == CM_ERROR_BADFD) {
2244 error = 6; /* invalid file handle */
2246 else if (code == CM_ERROR_BADFDOP) {
2247 class = 1; /* invalid op on FD */
2250 else if (code == CM_ERROR_EXISTS) {
2252 error = 80; /* file already exists */
2254 else if (code == CM_ERROR_NOTEMPTY) {
2256 error = 5; /* delete directory not empty */
2258 else if (code == CM_ERROR_CROSSDEVLINK) {
2260 error = 17; /* EXDEV */
2262 else if (code == CM_ERROR_NOTDIR) {
2263 class = 1; /* bad path */
2266 else if (code == CM_ERROR_ISDIR) {
2267 class = 1; /* access denied; DOS doesn't have a good match */
2270 else if (code == CM_ERROR_BADOP) {
2274 else if (code == CM_ERROR_BADSHARENAME) {
2278 else if (code == CM_ERROR_NOIPC) {
2280 error = 4; /* bad access */
2282 else if (code == CM_ERROR_CLOCKSKEW) {
2283 class = 1; /* invalid function */
2286 else if (code == CM_ERROR_BADTID) {
2290 else if (code == CM_ERROR_USESTD) {
2294 else if (code == CM_ERROR_REMOTECONN) {
2298 else if (code == CM_ERROR_QUOTA) {
2299 if (vcp->flags & SMB_VCFLAG_USEV3) {
2301 error = 39; /* disk full */
2305 error = 5; /* access denied */
2308 else if (code == CM_ERROR_SPACE) {
2309 if (vcp->flags & SMB_VCFLAG_USEV3) {
2311 error = 39; /* disk full */
2315 error = 5; /* access denied */
2318 else if (code == CM_ERROR_PARTIALWRITE) {
2320 error = 39; /* disk full */
2322 else if (code == CM_ERROR_ATSYS) {
2324 error = 2; /* ENOENT */
2326 else if (code == CM_ERROR_WOULDBLOCK) {
2328 error = 33; /* lock conflict */
2330 else if (code == CM_ERROR_NOFILES) {
2332 error = 18; /* no files in search */
2334 else if (code == CM_ERROR_RENAME_IDENTICAL) {
2336 error = 183; /* Samba uses this */
2338 else if (code == CM_ERROR_BADPASSWORD || code == CM_ERROR_BADLOGONTYPE) {
2339 /* we don't have a good way of reporting CM_ERROR_BADLOGONTYPE */
2341 error = 2; /* bad password */
2350 osi_Log3(smb_logp, "SMB SEND code %x as SMB %d: %d", code, class, error);
2353 long smb_SendCoreBadOp(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2355 return CM_ERROR_BADOP;
2358 long smb_ReceiveCoreEcho(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2360 unsigned short EchoCount, i;
2361 char *data, *outdata;
2364 EchoCount = (unsigned short) smb_GetSMBParm(inp, 0);
2366 for (i=1; i<=EchoCount; i++) {
2367 data = smb_GetSMBData(inp, &dataSize);
2368 smb_SetSMBParm(outp, 0, i);
2369 smb_SetSMBDataLength(outp, dataSize);
2370 outdata = smb_GetSMBData(outp, NULL);
2371 memcpy(outdata, data, dataSize);
2372 smb_SendPacket(vcp, outp);
2378 long smb_ReceiveCoreReadRaw(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2381 long count, minCount, finalCount;
2385 cm_user_t *userp = NULL;
2389 char *rawBuf = NULL;
2391 dos_ptr rawBuf = NULL;
2398 fd = smb_GetSMBParm(inp, 0);
2399 count = smb_GetSMBParm(inp, 3);
2400 minCount = smb_GetSMBParm(inp, 4);
2401 offset.HighPart = 0; /* too bad */
2402 offset.LowPart = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
2404 osi_Log3(smb_logp, "smb_ReceieveCoreReadRaw fd %d, off 0x%x, size 0x%x",
2405 fd, offset.LowPart, count);
2407 fidp = smb_FindFID(vcp, fd, 0);
2411 lock_ObtainMutex(&smb_RawBufLock);
2413 /* Get a raw buf, from head of list */
2414 rawBuf = smb_RawBufs;
2416 smb_RawBufs = *(char **)smb_RawBufs;
2418 smb_RawBufs = _farpeekl(_dos_ds, smb_RawBufs);
2421 lock_ReleaseMutex(&smb_RawBufLock);
2425 if (fidp->flags & SMB_FID_IOCTL)
2428 rc = smb_IoctlReadRaw(fidp, vcp, inp, outp);
2430 rc = smb_IoctlReadRaw(fidp, vcp, inp, outp, rawBuf);
2433 /* Give back raw buffer */
2434 lock_ObtainMutex(&smb_RawBufLock);
2436 *((char **) rawBuf) = smb_RawBufs;
2438 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
2441 smb_RawBufs = rawBuf;
2442 lock_ReleaseMutex(&smb_RawBufLock);
2445 smb_ReleaseFID(fidp);
2449 userp = smb_GetUser(vcp, inp);
2452 code = smb_ReadData(fidp, &offset, count, rawBuf, userp, &finalCount);
2454 /* have to give ReadData flag so it will treat buffer as DOS mem. */
2455 code = smb_ReadData(fidp, &offset, count, (unsigned char *)rawBuf,
2456 userp, &finalCount, TRUE /* rawFlag */);
2463 cm_ReleaseUser(userp);
2466 smb_ReleaseFID(fidp);
2471 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
2473 memset((char *)ncbp, 0, sizeof(NCB));
2475 ncbp->ncb_length = (unsigned short) finalCount;
2476 ncbp->ncb_lsn = (unsigned char) vcp->lsn;
2477 ncbp->ncb_lana_num = vcp->lana;
2478 ncbp->ncb_command = NCBSEND;
2479 ncbp->ncb_buffer = rawBuf;
2482 code = Netbios(ncbp);
2484 code = Netbios(ncbp, dos_ncb);
2487 osi_Log1(smb_logp, "ReadRaw send failure code %d", code);
2490 /* Give back raw buffer */
2491 lock_ObtainMutex(&smb_RawBufLock);
2493 *((char **) rawBuf) = smb_RawBufs;
2495 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
2498 smb_RawBufs = rawBuf;
2499 lock_ReleaseMutex(&smb_RawBufLock);
2505 long smb_ReceiveCoreLockRecord(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2510 long smb_ReceiveCoreUnlockRecord(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2515 long smb_ReceiveNegotiate(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2522 int protoIndex; /* index we're using */
2527 char protocol_array[10][1024]; /* protocol signature of the client */
2528 int caps; /* capabilities */
2531 TIME_ZONE_INFORMATION tzi;
2533 osi_Log1(smb_logp, "SMB receive negotiate; %d + 1 ongoing ops",
2537 DWORD now = GetCurrentTime();
2538 if (now - last_msg_time >= 30000
2539 && now - last_msg_time <= 90000) {
2541 "Setting dead_vcp %x", active_vcp);
2543 smb_ReleaseVC(dead_vcp);
2545 "Previous dead_vcp %x", dead_vcp);
2547 smb_HoldVC(active_vcp);
2548 dead_vcp = active_vcp;
2549 dead_vcp->flags |= SMB_VCFLAG_ALREADYDEAD;
2554 inp->flags |= SMB_PACKETFLAG_PROFILE_UPDATE_OK;
2556 namep = smb_GetSMBData(inp, &dbytes);
2559 coreProtoIndex = -1; /* not found */
2562 while(namex < dbytes) {
2563 osi_Log1(smb_logp, "Protocol %s",
2564 osi_LogSaveString(smb_logp, namep+1));
2565 strcpy(protocol_array[tcounter], namep+1);
2567 /* namep points at the first protocol, or really, a 0x02
2568 * byte preceding the null-terminated ASCII name.
2570 if (strcmp("PC NETWORK PROGRAM 1.0", namep+1) == 0) {
2571 coreProtoIndex = tcounter;
2573 else if (smb_useV3 && strcmp("LM1.2X002", namep+1) == 0) {
2574 v3ProtoIndex = tcounter;
2576 else if (smb_useV3 && strcmp("NT LM 0.12", namep+1) == 0) {
2577 NTProtoIndex = tcounter;
2580 /* compute size of protocol entry */
2581 entryLength = strlen(namep+1);
2582 entryLength += 2; /* 0x02 bytes and null termination */
2584 /* advance over this protocol entry */
2585 namex += entryLength;
2586 namep += entryLength;
2587 tcounter++; /* which proto entry we're looking at */
2590 if (NTProtoIndex != -1) {
2591 protoIndex = NTProtoIndex;
2592 vcp->flags |= (SMB_VCFLAG_USENT | SMB_VCFLAG_USEV3);
2594 else if (v3ProtoIndex != -1) {
2595 protoIndex = v3ProtoIndex;
2596 vcp->flags |= SMB_VCFLAG_USEV3;
2598 else if (coreProtoIndex != -1) {
2599 protoIndex = coreProtoIndex;
2600 vcp->flags |= SMB_VCFLAG_USECORE;
2602 else protoIndex = -1;
2604 if (protoIndex == -1)
2605 return CM_ERROR_INVAL;
2606 else if (NTProtoIndex != -1) {
2607 smb_SetSMBParm(outp, 0, protoIndex);
2608 if (smb_authType != SMB_AUTH_NONE) {
2609 smb_SetSMBParmByte(outp, 1,
2610 NEGOTIATE_SECURITY_USER_LEVEL |
2611 NEGOTIATE_SECURITY_CHALLENGE_RESPONSE); /* user level security, challenge response */
2613 smb_SetSMBParmByte(outp, 1, 0); /* share level auth with plaintext password. */
2615 smb_SetSMBParm(outp, 1, smb_maxMpxRequests); /* max multiplexed requests */
2616 smb_SetSMBParm(outp, 2, smb_maxVCPerServer); /* max VCs per consumer/server connection */
2617 smb_SetSMBParmLong(outp, 3, SMB_PACKETSIZE); /* xmit buffer size */
2618 smb_SetSMBParmLong(outp, 5, SMB_MAXRAWSIZE); /* raw buffer size */
2619 /* The session key is not a well documented field however most clients
2620 * will echo back the session key to the server. Currently we are using
2621 * the same value for all sessions. We should generate a random value
2622 * and store it into the vcp
2624 smb_SetSMBParm(outp, 7, 1); /* next 2: session key */
2625 smb_SetSMBParm(outp, 8, 1);
2627 * Tried changing the capabilities to support for W2K - defect 117695
2628 * Maybe something else needs to be changed here?
2632 smb_SetSMBParmLong(outp, 9, 0x43fd);
2634 smb_SetSMBParmLong(outp, 9, 0x251);
2637 * 32-bit error codes *
2641 caps = NTNEGOTIATE_CAPABILITY_NTSTATUS |
2642 NTNEGOTIATE_CAPABILITY_NTFIND |
2643 NTNEGOTIATE_CAPABILITY_RAWMODE |
2644 NTNEGOTIATE_CAPABILITY_NTSMB;
2646 if ( smb_authType == SMB_AUTH_EXTENDED )
2647 caps |= NTNEGOTIATE_CAPABILITY_EXTENDED_SECURITY;
2649 smb_SetSMBParmLong(outp, 9, caps);
2651 smb_SearchTimeFromUnixTime(&dosTime, unixTime);
2652 smb_SetSMBParmLong(outp, 11, LOWORD(dosTime));/* server time */
2653 smb_SetSMBParmLong(outp, 13, HIWORD(dosTime));/* server date */
2655 GetTimeZoneInformation(&tzi);
2656 smb_SetSMBParm(outp, 15, (unsigned short) tzi.Bias); /* server tzone */
2658 if (smb_authType == SMB_AUTH_NTLM) {
2659 smb_SetSMBParmByte(outp, 16, MSV1_0_CHALLENGE_LENGTH);/* Encryption key length */
2660 smb_SetSMBDataLength(outp, MSV1_0_CHALLENGE_LENGTH + smb_ServerDomainNameLength);
2661 /* paste in encryption key */
2662 datap = smb_GetSMBData(outp, NULL);
2663 memcpy(datap,vcp->encKey,MSV1_0_CHALLENGE_LENGTH);
2664 /* and the faux domain name */
2665 strcpy(datap + MSV1_0_CHALLENGE_LENGTH,smb_ServerDomainName);
2666 } else if ( smb_authType == SMB_AUTH_EXTENDED ) {
2670 smb_SetSMBParmByte(outp, 16, 0); /* Encryption key length */
2672 smb_NegotiateExtendedSecurity(&secBlob, &secBlobLength);
2674 smb_SetSMBDataLength(outp, secBlobLength + sizeof(smb_ServerGUID));
2676 datap = smb_GetSMBData(outp, NULL);
2677 memcpy(datap, &smb_ServerGUID, sizeof(smb_ServerGUID));
2680 datap += sizeof(smb_ServerGUID);
2681 memcpy(datap, secBlob, secBlobLength);
2685 smb_SetSMBParmByte(outp, 16, 0); /* Encryption key length */
2686 smb_SetSMBDataLength(outp, 0); /* Perhaps we should specify 8 bytes anyway */
2689 else if (v3ProtoIndex != -1) {
2690 smb_SetSMBParm(outp, 0, protoIndex);
2692 /* NOTE: Extended authentication cannot be negotiated with v3
2693 * therefore we fail over to NTLM
2695 if (smb_authType == SMB_AUTH_NTLM || smb_authType == SMB_AUTH_EXTENDED) {
2696 smb_SetSMBParm(outp, 1,
2697 NEGOTIATE_SECURITY_USER_LEVEL |
2698 NEGOTIATE_SECURITY_CHALLENGE_RESPONSE); /* user level security, challenge response */
2700 smb_SetSMBParm(outp, 1, 0); /* share level auth with clear password */
2702 smb_SetSMBParm(outp, 2, SMB_PACKETSIZE);
2703 smb_SetSMBParm(outp, 3, smb_maxMpxRequests); /* max multiplexed requests */
2704 smb_SetSMBParm(outp, 4, smb_maxVCPerServer); /* max VCs per consumer/server connection */
2705 smb_SetSMBParm(outp, 5, 0); /* no support of block mode for read or write */
2706 smb_SetSMBParm(outp, 6, 1); /* next 2: session key */
2707 smb_SetSMBParm(outp, 7, 1);
2709 smb_SearchTimeFromUnixTime(&dosTime, unixTime);
2710 smb_SetSMBParm(outp, 8, LOWORD(dosTime)); /* server time */
2711 smb_SetSMBParm(outp, 9, HIWORD(dosTime)); /* server date */
2713 GetTimeZoneInformation(&tzi);
2714 smb_SetSMBParm(outp, 10, (unsigned short) tzi.Bias); /* server tzone */
2716 /* NOTE: Extended authentication cannot be negotiated with v3
2717 * therefore we fail over to NTLM
2719 if (smb_authType == SMB_AUTH_NTLM || smb_authType == SMB_AUTH_EXTENDED) {
2720 smb_SetSMBParm(outp, 11, MSV1_0_CHALLENGE_LENGTH); /* encryption key length */
2721 smb_SetSMBParm(outp, 12, 0); /* resvd */
2722 smb_SetSMBDataLength(outp, MSV1_0_CHALLENGE_LENGTH + smb_ServerDomainNameLength); /* perhaps should specify 8 bytes anyway */
2723 datap = smb_GetSMBData(outp, NULL);
2724 /* paste in a new encryption key */
2725 memcpy(datap, vcp->encKey, MSV1_0_CHALLENGE_LENGTH);
2726 /* and the faux domain name */
2727 strcpy(datap + MSV1_0_CHALLENGE_LENGTH, smb_ServerDomainName);
2729 smb_SetSMBParm(outp, 11, 0); /* encryption key length */
2730 smb_SetSMBParm(outp, 12, 0); /* resvd */
2731 smb_SetSMBDataLength(outp, 0);
2734 else if (coreProtoIndex != -1) { /* not really supported anymore */
2735 smb_SetSMBParm(outp, 0, protoIndex);
2736 smb_SetSMBDataLength(outp, 0);
2741 void smb_Daemon(void *parmp)
2748 if ((count % 360) == 0) { /* every hour */
2751 /* Initialize smb_localZero */
2752 myTime.tm_isdst = -1; /* compute whether on DST or not */
2753 myTime.tm_year = 70;
2759 smb_localZero = mktime(&myTime);
2761 smb_CalculateNowTZ();
2763 /* XXX GC dir search entries */
2767 void smb_WaitingLocksDaemon()
2769 smb_waitingLock_t *wL, *nwL;
2772 smb_packet_t *inp, *outp;
2777 lock_ObtainWrite(&smb_globalLock);
2778 nwL = smb_allWaitingLocks;
2780 osi_SleepW((long)&smb_allWaitingLocks, &smb_globalLock);
2789 lock_ObtainWrite(&smb_globalLock);
2791 nwL = (smb_waitingLock_t *) osi_QNext(&wL->q);
2792 lock_ReleaseWrite(&smb_globalLock);
2793 code = cm_RetryLock((cm_file_lock_t *) wL->lockp,
2794 wL->vcp->flags & SMB_VCFLAG_ALREADYDEAD);
2795 if (code == CM_ERROR_WOULDBLOCK) {
2797 if (wL->timeRemaining != 0xffffffff
2798 && (wL->timeRemaining -= 1000) < 0)
2807 ncbp->ncb_length = inp->ncb_length;
2808 inp->spacep = cm_GetSpace();
2810 /* Remove waitingLock from list */
2811 lock_ObtainWrite(&smb_globalLock);
2812 osi_QRemove((osi_queue_t **)&smb_allWaitingLocks,
2814 lock_ReleaseWrite(&smb_globalLock);
2816 /* Resume packet processing */
2818 smb_SetSMBDataLength(outp, 0);
2819 outp->flags |= SMB_PACKETFLAG_SUSPENDED;
2820 outp->resumeCode = code;
2822 smb_DispatchPacket(vcp, inp, outp, ncbp, NULL);
2825 cm_FreeSpace(inp->spacep);
2826 smb_FreePacket(inp);
2827 smb_FreePacket(outp);
2835 long smb_ReceiveCoreGetDiskAttributes(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2837 osi_Log0(smb_logp, "SMB receive get disk attributes");
2839 smb_SetSMBParm(outp, 0, 32000);
2840 smb_SetSMBParm(outp, 1, 64);
2841 smb_SetSMBParm(outp, 2, 1024);
2842 smb_SetSMBParm(outp, 3, 30000);
2843 smb_SetSMBParm(outp, 4, 0);
2844 smb_SetSMBDataLength(outp, 0);
2848 long smb_ReceiveCoreTreeConnect(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *rsp)
2852 unsigned short newTid;
2853 char shareName[256];
2861 osi_Log0(smb_logp, "SMB receive tree connect");
2863 /* parse input parameters */
2864 tp = smb_GetSMBData(inp, NULL);
2865 pathp = smb_ParseASCIIBlock(tp, &tp);
2866 passwordp = smb_ParseASCIIBlock(tp, &tp);
2867 tp = strrchr(pathp, '\\');
2869 return CM_ERROR_BADSMB;
2870 strcpy(shareName, tp+1);
2872 userp = smb_GetUser(vcp, inp);
2874 lock_ObtainMutex(&vcp->mx);
2875 newTid = vcp->tidCounter++;
2876 lock_ReleaseMutex(&vcp->mx);
2878 tidp = smb_FindTID(vcp, newTid, SMB_FLAG_CREATE);
2879 uidp = smb_FindUID(vcp, ((smb_t *)inp)->uid, 0);
2880 shareFound = smb_FindShare(vcp, uidp, shareName, &sharePath);
2882 smb_ReleaseUID(uidp);
2884 smb_ReleaseTID(tidp);
2885 return CM_ERROR_BADSHARENAME;
2887 lock_ObtainMutex(&tidp->mx);
2888 tidp->userp = userp;
2889 tidp->pathname = sharePath;
2890 lock_ReleaseMutex(&tidp->mx);
2891 smb_ReleaseTID(tidp);
2893 smb_SetSMBParm(rsp, 0, SMB_PACKETSIZE);
2894 smb_SetSMBParm(rsp, 1, newTid);
2895 smb_SetSMBDataLength(rsp, 0);
2897 osi_Log1(smb_logp, "SMB tree connect created ID %d", newTid);
2901 unsigned char *smb_ParseDataBlock(unsigned char *inp, char **chainpp, int *lengthp)
2905 if (*inp++ != 0x1) return NULL;
2906 tlen = inp[0] + (inp[1]<<8);
2907 inp += 2; /* skip length field */
2910 *chainpp = inp + tlen;
2913 if (lengthp) *lengthp = tlen;
2918 /* set maskp to the mask part of the incoming path.
2919 * Mask is 11 bytes long (8.3 with the dot elided).
2920 * Returns true if succeeds with a valid name, otherwise it does
2921 * its best, but returns false.
2923 int smb_Get8Dot3MaskFromPath(unsigned char *maskp, unsigned char *pathp)
2931 /* starts off valid */
2934 /* mask starts out all blanks */
2935 memset(maskp, ' ', 11);
2937 /* find last backslash, or use whole thing if there is none */
2938 tp = strrchr(pathp, '\\');
2939 if (!tp) tp = pathp;
2940 else tp++; /* skip slash */
2944 /* names starting with a dot are illegal */
2945 if (*tp == '.') valid8Dot3 = 0;
2949 if (tc == 0) return valid8Dot3;
2950 if (tc == '.' || tc == '"') break;
2951 if (i < 8) *up++ = tc;
2952 else valid8Dot3 = 0;
2955 /* if we get here, tp point after the dot */
2956 up = maskp+8; /* ext goes here */
2963 if (tc == '.' || tc == '"')
2966 /* copy extension if not too long */
2976 int smb_Match8Dot3Mask(char *unixNamep, char *maskp)
2986 /* XXX redo this, calling smb_V3MatchMask with a converted mask */
2988 valid = smb_Get8Dot3MaskFromPath(umask, unixNamep);
2992 /* otherwise, we have a valid 8.3 name; see if we have a match,
2993 * treating '?' as a wildcard in maskp (but not in the file name).
2995 tp1 = umask; /* real name, in mask format */
2996 tp2 = maskp; /* mask, in mask format */
2997 for(i=0; i<11; i++) {
2998 tc1 = *tp1++; /* char from real name */
2999 tc2 = *tp2++; /* char from mask */
3000 tc1 = (char) cm_foldUpper[(unsigned char)tc1];
3001 tc2 = (char) cm_foldUpper[(unsigned char)tc2];
3004 if (tc2 == '?' && tc1 != ' ')
3011 /* we got a match */
3015 char *smb_FindMask(char *pathp)
3019 tp = strrchr(pathp, '\\'); /* find last slash */
3022 return tp+1; /* skip the slash */
3024 return pathp; /* no slash, return the entire path */
3027 long smb_ReceiveCoreSearchVolume(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3029 unsigned char *pathp;
3031 unsigned char mask[11];
3032 unsigned char *statBlockp;
3033 unsigned char initStatBlock[21];
3036 osi_Log0(smb_logp, "SMB receive search volume");
3038 /* pull pathname and stat block out of request */
3039 tp = smb_GetSMBData(inp, NULL);
3040 pathp = smb_ParseASCIIBlock(tp, (char **) &tp);
3041 osi_assert(pathp != NULL);
3042 statBlockp = smb_ParseVblBlock(tp, (char **) &tp, &statLen);
3043 osi_assert(statBlockp != NULL);
3045 statBlockp = initStatBlock;
3049 /* for returning to caller */
3050 smb_Get8Dot3MaskFromPath(mask, pathp);
3052 smb_SetSMBParm(outp, 0, 1); /* we're returning one entry */
3053 tp = smb_GetSMBData(outp, NULL);
3055 *tp++ = 43; /* bytes in a dir entry */
3056 *tp++ = 0; /* high byte in counter */
3058 /* now marshall the dir entry, starting with the search status */
3059 *tp++ = statBlockp[0]; /* Reserved */
3060 memcpy(tp, mask, 11); tp += 11; /* FileName */
3062 /* now pass back server use info, with 1st byte non-zero */
3064 memset(tp, 0, 4); tp += 4; /* reserved for server use */
3066 memcpy(tp, statBlockp+17, 4); tp += 4; /* reserved for consumer */
3068 *tp++ = 0x8; /* attribute: volume */
3078 /* 4 byte file size */
3084 /* finally, null-terminated 8.3 pathname, which we set to AFS */
3085 memset(tp, ' ', 13);
3088 /* set the length of the data part of the packet to 43 + 3, for the dir
3089 * entry plus the 5 and the length fields.
3091 smb_SetSMBDataLength(outp, 46);
3095 long smb_ApplyDirListPatches(smb_dirListPatch_t **dirPatchespp,
3096 cm_user_t *userp, cm_req_t *reqp)
3104 smb_dirListPatch_t *patchp;
3105 smb_dirListPatch_t *npatchp;
3107 for(patchp = *dirPatchespp; patchp; patchp =
3108 (smb_dirListPatch_t *) osi_QNext(&patchp->q)) {
3109 code = cm_GetSCache(&patchp->fid, &scp, userp, reqp);
3111 lock_ObtainMutex(&scp->mx);
3112 code = cm_SyncOp(scp, NULL, userp, reqp, 0,
3113 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3115 lock_ReleaseMutex(&scp->mx);
3116 cm_ReleaseSCache(scp);
3119 dptr = patchp->dptr;
3121 attr = smb_Attributes(scp);
3122 /* check hidden attribute (the flag is only ON when dot file hiding is on ) */
3123 if( patchp->flags & SMB_DIRLISTPATCH_DOTFILE )
3124 attr |= SMB_ATTR_HIDDEN;
3128 smb_SearchTimeFromUnixTime(&dosTime, scp->clientModTime);
3131 shortTemp = dosTime & 0xffff;
3132 *((u_short *)dptr) = shortTemp;
3135 /* and copy out date */
3136 shortTemp = (dosTime>>16) & 0xffff;
3137 *((u_short *)dptr) = shortTemp;
3140 /* copy out file length */
3141 *((u_long *)dptr) = scp->length.LowPart;
3143 lock_ReleaseMutex(&scp->mx);
3144 cm_ReleaseSCache(scp);
3147 /* now free the patches */
3148 for(patchp = *dirPatchespp; patchp; patchp = npatchp) {
3149 npatchp = (smb_dirListPatch_t *) osi_QNext(&patchp->q);
3153 /* and mark the list as empty */
3154 *dirPatchespp = NULL;
3159 long smb_ReceiveCoreSearchDir(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3168 smb_dirListPatch_t *dirListPatchesp;
3169 smb_dirListPatch_t *curPatchp;
3173 osi_hyper_t dirLength;
3174 osi_hyper_t bufferOffset;
3175 osi_hyper_t curOffset;
3177 unsigned char *inCookiep;
3178 smb_dirSearch_t *dsp;
3182 unsigned long clientCookie;
3183 cm_pageHeader_t *pageHeaderp;
3184 cm_user_t *userp = NULL;
3191 long nextEntryCookie;
3192 int numDirChunks; /* # of 32 byte dir chunks in this entry */
3193 char resByte; /* reserved byte from the cookie */
3194 char *op; /* output data ptr */
3195 char *origOp; /* original value of op */
3196 cm_space_t *spacep; /* for pathname buffer */
3207 maxCount = smb_GetSMBParm(inp, 0);
3209 dirListPatchesp = NULL;
3211 caseFold = CM_FLAG_CASEFOLD;
3213 tp = smb_GetSMBData(inp, NULL);
3214 pathp = smb_ParseASCIIBlock(tp, &tp);
3215 inCookiep = smb_ParseVblBlock(tp, &tp, &dataLength);
3217 /* bail out if request looks bad */
3218 if (!tp || !pathp) {
3219 return CM_ERROR_BADSMB;
3222 /* We can handle long names */
3223 if (vcp->flags & SMB_VCFLAG_USENT)
3224 ((smb_t *)outp)->flg2 |= 0x40; /* IS_LONG_NAME */
3226 /* make sure we got a whole search status */
3227 if (dataLength < 21) {
3228 nextCookie = 0; /* start at the beginning of the dir */
3231 attribute = smb_GetSMBParm(inp, 1);
3233 /* handle volume info in another function */
3234 if (attribute & 0x8)
3235 return smb_ReceiveCoreSearchVolume(vcp, inp, outp);
3237 osi_Log2(smb_logp, "SMB receive search dir count %d [%s]",
3238 maxCount, osi_LogSaveString(smb_logp, pathp));
3240 if (*pathp == 0) { /* null pathp, treat as root dir */
3241 if (!(attribute & SMB_ATTR_DIRECTORY)) /* exclude dirs */
3242 return CM_ERROR_NOFILES;
3246 dsp = smb_NewDirSearch(0);
3247 dsp->attribute = attribute;
3248 smb_Get8Dot3MaskFromPath(mask, pathp);
3249 memcpy(dsp->mask, mask, 11);
3251 /* track if this is likely to match a lot of entries */
3252 if (smb_IsStarMask(mask)) starPattern = 1;
3253 else starPattern = 0;
3256 /* pull the next cookie value out of the search status block */
3257 nextCookie = inCookiep[13] + (inCookiep[14]<<8) + (inCookiep[15]<<16)
3258 + (inCookiep[16]<<24);
3259 dsp = smb_FindDirSearch(inCookiep[12]);
3261 /* can't find dir search status; fatal error */
3262 return CM_ERROR_BADFD;
3264 attribute = dsp->attribute;
3265 resByte = inCookiep[0];
3267 /* copy out client cookie, in host byte order. Don't bother
3268 * interpreting it, since we're just passing it through, anyway.
3270 memcpy(&clientCookie, &inCookiep[17], 4);
3272 memcpy(mask, dsp->mask, 11);
3274 /* assume we're doing a star match if it has continued for more
3280 osi_Log3(smb_logp, "SMB dir search cookie 0x%x, connection %d, attr 0x%x",
3281 nextCookie, dsp->cookie, attribute);
3283 userp = smb_GetUser(vcp, inp);
3285 /* try to get the vnode for the path name next */
3286 lock_ObtainMutex(&dsp->mx);
3293 spacep = inp->spacep;
3294 smb_StripLastComponent(spacep->data, NULL, pathp);
3295 lock_ReleaseMutex(&dsp->mx);
3296 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3297 code = cm_NameI(cm_rootSCachep, spacep->data,
3298 caseFold | CM_FLAG_FOLLOW, userp, tidPathp, &req, &scp);
3299 lock_ObtainMutex(&dsp->mx);
3301 if (dsp->scp != 0) cm_ReleaseSCache(dsp->scp);
3303 /* we need one hold for the entry we just stored into,
3304 * and one for our own processing. When we're done with this
3305 * function, we'll drop the one for our own processing.
3306 * We held it once from the namei call, and so we do another hold
3310 lock_ObtainMutex(&scp->mx);
3311 if ((scp->flags & CM_SCACHEFLAG_BULKSTATTING) == 0
3312 && LargeIntegerGreaterOrEqualToZero(scp->bulkStatProgress)) {
3313 scp->flags |= CM_SCACHEFLAG_BULKSTATTING;
3314 dsp->flags |= SMB_DIRSEARCH_BULKST;
3316 lock_ReleaseMutex(&scp->mx);
3319 lock_ReleaseMutex(&dsp->mx);
3321 cm_ReleaseUser(userp);
3322 smb_DeleteDirSearch(dsp);
3323 smb_ReleaseDirSearch(dsp);
3327 /* reserves space for parameter; we'll adjust it again later to the
3328 * real count of the # of entries we returned once we've actually
3329 * assembled the directory listing.
3331 smb_SetSMBParm(outp, 0, 0);
3333 /* get the directory size */
3334 lock_ObtainMutex(&scp->mx);
3335 code = cm_SyncOp(scp, NULL, userp, &req, 0,
3336 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3338 lock_ReleaseMutex(&scp->mx);
3339 cm_ReleaseSCache(scp);
3340 cm_ReleaseUser(userp);
3341 smb_DeleteDirSearch(dsp);
3342 smb_ReleaseDirSearch(dsp);
3346 dirLength = scp->length;
3348 bufferOffset.LowPart = bufferOffset.HighPart = 0;
3349 curOffset.HighPart = 0;
3350 curOffset.LowPart = nextCookie;
3351 origOp = op = smb_GetSMBData(outp, NULL);
3352 /* and write out the basic header */
3353 *op++ = 5; /* variable block */
3354 op += 2; /* skip vbl block length; we'll fill it in later */
3358 /* make sure that curOffset.LowPart doesn't point to the first
3359 * 32 bytes in the 2nd through last dir page, and that it doesn't
3360 * point at the first 13 32-byte chunks in the first dir page,
3361 * since those are dir and page headers, and don't contain useful
3364 temp = curOffset.LowPart & (2048-1);
3365 if (curOffset.HighPart == 0 && curOffset.LowPart < 2048) {
3366 /* we're in the first page */
3367 if (temp < 13*32) temp = 13*32;
3370 /* we're in a later dir page */
3371 if (temp < 32) temp = 32;
3374 /* make sure the low order 5 bits are zero */
3377 /* now put temp bits back ito curOffset.LowPart */
3378 curOffset.LowPart &= ~(2048-1);
3379 curOffset.LowPart |= temp;
3381 /* check if we've returned all the names that will fit in the
3384 if (returnedNames >= maxCount)
3387 /* check if we've passed the dir's EOF */
3388 if (LargeIntegerGreaterThanOrEqualTo(curOffset, dirLength)) break;
3390 /* see if we can use the bufferp we have now; compute in which page
3391 * the current offset would be, and check whether that's the offset
3392 * of the buffer we have. If not, get the buffer.
3394 thyper.HighPart = curOffset.HighPart;
3395 thyper.LowPart = curOffset.LowPart & ~(buf_bufferSize-1);
3396 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
3399 buf_Release(bufferp);
3402 lock_ReleaseMutex(&scp->mx);
3403 lock_ObtainRead(&scp->bufCreateLock);
3404 code = buf_Get(scp, &thyper, &bufferp);
3405 lock_ReleaseRead(&scp->bufCreateLock);
3407 /* now, if we're doing a star match, do bulk fetching of all of
3408 * the status info for files in the dir.
3411 smb_ApplyDirListPatches(&dirListPatchesp, userp,
3413 if ((dsp->flags & SMB_DIRSEARCH_BULKST)
3414 && LargeIntegerGreaterThanOrEqualTo(thyper,
3415 scp->bulkStatProgress)) {
3416 /* Don't bulk stat if risking timeout */
3417 int now = GetCurrentTime();
3418 if (now - req.startTime > 5000) {
3419 scp->bulkStatProgress = thyper;
3420 scp->flags &= ~CM_SCACHEFLAG_BULKSTATTING;
3421 dsp->flags &= ~SMB_DIRSEARCH_BULKST;
3423 cm_TryBulkStat(scp, &thyper, userp, &req);
3427 lock_ObtainMutex(&scp->mx);
3430 bufferOffset = thyper;
3432 /* now get the data in the cache */
3434 code = cm_SyncOp(scp, bufferp, userp, &req,
3436 CM_SCACHESYNC_NEEDCALLBACK
3437 | CM_SCACHESYNC_READ);
3440 if (cm_HaveBuffer(scp, bufferp, 0)) break;
3442 /* otherwise, load the buffer and try again */
3443 code = cm_GetBuffer(scp, bufferp, NULL, userp,
3448 buf_Release(bufferp);
3452 } /* if (wrong buffer) ... */
3454 /* now we have the buffer containing the entry we're interested in; copy
3455 * it out if it represents a non-deleted entry.
3457 entryInDir = curOffset.LowPart & (2048-1);
3458 entryInBuffer = curOffset.LowPart & (buf_bufferSize - 1);
3460 /* page header will help tell us which entries are free. Page header
3461 * can change more often than once per buffer, since AFS 3 dir page size
3462 * may be less than (but not more than a buffer package buffer.
3464 temp = curOffset.LowPart & (buf_bufferSize - 1); /* only look intra-buffer */
3465 temp &= ~(2048 - 1); /* turn off intra-page bits */
3466 pageHeaderp = (cm_pageHeader_t *) (bufferp->datap + temp);
3468 /* now determine which entry we're looking at in the page. If it is
3469 * free (there's a free bitmap at the start of the dir), we should
3470 * skip these 32 bytes.
3472 slotInPage = (entryInDir & 0x7e0) >> 5;
3473 if (!(pageHeaderp->freeBitmap[slotInPage>>3] & (1 << (slotInPage & 0x7)))) {
3474 /* this entry is free */
3475 numDirChunks = 1; /* only skip this guy */
3479 tp = bufferp->datap + entryInBuffer;
3480 dep = (cm_dirEntry_t *) tp; /* now points to AFS3 dir entry */
3482 /* while we're here, compute the next entry's location, too,
3483 * since we'll need it when writing out the cookie into the dir
3486 * XXXX Probably should do more sanity checking.
3488 numDirChunks = cm_NameEntries(dep->name, NULL);
3490 /* compute the offset of the cookie representing the next entry */
3491 nextEntryCookie = curOffset.LowPart + (CM_DIR_CHUNKSIZE * numDirChunks);
3493 /* Compute 8.3 name if necessary */
3494 actualName = dep->name;
3495 if (dep->fid.vnode != 0 && !cm_Is8Dot3(actualName)) {
3496 cm_Gen8Dot3Name(dep, shortName, &shortNameEnd);
3497 actualName = shortName;
3500 if (dep->fid.vnode != 0 && smb_Match8Dot3Mask(actualName, mask)) {
3501 /* this is one of the entries to use: it is not deleted
3502 * and it matches the star pattern we're looking for.
3505 /* Eliminate entries that don't match requested
3508 /* no hidden files */
3509 if(smb_hideDotFiles && !(dsp->attribute & SMB_ATTR_HIDDEN) && smb_IsDotFile(actualName))
3512 if (!(dsp->attribute & SMB_ATTR_DIRECTORY)) /* no directories */
3514 /* We have already done the cm_TryBulkStat above */
3515 fid.cell = scp->fid.cell;
3516 fid.volume = scp->fid.volume;
3517 fid.vnode = ntohl(dep->fid.vnode);
3518 fid.unique = ntohl(dep->fid.unique);
3519 fileType = cm_FindFileType(&fid);
3520 osi_Log2(smb_logp, "smb_ReceiveCoreSearchDir: file %s "
3521 "has filetype %d", dep->name,
3523 if (fileType == CM_SCACHETYPE_DIRECTORY)
3528 memcpy(op, mask, 11); op += 11;
3529 *op++ = (char) dsp->cookie; /* they say it must be non-zero */
3530 *op++ = nextEntryCookie & 0xff;
3531 *op++ = (nextEntryCookie>>8) & 0xff;
3532 *op++ = (nextEntryCookie>>16) & 0xff;
3533 *op++ = (nextEntryCookie>>24) & 0xff;
3534 memcpy(op, &clientCookie, 4); op += 4;
3536 /* now we emit the attribute. This is sort of tricky,
3537 * since we need to really stat the file to find out
3538 * what type of entry we've got. Right now, we're
3539 * copying out data from a buffer, while holding the
3540 * scp locked, so it isn't really convenient to stat
3541 * something now. We'll put in a place holder now,
3542 * and make a second pass before returning this to get
3543 * the real attributes. So, we just skip the data for
3544 * now, and adjust it later. We allocate a patch
3545 * record to make it easy to find this point later.
3546 * The replay will happen at a time when it is safe to
3547 * unlock the directory.
3549 curPatchp = malloc(sizeof(*curPatchp));
3550 osi_QAdd((osi_queue_t **) &dirListPatchesp, &curPatchp->q);
3551 curPatchp->dptr = op;
3552 curPatchp->fid.cell = scp->fid.cell;
3553 curPatchp->fid.volume = scp->fid.volume;
3554 curPatchp->fid.vnode = ntohl(dep->fid.vnode);
3555 curPatchp->fid.unique = ntohl(dep->fid.unique);
3557 /* do hidden attribute here since name won't be around when applying
3561 if ( smb_hideDotFiles && smb_IsDotFile(actualName) )
3562 curPatchp->flags = SMB_DIRLISTPATCH_DOTFILE;
3564 curPatchp->flags = 0;
3566 op += 9; /* skip attr, time, date and size */
3568 /* zero out name area. The spec says to pad with
3569 * spaces, but Samba doesn't, and neither do we.
3573 /* finally, we get to copy out the name; we know that
3574 * it fits in 8.3 or the pattern wouldn't match, but it
3575 * never hurts to be sure.
3577 strncpy(op, actualName, 13);
3579 /* Uppercase if requested by client */
3580 if ((((smb_t *)inp)->flg2 & 1) == 0)
3585 /* now, adjust the # of entries copied */
3587 } /* if we're including this name */
3590 /* and adjust curOffset to be where the new cookie is */
3591 thyper.HighPart = 0;
3592 thyper.LowPart = CM_DIR_CHUNKSIZE * numDirChunks;
3593 curOffset = LargeIntegerAdd(thyper, curOffset);
3594 } /* while copying data for dir listing */
3596 /* release the mutex */
3597 lock_ReleaseMutex(&scp->mx);
3598 if (bufferp) buf_Release(bufferp);
3600 /* apply and free last set of patches; if not doing a star match, this
3601 * will be empty, but better safe (and freeing everything) than sorry.
3603 smb_ApplyDirListPatches(&dirListPatchesp, userp, &req);
3605 /* special return code for unsuccessful search */
3606 if (code == 0 && dataLength < 21 && returnedNames == 0)
3607 code = CM_ERROR_NOFILES;
3609 osi_Log2(smb_logp, "SMB search dir done, %d names, code %d",
3610 returnedNames, code);
3613 smb_DeleteDirSearch(dsp);
3614 smb_ReleaseDirSearch(dsp);
3615 cm_ReleaseSCache(scp);
3616 cm_ReleaseUser(userp);
3620 /* finalize the output buffer */
3621 smb_SetSMBParm(outp, 0, returnedNames);
3622 temp = (long) (op - origOp);
3623 smb_SetSMBDataLength(outp, temp);
3625 /* the data area is a variable block, which has a 5 (already there)
3626 * followed by the length of the # of data bytes. We now know this to
3627 * be "temp," although that includes the 3 bytes of vbl block header.
3628 * Deduct for them and fill in the length field.
3630 temp -= 3; /* deduct vbl block info */
3631 osi_assert(temp == (43 * returnedNames));
3632 origOp[1] = temp & 0xff;
3633 origOp[2] = (temp>>8) & 0xff;
3634 if (returnedNames == 0) smb_DeleteDirSearch(dsp);
3635 smb_ReleaseDirSearch(dsp);
3636 cm_ReleaseSCache(scp);
3637 cm_ReleaseUser(userp);
3641 /* verify that this is a valid path to a directory. I don't know why they
3642 * don't use the get file attributes call.
3644 long smb_ReceiveCoreCheckPath(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3648 cm_scache_t *rootScp;
3649 cm_scache_t *newScp;
3658 pathp = smb_GetSMBData(inp, NULL);
3659 pathp = smb_ParseASCIIBlock(pathp, NULL);
3660 osi_Log1(smb_logp, "SMB receive check path %s",
3661 osi_LogSaveString(smb_logp, pathp));
3664 return CM_ERROR_BADFD;
3667 rootScp = cm_rootSCachep;
3669 userp = smb_GetUser(vcp, inp);
3671 caseFold = CM_FLAG_CASEFOLD;
3673 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3674 code = cm_NameI(rootScp, pathp,
3675 caseFold | CM_FLAG_FOLLOW | CM_FLAG_CHECKPATH,
3676 userp, tidPathp, &req, &newScp);
3679 cm_ReleaseUser(userp);
3683 /* now lock the vnode with a callback; returns with newScp locked */
3684 lock_ObtainMutex(&newScp->mx);
3685 code = cm_SyncOp(newScp, NULL, userp, &req, PRSFS_LOOKUP,
3686 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
3687 if (code && code != CM_ERROR_NOACCESS) {
3688 lock_ReleaseMutex(&newScp->mx);
3689 cm_ReleaseSCache(newScp);
3690 cm_ReleaseUser(userp);
3694 attrs = smb_Attributes(newScp);
3696 if (!(attrs & 0x10))
3697 code = CM_ERROR_NOTDIR;
3699 lock_ReleaseMutex(&newScp->mx);
3701 cm_ReleaseSCache(newScp);
3702 cm_ReleaseUser(userp);
3706 long smb_ReceiveCoreSetFileAttributes(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3710 cm_scache_t *rootScp;
3711 unsigned short attribute;
3713 cm_scache_t *newScp;
3722 /* decode basic attributes we're passed */
3723 attribute = smb_GetSMBParm(inp, 0);
3724 dosTime = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
3726 pathp = smb_GetSMBData(inp, NULL);
3727 pathp = smb_ParseASCIIBlock(pathp, NULL);
3730 return CM_ERROR_BADSMB;
3733 osi_Log2(smb_logp, "SMB receive setfile attributes time %d, attr 0x%x",
3734 dosTime, attribute);
3736 rootScp = cm_rootSCachep;
3738 userp = smb_GetUser(vcp, inp);
3740 caseFold = CM_FLAG_CASEFOLD;
3742 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3743 code = cm_NameI(rootScp, pathp, caseFold | CM_FLAG_FOLLOW, userp,
3744 tidPathp, &req, &newScp);
3747 cm_ReleaseUser(userp);
3751 /* now lock the vnode with a callback; returns with newScp locked; we
3752 * need the current status to determine what the new status is, in some
3755 lock_ObtainMutex(&newScp->mx);
3756 code = cm_SyncOp(newScp, NULL, userp, &req, 0,
3757 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
3759 lock_ReleaseMutex(&newScp->mx);
3760 cm_ReleaseSCache(newScp);
3761 cm_ReleaseUser(userp);
3765 /* Check for RO volume */
3766 if (newScp->flags & CM_SCACHEFLAG_RO) {
3767 lock_ReleaseMutex(&newScp->mx);
3768 cm_ReleaseSCache(newScp);
3769 cm_ReleaseUser(userp);
3770 return CM_ERROR_READONLY;
3773 /* prepare for setattr call */
3776 attr.mask |= CM_ATTRMASK_CLIENTMODTIME;
3777 smb_UnixTimeFromDosUTime(&attr.clientModTime, dosTime);
3779 if ((newScp->unixModeBits & 0222) && (attribute & 1) != 0) {
3780 /* we're told to make a writable file read-only */
3781 attr.unixModeBits = newScp->unixModeBits & ~0222;
3782 attr.mask |= CM_ATTRMASK_UNIXMODEBITS;
3784 else if ((newScp->unixModeBits & 0222) == 0 && (attribute & 1) == 0) {
3785 /* we're told to make a read-only file writable */
3786 attr.unixModeBits = newScp->unixModeBits | 0222;
3787 attr.mask |= CM_ATTRMASK_UNIXMODEBITS;
3789 lock_ReleaseMutex(&newScp->mx);
3791 /* now call setattr */
3793 code = cm_SetAttr(newScp, &attr, userp, &req);
3797 cm_ReleaseSCache(newScp);
3798 cm_ReleaseUser(userp);
3803 long smb_ReceiveCoreGetFileAttributes(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3807 cm_scache_t *rootScp;
3808 cm_scache_t *newScp, *dscp;
3820 pathp = smb_GetSMBData(inp, NULL);
3821 pathp = smb_ParseASCIIBlock(pathp, NULL);
3824 return CM_ERROR_BADSMB;
3827 if (*pathp == 0) /* null path */
3830 osi_Log1(smb_logp, "SMB receive getfile attributes path %s",
3831 osi_LogSaveString(smb_logp, pathp));
3833 rootScp = cm_rootSCachep;
3835 userp = smb_GetUser(vcp, inp);
3837 /* we shouldn't need this for V3 requests, but we seem to */
3838 caseFold = CM_FLAG_CASEFOLD;
3840 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3843 * XXX Strange hack XXX
3845 * As of Patch 5 (16 July 97), we are having the following problem:
3846 * In NT Explorer 4.0, whenever we click on a directory, AFS gets
3847 * requests to look up "desktop.ini" in all the subdirectories.
3848 * This can cause zillions of timeouts looking up non-existent cells
3849 * and volumes, especially in the top-level directory.
3851 * We have not found any way to avoid this or work around it except
3852 * to explicitly ignore the requests for mount points that haven't
3853 * yet been evaluated and for directories that haven't yet been
3856 * We should modify this hack to provide a fake desktop.ini file
3857 * http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/custom.asp
3859 spacep = inp->spacep;
3860 smb_StripLastComponent(spacep->data, &lastComp, pathp);
3861 if (lastComp && stricmp(lastComp, "\\desktop.ini") == 0) {
3862 code = cm_NameI(rootScp, spacep->data,
3863 caseFold | CM_FLAG_DIRSEARCH | CM_FLAG_FOLLOW,
3864 userp, tidPathp, &req, &dscp);
3866 if (dscp->fileType == CM_SCACHETYPE_MOUNTPOINT
3867 && !dscp->mountRootFidp)
3868 code = CM_ERROR_NOSUCHFILE;
3869 else if (dscp->fileType == CM_SCACHETYPE_DIRECTORY) {
3870 cm_buf_t *bp = buf_Find(dscp, &hzero);
3874 code = CM_ERROR_NOSUCHFILE;
3876 cm_ReleaseSCache(dscp);
3878 cm_ReleaseUser(userp);
3884 code = cm_NameI(rootScp, pathp, caseFold | CM_FLAG_FOLLOW, userp,
3885 tidPathp, &req, &newScp);
3888 cm_ReleaseUser(userp);
3892 /* now lock the vnode with a callback; returns with newScp locked */
3893 lock_ObtainMutex(&newScp->mx);
3894 code = cm_SyncOp(newScp, NULL, userp, &req, 0,
3895 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
3897 lock_ReleaseMutex(&newScp->mx);
3898 cm_ReleaseSCache(newScp);
3899 cm_ReleaseUser(userp);
3904 /* use smb_Attributes instead. Also the fact that a file is
3905 * in a readonly volume doesn't mean it shojuld be marked as RO
3907 if (newScp->fileType == CM_SCACHETYPE_DIRECTORY
3908 || newScp->fileType == CM_SCACHETYPE_MOUNTPOINT)
3909 attrs = SMB_ATTR_DIRECTORY;
3912 if ((newScp->unixModeBits & 0222) == 0 || (newScp->flags & CM_SCACHEFLAG_RO))
3913 attrs |= SMB_ATTR_READONLY; /* turn on read-only flag */
3915 attrs = smb_Attributes(newScp);
3918 smb_SetSMBParm(outp, 0, attrs);
3920 smb_DosUTimeFromUnixTime(&dosTime, newScp->clientModTime);
3921 smb_SetSMBParm(outp, 1, dosTime & 0xffff);
3922 smb_SetSMBParm(outp, 2, (dosTime>>16) & 0xffff);
3923 smb_SetSMBParm(outp, 3, newScp->length.LowPart & 0xffff);
3924 smb_SetSMBParm(outp, 4, (newScp->length.LowPart >> 16) & 0xffff);
3925 smb_SetSMBParm(outp, 5, 0);
3926 smb_SetSMBParm(outp, 6, 0);
3927 smb_SetSMBParm(outp, 7, 0);
3928 smb_SetSMBParm(outp, 8, 0);
3929 smb_SetSMBParm(outp, 9, 0);
3930 smb_SetSMBDataLength(outp, 0);
3931 lock_ReleaseMutex(&newScp->mx);
3933 cm_ReleaseSCache(newScp);
3934 cm_ReleaseUser(userp);
3939 long smb_ReceiveCoreTreeDisconnect(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3943 osi_Log0(smb_logp, "SMB receive tree disconnect");
3945 /* find the tree and free it */
3946 tidp = smb_FindTID(vcp, ((smb_t *)inp)->tid, 0);
3948 lock_ObtainMutex(&tidp->mx);
3949 tidp->flags |= SMB_TIDFLAG_DELETE;
3950 lock_ReleaseMutex(&tidp->mx);
3951 smb_ReleaseTID(tidp);
3957 long smb_ReceiveCoreOpen(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3975 pathp = smb_GetSMBData(inp, NULL);
3976 pathp = smb_ParseASCIIBlock(pathp, NULL);
3978 osi_Log1(smb_logp, "SMB receive open file [%s]", osi_LogSaveString(smb_logp, pathp));
3980 #ifdef DEBUG_VERBOSE
3984 hexpath = osi_HexifyString( pathp );
3985 DEBUG_EVENT2("AFS", "CoreOpen H[%s] A[%s]", hexpath, pathp);
3990 share = smb_GetSMBParm(inp, 0);
3991 attribute = smb_GetSMBParm(inp, 1);
3993 spacep = inp->spacep;
3994 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
3995 if (lastNamep && strcmp(lastNamep, SMB_IOCTL_FILENAME) == 0) {
3996 /* special case magic file name for receiving IOCTL requests
3997 * (since IOCTL calls themselves aren't getting through).
3999 fidp = smb_FindFID(vcp, 0, SMB_FLAG_CREATE);
4000 smb_SetupIoctlFid(fidp, spacep);
4001 smb_SetSMBParm(outp, 0, fidp->fid);
4002 smb_SetSMBParm(outp, 1, 0); /* attrs */
4003 smb_SetSMBParm(outp, 2, 0); /* next 2 are DOS time */
4004 smb_SetSMBParm(outp, 3, 0);
4005 smb_SetSMBParm(outp, 4, 0); /* next 2 are length */
4006 smb_SetSMBParm(outp, 5, 0x7fff);
4007 /* pass the open mode back */
4008 smb_SetSMBParm(outp, 6, (share & 0xf));
4009 smb_SetSMBDataLength(outp, 0);
4010 smb_ReleaseFID(fidp);
4014 userp = smb_GetUser(vcp, inp);
4016 caseFold = CM_FLAG_CASEFOLD;
4018 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
4019 code = cm_NameI(cm_rootSCachep, pathp, caseFold | CM_FLAG_FOLLOW, userp,
4020 tidPathp, &req, &scp);
4023 cm_ReleaseUser(userp);
4027 code = cm_CheckOpen(scp, share & 0x7, 0, userp, &req);
4029 cm_ReleaseSCache(scp);
4030 cm_ReleaseUser(userp);
4034 /* don't need callback to check file type, since file types never
4035 * change, and namei and cm_Lookup all stat the object at least once on
4036 * a successful return.
4038 if (scp->fileType != CM_SCACHETYPE_FILE) {
4039 cm_ReleaseSCache(scp);
4040 cm_ReleaseUser(userp);
4041 return CM_ERROR_ISDIR;
4044 fidp = smb_FindFID(vcp, 0, SMB_FLAG_CREATE);
4047 /* save a pointer to the vnode */
4050 if ((share & 0xf) == 0)
4051 fidp->flags |= SMB_FID_OPENREAD;
4052 else if ((share & 0xf) == 1)
4053 fidp->flags |= SMB_FID_OPENWRITE;
4055 fidp->flags |= (SMB_FID_OPENREAD | SMB_FID_OPENWRITE);
4057 lock_ObtainMutex(&scp->mx);
4058 smb_SetSMBParm(outp, 0, fidp->fid);
4059 smb_SetSMBParm(outp, 1, smb_Attributes(scp));
4060 smb_DosUTimeFromUnixTime(&dosTime, scp->clientModTime);
4061 smb_SetSMBParm(outp, 2, dosTime & 0xffff);
4062 smb_SetSMBParm(outp, 3, (dosTime >> 16) & 0xffff);
4063 smb_SetSMBParm(outp, 4, scp->length.LowPart & 0xffff);
4064 smb_SetSMBParm(outp, 5, (scp->length.LowPart >> 16) & 0xffff);
4065 /* pass the open mode back; XXXX add access checks */
4066 smb_SetSMBParm(outp, 6, (share & 0xf));
4067 smb_SetSMBDataLength(outp, 0);
4068 lock_ReleaseMutex(&scp->mx);
4071 cm_Open(scp, 0, userp);
4073 /* send and free packet */
4074 smb_ReleaseFID(fidp);
4075 cm_ReleaseUser(userp);
4076 /* don't release scp, since we've squirreled away the pointer in the fid struct */
4080 typedef struct smb_unlinkRock {
4085 char *maskp; /* pointer to the star pattern */
4090 int smb_UnlinkProc(cm_scache_t *dscp, cm_dirEntry_t *dep, void *vrockp, osi_hyper_t *offp)
4093 smb_unlinkRock_t *rockp;
4101 caseFold = ((rockp->flags & SMB_MASKFLAG_CASEFOLD)? CM_FLAG_CASEFOLD : 0);
4102 if (!(rockp->vcp->flags & SMB_VCFLAG_USEV3))
4103 caseFold |= CM_FLAG_8DOT3;
4105 matchName = dep->name;
4106 match = smb_V3MatchMask(matchName, rockp->maskp, caseFold);
4108 && (rockp->flags & SMB_MASKFLAG_TILDE)
4109 && !cm_Is8Dot3(dep->name)) {
4110 cm_Gen8Dot3Name(dep, shortName, NULL);
4111 matchName = shortName;
4112 /* 8.3 matches are always case insensitive */
4113 match = smb_V3MatchMask(matchName, rockp->maskp, caseFold | CM_FLAG_CASEFOLD);
4116 osi_Log1(smb_logp, "Unlinking %s",
4117 osi_LogSaveString(smb_logp, matchName));
4118 code = cm_Unlink(dscp, dep->name, rockp->userp, rockp->reqp);
4119 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4120 smb_NotifyChange(FILE_ACTION_REMOVED,
4121 FILE_NOTIFY_CHANGE_FILE_NAME,
4122 dscp, dep->name, NULL, TRUE);
4125 /* If we made a case sensitive exact match, we might as well quit now. */
4126 if(!(rockp->flags & SMB_MASKFLAG_CASEFOLD) && !strcmp(matchName, rockp->maskp))
4127 code = CM_ERROR_STOPNOW;
4135 long smb_ReceiveCoreUnlink(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4144 smb_unlinkRock_t rock;
4153 attribute = smb_GetSMBParm(inp, 0);
4155 tp = smb_GetSMBData(inp, NULL);
4156 pathp = smb_ParseASCIIBlock(tp, &tp);
4158 osi_Log1(smb_logp, "SMB receive unlink %s",
4159 osi_LogSaveString(smb_logp, pathp));
4161 spacep = inp->spacep;
4162 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
4164 userp = smb_GetUser(vcp, inp);
4166 caseFold = CM_FLAG_FOLLOW | CM_FLAG_CASEFOLD;
4168 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
4169 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold, userp, tidPathp,
4173 cm_ReleaseUser(userp);
4177 /* otherwise, scp points to the parent directory. */
4184 rock.maskp = smb_FindMask(pathp);
4185 rock.flags = ((strchr(rock.maskp, '~') != NULL) ? SMB_MASKFLAG_TILDE : 0);
4188 thyper.HighPart = 0;
4194 /* Now, if we aren't dealing with a wildcard match, we first try an exact
4195 * match. If that fails, we do a case insensitve match.
4197 if (!(rock.flags & SMB_MASKFLAG_TILDE) &&
4198 !smb_IsStarMask(rock.maskp)) {
4199 code = cm_ApplyDir(dscp, smb_UnlinkProc, &rock, &thyper, userp, &req, NULL);
4202 thyper.HighPart = 0;
4203 rock.flags |= SMB_MASKFLAG_CASEFOLD;
4208 code = cm_ApplyDir(dscp, smb_UnlinkProc, &rock, &thyper, userp, &req, NULL);
4210 if (code == CM_ERROR_STOPNOW)
4213 cm_ReleaseUser(userp);
4215 cm_ReleaseSCache(dscp);
4217 if (code == 0 && !rock.any)
4218 code = CM_ERROR_NOSUCHFILE;
4222 typedef struct smb_renameRock {
4223 cm_scache_t *odscp; /* old dir */
4224 cm_scache_t *ndscp; /* new dir */
4225 cm_user_t *userp; /* user */
4226 cm_req_t *reqp; /* request struct */
4227 smb_vc_t *vcp; /* virtual circuit */
4228 char *maskp; /* pointer to star pattern of old file name */
4229 int flags; /* tilde, casefold, etc */
4230 char *newNamep; /* ptr to the new file's name */
4233 int smb_RenameProc(cm_scache_t *dscp, cm_dirEntry_t *dep, void *vrockp, osi_hyper_t *offp)
4236 smb_renameRock_t *rockp;
4241 rockp = (smb_renameRock_t *) vrockp;
4243 caseFold = ((rockp->flags & SMB_MASKFLAG_CASEFOLD)? CM_FLAG_CASEFOLD : 0);
4244 if (!(rockp->vcp->flags & SMB_VCFLAG_USEV3))
4245 caseFold |= CM_FLAG_8DOT3;
4247 match = smb_V3MatchMask(dep->name, rockp->maskp, caseFold);
4249 && (rockp->flags & SMB_MASKFLAG_TILDE)
4250 && !cm_Is8Dot3(dep->name)) {
4251 cm_Gen8Dot3Name(dep, shortName, NULL);
4252 match = smb_V3MatchMask(shortName, rockp->maskp, caseFold);
4255 code = cm_Rename(rockp->odscp, dep->name,
4256 rockp->ndscp, rockp->newNamep, rockp->userp,
4258 /* if the call worked, stop doing the search now, since we
4259 * really only want to rename one file.
4262 code = CM_ERROR_STOPNOW;
4269 long smb_ReceiveCoreRename(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4275 cm_space_t *spacep = NULL;
4276 smb_renameRock_t rock;
4277 cm_scache_t *oldDscp = NULL;
4278 cm_scache_t *newDscp = NULL;
4279 cm_scache_t *tmpscp= NULL;
4280 cm_scache_t *tmpscp2 = NULL;
4292 tp = smb_GetSMBData(inp, NULL);
4293 oldPathp = smb_ParseASCIIBlock(tp, &tp);
4294 newPathp = smb_ParseASCIIBlock(tp, &tp);
4296 osi_Log2(smb_logp, "smb rename [%s] to [%s]",
4297 osi_LogSaveString(smb_logp, oldPathp),
4298 osi_LogSaveString(smb_logp, newPathp));
4300 spacep = inp->spacep;
4301 smb_StripLastComponent(spacep->data, &oldLastNamep, oldPathp);
4303 userp = smb_GetUser(vcp, inp);
4306 * Changed to use CASEFOLD always. This enables us to rename Foo/baz when
4307 * what actually exists is foo/baz. I don't know why the code used to be
4308 * the way it was. 1/29/96
4310 * caseFold = ((vcp->flags & SMB_VCFLAG_USEV3) ? 0: CM_FLAG_CASEFOLD);
4312 * Changed to use CM_FLAG_FOLLOW. 7/24/96
4314 * caseFold = CM_FLAG_CASEFOLD;
4316 caseFold = CM_FLAG_FOLLOW | CM_FLAG_CASEFOLD;
4318 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
4319 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold,
4320 userp, tidPathp, &req, &oldDscp);
4323 cm_ReleaseUser(userp);
4327 smb_StripLastComponent(spacep->data, &newLastNamep, newPathp);
4328 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold,
4329 userp, tidPathp, &req, &newDscp);
4332 cm_ReleaseSCache(oldDscp);
4333 cm_ReleaseUser(userp);
4337 /* otherwise, oldDscp and newDscp point to the corresponding directories.
4338 * next, get the component names, and lower case them.
4341 /* handle the old name first */
4343 oldLastNamep = oldPathp;
4347 /* and handle the new name, too */
4349 newLastNamep = newPathp;
4353 /* TODO: The old name could be a wildcard. The new name must not be */
4355 /* do the vnode call */
4356 rock.odscp = oldDscp;
4357 rock.ndscp = newDscp;
4361 rock.maskp = oldLastNamep;
4362 rock.flags = ((strchr(oldLastNamep, '~') != NULL) ? SMB_MASKFLAG_TILDE : 0);
4363 rock.newNamep = newLastNamep;
4365 /* Check if the file already exists; if so return error */
4366 code = cm_Lookup(newDscp,newLastNamep,CM_FLAG_CHECKPATH,userp,&req,&tmpscp);
4367 if ((code != CM_ERROR_NOSUCHFILE) && (code != CM_ERROR_NOSUCHPATH) && (code != CM_ERROR_NOSUCHVOLUME) ) {
4368 osi_Log2(afsd_logp, " lookup returns %ld for [%s]", code,
4369 osi_LogSaveString(afsd_logp, newLastNamep));
4371 /* Check if the old and the new names differ only in case. If so return
4372 * success, else return CM_ERROR_EXISTS
4374 if (!code && oldDscp == newDscp && !stricmp(oldLastNamep, newLastNamep)) {
4376 /* This would be a success only if the old file is *as same as* the new file */
4377 code = cm_Lookup(oldDscp, oldLastNamep, CM_FLAG_CHECKPATH, userp, &req, &tmpscp2);
4379 if (tmpscp == tmpscp2)
4382 code = CM_ERROR_EXISTS;
4383 cm_ReleaseSCache(tmpscp2);
4386 code = CM_ERROR_NOSUCHFILE;
4389 /* file exist, do not rename, also fixes move */
4390 osi_Log0(afsd_logp, "Can't rename. Target already exists");
4391 code = CM_ERROR_EXISTS;
4395 cm_ReleaseSCache(tmpscp);
4396 cm_ReleaseSCache(newDscp);
4397 cm_ReleaseSCache(oldDscp);
4398 cm_ReleaseUser(userp);
4402 /* Now search the directory for the pattern, and do the appropriate rename when found */
4403 thyper.LowPart = 0; /* search dir from here */
4404 thyper.HighPart = 0;
4406 code = cm_ApplyDir(oldDscp, smb_RenameProc, &rock, &thyper, userp, &req, NULL);
4408 if (code == CM_ERROR_STOPNOW)
4411 code = CM_ERROR_NOSUCHFILE;
4413 /* Handle Change Notification */
4415 * Being lazy, not distinguishing between files and dirs in this
4416 * filter, since we'd have to do a lookup.
4418 filter = FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME;
4419 if (oldDscp == newDscp) {
4420 if (oldDscp->flags & CM_SCACHEFLAG_ANYWATCH)
4421 smb_NotifyChange(FILE_ACTION_RENAMED_OLD_NAME,
4422 filter, oldDscp, oldLastNamep,
4423 newLastNamep, TRUE);
4425 if (oldDscp->flags & CM_SCACHEFLAG_ANYWATCH)
4426 smb_NotifyChange(FILE_ACTION_RENAMED_OLD_NAME,
4427 filter, oldDscp, oldLastNamep,
4429 if (newDscp->flags & CM_SCACHEFLAG_ANYWATCH)
4430 smb_NotifyChange(FILE_ACTION_RENAMED_NEW_NAME,
4431 filter, newDscp, newLastNamep,
4436 cm_ReleaseSCache(tmpscp);
4437 cm_ReleaseUser(userp);
4438 cm_ReleaseSCache(oldDscp);
4439 cm_ReleaseSCache(newDscp);
4443 typedef struct smb_rmdirRock {
4447 char *maskp; /* pointer to the star pattern */
4452 int smb_RmdirProc(cm_scache_t *dscp, cm_dirEntry_t *dep, void *vrockp, osi_hyper_t *offp)
4455 smb_rmdirRock_t *rockp;
4460 rockp = (smb_rmdirRock_t *) vrockp;
4462 matchName = dep->name;
4463 if (rockp->flags & SMB_MASKFLAG_CASEFOLD)
4464 match = (cm_stricmp(matchName, rockp->maskp) == 0);
4466 match = (strcmp(matchName, rockp->maskp) == 0);
4468 && (rockp->flags & SMB_MASKFLAG_TILDE)
4469 && !cm_Is8Dot3(dep->name)) {
4470 cm_Gen8Dot3Name(dep, shortName, NULL);
4471 matchName = shortName;
4472 match = (cm_stricmp(matchName, rockp->maskp) == 0);
4475 osi_Log1(smb_logp, "Removing directory %s",
4476 osi_LogSaveString(smb_logp, matchName));
4477 code = cm_RemoveDir(dscp, dep->name, rockp->userp, rockp->reqp);
4478 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4479 smb_NotifyChange(FILE_ACTION_REMOVED,
4480 FILE_NOTIFY_CHANGE_DIR_NAME,
4481 dscp, dep->name, NULL, TRUE);
4490 long smb_ReceiveCoreRemoveDir(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4498 smb_rmdirRock_t rock;
4507 tp = smb_GetSMBData(inp, NULL);
4508 pathp = smb_ParseASCIIBlock(tp, &tp);
4510 spacep = inp->spacep;
4511 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
4513 userp = smb_GetUser(vcp, inp);
4515 caseFold = CM_FLAG_CASEFOLD;
4517 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
4518 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold | CM_FLAG_FOLLOW,
4519 userp, tidPathp, &req, &dscp);
4522 cm_ReleaseUser(userp);
4526 /* otherwise, scp points to the parent directory. */
4533 rock.maskp = lastNamep;
4534 rock.flags = ((strchr(rock.maskp, '~') != NULL) ? SMB_MASKFLAG_TILDE : 0);
4537 thyper.HighPart = 0;
4541 /* First do a case sensitive match, and if that fails, do a case insensitive match */
4542 code = cm_ApplyDir(dscp, smb_RmdirProc, &rock, &thyper, userp, &req, NULL);
4543 if (code == 0 && !rock.any) {
4545 thyper.HighPart = 0;
4546 rock.flags |= SMB_MASKFLAG_CASEFOLD;
4547 code = cm_ApplyDir(dscp, smb_RmdirProc, &rock, &thyper, userp, &req, NULL);
4550 cm_ReleaseUser(userp);
4552 cm_ReleaseSCache(dscp);
4554 if (code == 0 && !rock.any)
4555 code = CM_ERROR_NOSUCHFILE;
4559 long smb_ReceiveCoreFlush(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4569 fid = smb_GetSMBParm(inp, 0);
4571 osi_Log1(smb_logp, "SMB flush fid %d", fid);
4573 fid = smb_ChainFID(fid, inp);
4574 fidp = smb_FindFID(vcp, fid, 0);
4575 if (!fidp || (fidp->flags & SMB_FID_IOCTL)) {
4577 smb_ReleaseFID(fidp);
4578 return CM_ERROR_BADFD;
4581 userp = smb_GetUser(vcp, inp);
4583 lock_ObtainMutex(&fidp->mx);
4584 if (fidp->flags & SMB_FID_OPENWRITE)
4585 code = cm_FSync(fidp->scp, userp, &req);
4588 lock_ReleaseMutex(&fidp->mx);
4590 smb_ReleaseFID(fidp);
4592 cm_ReleaseUser(userp);
4597 struct smb_FullNameRock {
4603 int smb_FullNameProc(cm_scache_t *scp, cm_dirEntry_t *dep, void *rockp,
4607 struct smb_FullNameRock *vrockp;
4609 vrockp = (struct smb_FullNameRock *)rockp;
4611 if (!cm_Is8Dot3(dep->name)) {
4612 cm_Gen8Dot3Name(dep, shortName, NULL);
4614 if (cm_stricmp(shortName, vrockp->name) == 0) {
4615 vrockp->fullName = strdup(dep->name);
4616 return CM_ERROR_STOPNOW;
4619 if (cm_stricmp(dep->name, vrockp->name) == 0
4620 && ntohl(dep->fid.vnode) == vrockp->vnode->fid.vnode
4621 && ntohl(dep->fid.unique) == vrockp->vnode->fid.unique) {
4622 vrockp->fullName = strdup(dep->name);
4623 return CM_ERROR_STOPNOW;
4628 void smb_FullName(cm_scache_t *dscp, cm_scache_t *scp, char *pathp,
4629 char **newPathp, cm_user_t *userp, cm_req_t *reqp)
4631 struct smb_FullNameRock rock;
4637 code = cm_ApplyDir(dscp, smb_FullNameProc, &rock, NULL,
4639 if (code == CM_ERROR_STOPNOW)
4640 *newPathp = rock.fullName;
4642 *newPathp = strdup(pathp);
4645 long smb_ReceiveCoreClose(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4656 fid = smb_GetSMBParm(inp, 0);
4657 dosTime = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
4659 osi_Log1(smb_logp, "SMB close fid %d", fid);
4661 fid = smb_ChainFID(fid, inp);
4662 fidp = smb_FindFID(vcp, fid, 0);
4664 return CM_ERROR_BADFD;
4667 userp = smb_GetUser(vcp, inp);
4669 lock_ObtainMutex(&fidp->mx);
4671 /* Don't jump the gun on an async raw write */
4672 while (fidp->raw_writers) {
4673 lock_ReleaseMutex(&fidp->mx);
4674 thrd_WaitForSingleObject_Event(fidp->raw_write_event, RAWTIMEOUT);
4675 lock_ObtainMutex(&fidp->mx);
4678 fidp->flags |= SMB_FID_DELETE;
4680 /* watch for ioctl closes, and read-only opens */
4681 if (fidp->scp != NULL
4682 && (fidp->flags & (SMB_FID_OPENWRITE | SMB_FID_DELONCLOSE))
4683 == SMB_FID_OPENWRITE) {
4684 if (dosTime != 0 && dosTime != -1) {
4685 fidp->scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
4686 /* This fixes defect 10958 */
4687 CompensateForSmbClientLastWriteTimeBugs(&dosTime);
4688 smb_UnixTimeFromDosUTime(&fidp->scp->clientModTime, dosTime);
4690 code = cm_FSync(fidp->scp, userp, &req);
4695 if (fidp->flags & SMB_FID_DELONCLOSE) {
4696 cm_scache_t *dscp = fidp->NTopen_dscp;
4697 char *pathp = fidp->NTopen_pathp;
4700 smb_FullName(dscp, fidp->scp, pathp, &fullPathp, userp, &req);
4701 if (fidp->scp->fileType == CM_SCACHETYPE_DIRECTORY) {
4702 code = cm_RemoveDir(dscp, fullPathp, userp, &req);
4703 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4704 smb_NotifyChange(FILE_ACTION_REMOVED,
4705 FILE_NOTIFY_CHANGE_DIR_NAME,
4706 dscp, fullPathp, NULL, TRUE);
4710 code = cm_Unlink(dscp, fullPathp, userp, &req);
4711 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4712 smb_NotifyChange(FILE_ACTION_REMOVED,
4713 FILE_NOTIFY_CHANGE_FILE_NAME,
4714 dscp, fullPathp, NULL, TRUE);
4718 lock_ReleaseMutex(&fidp->mx);
4720 if (fidp->flags & SMB_FID_NTOPEN) {
4721 cm_ReleaseSCache(fidp->NTopen_dscp);
4722 free(fidp->NTopen_pathp);
4724 if (fidp->NTopen_wholepathp)
4725 free(fidp->NTopen_wholepathp);
4727 smb_ReleaseFID(fidp);
4728 cm_ReleaseUser(userp);
4733 * smb_ReadData -- common code for Read, Read And X, and Raw Read
4736 long smb_ReadData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4737 cm_user_t *userp, long *readp)
4739 long smb_ReadData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4740 cm_user_t *userp, long *readp, int dosflag)
4747 osi_hyper_t fileLength;
4749 osi_hyper_t lastByte;
4750 osi_hyper_t bufferOffset;
4751 long bufIndex, nbytes;
4761 lock_ObtainMutex(&fidp->mx);
4763 lock_ObtainMutex(&scp->mx);
4765 if (offset.HighPart == 0) {
4766 chunk = offset.LowPart >> cm_logChunkSize;
4767 if (chunk != fidp->curr_chunk) {
4768 fidp->prev_chunk = fidp->curr_chunk;
4769 fidp->curr_chunk = chunk;
4771 if (fidp->curr_chunk == fidp->prev_chunk + 1)
4775 /* start by looking up the file's end */
4776 code = cm_SyncOp(scp, NULL, userp, &req, 0,
4777 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
4778 if (code) goto done;
4780 /* now we have the entry locked, look up the length */
4781 fileLength = scp->length;
4783 /* adjust count down so that it won't go past EOF */
4784 thyper.LowPart = count;
4785 thyper.HighPart = 0;
4786 thyper = LargeIntegerAdd(offset, thyper); /* where read should end */
4788 if (LargeIntegerGreaterThan(thyper, fileLength)) {
4789 /* we'd read past EOF, so just stop at fileLength bytes.
4790 * Start by computing how many bytes remain in the file.
4792 thyper = LargeIntegerSubtract(fileLength, offset);
4794 /* if we are past EOF, read 0 bytes */
4795 if (LargeIntegerLessThanZero(thyper))
4798 count = thyper.LowPart;
4803 /* now, copy the data one buffer at a time,
4804 * until we've filled the request packet
4807 /* if we've copied all the data requested, we're done */
4808 if (count <= 0) break;
4810 /* otherwise, load up a buffer of data */
4811 thyper.HighPart = offset.HighPart;
4812 thyper.LowPart = offset.LowPart & ~(buf_bufferSize-1);
4813 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
4816 buf_Release(bufferp);
4819 lock_ReleaseMutex(&scp->mx);
4821 lock_ObtainRead(&scp->bufCreateLock);
4822 code = buf_Get(scp, &thyper, &bufferp);
4823 lock_ReleaseRead(&scp->bufCreateLock);
4825 lock_ObtainMutex(&scp->mx);
4826 if (code) goto done;
4827 bufferOffset = thyper;
4829 /* now get the data in the cache */
4831 code = cm_SyncOp(scp, bufferp, userp, &req, 0,
4832 CM_SCACHESYNC_NEEDCALLBACK
4833 | CM_SCACHESYNC_READ);
4834 if (code) goto done;
4836 if (cm_HaveBuffer(scp, bufferp, 0)) break;
4838 /* otherwise, load the buffer and try again */
4839 code = cm_GetBuffer(scp, bufferp, NULL, userp, &req);
4843 buf_Release(bufferp);
4847 } /* if (wrong buffer) ... */
4849 /* now we have the right buffer loaded. Copy out the
4850 * data from here to the user's buffer.
4852 bufIndex = offset.LowPart & (buf_bufferSize - 1);
4854 /* and figure out how many bytes we want from this buffer */
4855 nbytes = buf_bufferSize - bufIndex; /* what remains in buffer */
4856 if (nbytes > count) nbytes = count; /* don't go past EOF */
4858 /* now copy the data */
4861 dosmemput(bufferp->datap + bufIndex, nbytes, (dos_ptr)op);
4864 memcpy(op, bufferp->datap + bufIndex, nbytes);
4866 /* adjust counters, pointers, etc. */
4869 thyper.LowPart = nbytes;
4870 thyper.HighPart = 0;
4871 offset = LargeIntegerAdd(thyper, offset);
4875 lock_ReleaseMutex(&scp->mx);
4876 lock_ReleaseMutex(&fidp->mx);
4878 buf_Release(bufferp);
4880 if (code == 0 && sequential)
4881 cm_ConsiderPrefetch(scp, &lastByte, userp, &req);
4887 * smb_WriteData -- common code for Write and Raw Write
4890 long smb_WriteData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4891 cm_user_t *userp, long *writtenp)
4893 long smb_WriteData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4894 cm_user_t *userp, long *writtenp, int dosflag)
4901 osi_hyper_t fileLength; /* file's length at start of write */
4902 osi_hyper_t minLength; /* don't read past this */
4903 long nbytes; /* # of bytes to transfer this iteration */
4905 osi_hyper_t thyper; /* hyper tmp variable */
4906 osi_hyper_t bufferOffset;
4907 long bufIndex; /* index in buffer where our data is */
4909 osi_hyper_t writeBackOffset; /* offset of region to write back when
4920 lock_ObtainMutex(&fidp->mx);
4922 lock_ObtainMutex(&scp->mx);
4924 /* start by looking up the file's end */
4925 code = cm_SyncOp(scp, NULL, userp, &req, 0,
4926 CM_SCACHESYNC_NEEDCALLBACK
4927 | CM_SCACHESYNC_SETSTATUS
4928 | CM_SCACHESYNC_GETSTATUS);
4932 /* make sure we have a writable FD */
4933 if (!(fidp->flags & SMB_FID_OPENWRITE)) {
4934 code = CM_ERROR_BADFDOP;
4938 /* now we have the entry locked, look up the length */
4939 fileLength = scp->length;
4940 minLength = fileLength;
4941 if (LargeIntegerGreaterThan(minLength, scp->serverLength))
4942 minLength = scp->serverLength;
4944 /* adjust file length if we extend past EOF */
4945 thyper.LowPart = count;
4946 thyper.HighPart = 0;
4947 thyper = LargeIntegerAdd(offset, thyper); /* where write should end */
4948 if (LargeIntegerGreaterThan(thyper, fileLength)) {
4949 /* we'd write past EOF, so extend the file */
4950 scp->mask |= CM_SCACHEMASK_LENGTH;
4951 scp->length = thyper;
4952 filter |= (FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE);
4954 filter |= FILE_NOTIFY_CHANGE_LAST_WRITE;
4956 /* now, if the new position (thyper) and the old (offset) are in
4957 * different storeback windows, remember to store back the previous
4958 * storeback window when we're done with the write.
4960 if ((thyper.LowPart & (-cm_chunkSize)) !=
4961 (offset.LowPart & (-cm_chunkSize))) {
4962 /* they're different */
4964 writeBackOffset.HighPart = offset.HighPart;
4965 writeBackOffset.LowPart = offset.LowPart & (-cm_chunkSize);
4970 /* now, copy the data one buffer at a time, until we've filled the
4973 /* if we've copied all the data requested, we're done */
4974 if (count <= 0) break;
4976 /* handle over quota or out of space */
4977 if (scp->flags & (CM_SCACHEFLAG_OVERQUOTA | CM_SCACHEFLAG_OUTOFSPACE)) {
4978 *writtenp = written;
4982 /* otherwise, load up a buffer of data */
4983 thyper.HighPart = offset.HighPart;
4984 thyper.LowPart = offset.LowPart & ~(buf_bufferSize-1);
4985 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
4988 lock_ReleaseMutex(&bufferp->mx);
4989 buf_Release(bufferp);
4992 lock_ReleaseMutex(&scp->mx);
4994 lock_ObtainRead(&scp->bufCreateLock);
4995 code = buf_Get(scp, &thyper, &bufferp);
4996 lock_ReleaseRead(&scp->bufCreateLock);
4998 lock_ObtainMutex(&bufferp->mx);
4999 lock_ObtainMutex(&scp->mx);
5000 if (code) goto done;
5002 bufferOffset = thyper;
5004 /* now get the data in the cache */
5006 code = cm_SyncOp(scp, bufferp, userp, &req, 0,
5007 CM_SCACHESYNC_NEEDCALLBACK
5008 | CM_SCACHESYNC_WRITE
5009 | CM_SCACHESYNC_BUFLOCKED);
5013 /* If we're overwriting the entire buffer, or
5014 * if we're writing at or past EOF, mark the
5015 * buffer as current so we don't call
5016 * cm_GetBuffer. This skips the fetch from the
5017 * server in those cases where we're going to
5018 * obliterate all the data in the buffer anyway,
5019 * or in those cases where there is no useful
5020 * data at the server to start with.
5022 * Use minLength instead of scp->length, since
5023 * the latter has already been updated by this
5026 if (LargeIntegerGreaterThanOrEqualTo(
5027 bufferp->offset, minLength)
5028 || LargeIntegerEqualTo(offset, bufferp->offset)
5029 && (count >= buf_bufferSize
5030 || LargeIntegerGreaterThanOrEqualTo(
5031 LargeIntegerAdd(offset,
5032 ConvertLongToLargeInteger(count)),
5034 if (count < buf_bufferSize
5035 && bufferp->dataVersion == -1)
5036 memset(bufferp->datap, 0,
5038 bufferp->dataVersion = scp->dataVersion;
5041 if (cm_HaveBuffer(scp, bufferp, 1)) break;
5043 /* otherwise, load the buffer and try again */
5044 lock_ReleaseMutex(&bufferp->mx);
5045 code = cm_GetBuffer(scp, bufferp, NULL, userp,
5047 lock_ReleaseMutex(&scp->mx);
5048 lock_ObtainMutex(&bufferp->mx);
5049 lock_ObtainMutex(&scp->mx);
5053 lock_ReleaseMutex(&bufferp->mx);
5054 buf_Release(bufferp);
5058 } /* if (wrong buffer) ... */
5060 /* now we have the right buffer loaded. Copy out the
5061 * data from here to the user's buffer.
5063 bufIndex = offset.LowPart & (buf_bufferSize - 1);
5065 /* and figure out how many bytes we want from this buffer */
5066 nbytes = buf_bufferSize - bufIndex; /* what remains in buffer */
5068 nbytes = count; /* don't go past end of request */
5070 /* now copy the data */
5073 dosmemget((dos_ptr)op, nbytes, bufferp->datap + bufIndex);
5076 memcpy(bufferp->datap + bufIndex, op, nbytes);
5077 buf_SetDirty(bufferp);
5079 /* and record the last writer */
5080 if (bufferp->userp != userp) {
5083 cm_ReleaseUser(bufferp->userp);
5084 bufferp->userp = userp;
5087 /* adjust counters, pointers, etc. */
5091 thyper.LowPart = nbytes;
5092 thyper.HighPart = 0;
5093 offset = LargeIntegerAdd(thyper, offset);
5097 lock_ReleaseMutex(&scp->mx);
5098 lock_ReleaseMutex(&fidp->mx);
5100 lock_ReleaseMutex(&bufferp->mx);
5101 buf_Release(bufferp);
5104 if (code == 0 && filter != 0 && (fidp->flags & SMB_FID_NTOPEN)
5105 && (fidp->NTopen_dscp->flags & CM_SCACHEFLAG_ANYWATCH)) {
5106 smb_NotifyChange(FILE_ACTION_MODIFIED, filter,
5107 fidp->NTopen_dscp, fidp->NTopen_pathp,
5111 if (code == 0 && doWriteBack) {
5112 lock_ObtainMutex(&scp->mx);
5113 cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_ASYNCSTORE);
5114 lock_ReleaseMutex(&scp->mx);
5115 cm_QueueBKGRequest(scp, cm_BkgStore, writeBackOffset.LowPart,
5116 writeBackOffset.HighPart, cm_chunkSize, 0, userp);
5122 long smb_ReceiveCoreWrite(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5125 long count, written = 0;
5130 cm_attr_t truncAttr; /* attribute struct used for truncating file */
5132 int inDataBlockCount;
5134 fd = smb_GetSMBParm(inp, 0);
5135 count = smb_GetSMBParm(inp, 1);
5136 offset.HighPart = 0; /* too bad */
5137 offset.LowPart = smb_GetSMBParm(inp, 2) | (smb_GetSMBParm(inp, 3) << 16);
5139 op = smb_GetSMBData(inp, NULL);
5140 op = smb_ParseDataBlock(op, NULL, &inDataBlockCount);
5142 osi_Log3(smb_logp, "smb_ReceiveCoreWrite fd %d, off 0x%x, size 0x%x",
5143 fd, offset.LowPart, count);
5145 fd = smb_ChainFID(fd, inp);
5146 fidp = smb_FindFID(vcp, fd, 0);
5148 return CM_ERROR_BADFD;
5151 if (fidp->flags & SMB_FID_IOCTL)
5152 return smb_IoctlWrite(fidp, vcp, inp, outp);
5154 userp = smb_GetUser(vcp, inp);
5156 /* special case: 0 bytes transferred means truncate to this position */
5162 truncAttr.mask = CM_ATTRMASK_LENGTH;
5163 truncAttr.length.LowPart = offset.LowPart;
5164 truncAttr.length.HighPart = 0;
5165 lock_ObtainMutex(&fidp->mx);
5166 code = cm_SetAttr(fidp->scp, &truncAttr, userp, &req);
5167 lock_ReleaseMutex(&fidp->mx);
5168 smb_SetSMBParm(outp, 0, /* count */ 0);
5169 smb_SetSMBDataLength(outp, 0);
5170 fidp->flags |= SMB_FID_LENGTHSETDONE;
5175 * Work around bug in NT client
5177 * When copying a file, the NT client should first copy the data,
5178 * then copy the last write time. But sometimes the NT client does
5179 * these in the wrong order, so the data copies would inadvertently
5180 * cause the last write time to be overwritten. We try to detect this,
5181 * and don't set client mod time if we think that would go against the
5184 if ((fidp->flags & SMB_FID_MTIMESETDONE) != SMB_FID_MTIMESETDONE) {
5185 fidp->scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
5186 fidp->scp->clientModTime = time(NULL);
5190 code = smb_WriteData(fidp, &offset, count, op, userp, &written);
5192 code = smb_WriteData(fidp, &offset, count, op, userp, &written, FALSE);
5194 if (code == 0 && written < count)
5195 code = CM_ERROR_PARTIALWRITE;
5197 /* set the packet data length to 3 bytes for the data block header,
5198 * plus the size of the data.
5200 smb_SetSMBParm(outp, 0, written);
5201 smb_SetSMBDataLength(outp, 0);
5204 smb_ReleaseFID(fidp);
5205 cm_ReleaseUser(userp);
5210 void smb_CompleteWriteRaw(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp,
5211 NCB *ncbp, raw_write_cont_t *rwcp)
5224 fd = smb_GetSMBParm(inp, 0);
5225 fidp = smb_FindFID(vcp, fd, 0);
5227 osi_Log2(smb_logp, "Completing Raw Write offset %x count %x",
5228 rwcp->offset.LowPart, rwcp->count);
5230 userp = smb_GetUser(vcp, inp);
5234 code = smb_WriteData(fidp, &rwcp->offset, rwcp->count, rawBuf, userp,
5237 rawBuf = (dos_ptr) rwcp->buf;
5238 code = smb_WriteData(fidp, &rwcp->offset, rwcp->count,
5239 (unsigned char *) rawBuf, userp,
5243 if (rwcp->writeMode & 0x1) { /* synchronous */
5246 smb_FormatResponsePacket(vcp, inp, outp);
5247 op = (smb_t *) outp;
5248 op->com = 0x20; /* SMB_COM_WRITE_COMPLETE */
5249 smb_SetSMBParm(outp, 0, written + rwcp->alreadyWritten);
5250 smb_SetSMBDataLength(outp, 0);
5251 smb_SendPacket(vcp, outp);
5252 smb_FreePacket(outp);
5254 else { /* asynchronous */
5255 lock_ObtainMutex(&fidp->mx);
5256 fidp->raw_writers--;
5257 if (fidp->raw_writers == 0)
5258 thrd_SetEvent(fidp->raw_write_event);
5259 lock_ReleaseMutex(&fidp->mx);
5262 /* Give back raw buffer */
5263 lock_ObtainMutex(&smb_RawBufLock);
5265 *((char **)rawBuf) = smb_RawBufs;
5267 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
5269 smb_RawBufs = rawBuf;
5270 lock_ReleaseMutex(&smb_RawBufLock);
5272 smb_ReleaseFID(fidp);
5273 cm_ReleaseUser(userp);
5276 long smb_ReceiveCoreWriteRawDummy(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5281 long smb_ReceiveCoreWriteRaw(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp, raw_write_cont_t *rwcp)
5284 long count, written = 0;
5291 unsigned short writeMode;
5298 fd = smb_GetSMBParm(inp, 0);
5299 totalCount = smb_GetSMBParm(inp, 1);
5300 count = smb_GetSMBParm(inp, 10);
5301 offset.HighPart = 0; /* too bad */
5302 offset.LowPart = smb_GetSMBParm(inp, 3) | (smb_GetSMBParm(inp, 4) << 16);
5303 writeMode = smb_GetSMBParm(inp, 7);
5305 op = (char *) inp->data;
5306 op += smb_GetSMBParm(inp, 11);
5309 "smb_ReceiveCoreWriteRaw fd %d, off 0x%x, size 0x%x, WriteMode 0x%x",
5310 fd, offset.LowPart, count, writeMode);
5312 fd = smb_ChainFID(fd, inp);
5313 fidp = smb_FindFID(vcp, fd, 0);
5315 return CM_ERROR_BADFD;
5318 userp = smb_GetUser(vcp, inp);
5321 * Work around bug in NT client
5323 * When copying a file, the NT client should first copy the data,
5324 * then copy the last write time. But sometimes the NT client does
5325 * these in the wrong order, so the data copies would inadvertently
5326 * cause the last write time to be overwritten. We try to detect this,
5327 * and don't set client mod time if we think that would go against the
5330 if ((fidp->flags & SMB_FID_LOOKSLIKECOPY) != SMB_FID_LOOKSLIKECOPY) {
5331 fidp->scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
5332 fidp->scp->clientModTime = time(NULL);
5336 code = smb_WriteData(fidp, &offset, count, op, userp, &written);
5338 code = smb_WriteData(fidp, &offset, count, op, userp, &written, FALSE);
5340 if (code == 0 && written < count)
5341 code = CM_ERROR_PARTIALWRITE;
5343 /* Get a raw buffer */
5346 lock_ObtainMutex(&smb_RawBufLock);
5348 /* Get a raw buf, from head of list */
5349 rawBuf = smb_RawBufs;
5351 smb_RawBufs = *(char **)smb_RawBufs;
5353 smb_RawBufs = _farpeekl(_dos_ds, smb_RawBufs);
5357 code = CM_ERROR_USESTD;
5359 lock_ReleaseMutex(&smb_RawBufLock);
5362 /* Don't allow a premature Close */
5363 if (code == 0 && (writeMode & 1) == 0) {
5364 lock_ObtainMutex(&fidp->mx);
5365 fidp->raw_writers++;
5366 thrd_ResetEvent(fidp->raw_write_event);
5367 lock_ReleaseMutex(&fidp->mx);
5370 smb_ReleaseFID(fidp);
5371 cm_ReleaseUser(userp);
5374 smb_SetSMBParm(outp, 0, written);
5375 smb_SetSMBDataLength(outp, 0);
5376 ((smb_t *)outp)->com = 0x20; /* SMB_COM_WRITE_COMPLETE */
5383 rwcp->offset.HighPart = 0;
5384 rwcp->offset.LowPart = offset.LowPart + count;
5385 rwcp->count = totalCount - count;
5386 rwcp->writeMode = writeMode;
5387 rwcp->alreadyWritten = written;
5389 /* set the packet data length to 3 bytes for the data block header,
5390 * plus the size of the data.
5392 smb_SetSMBParm(outp, 0, 0xffff);
5393 smb_SetSMBDataLength(outp, 0);
5398 long smb_ReceiveCoreRead(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5401 long count, finalCount;
5408 fd = smb_GetSMBParm(inp, 0);
5409 count = smb_GetSMBParm(inp, 1);
5410 offset.HighPart = 0; /* too bad */
5411 offset.LowPart = smb_GetSMBParm(inp, 2) | (smb_GetSMBParm(inp, 3) << 16);
5413 osi_Log3(smb_logp, "smb_ReceiveCoreRead fd %d, off 0x%x, size 0x%x",
5414 fd, offset.LowPart, count);
5416 fd = smb_ChainFID(fd, inp);
5417 fidp = smb_FindFID(vcp, fd, 0);
5419 return CM_ERROR_BADFD;
5422 if (fidp->flags & SMB_FID_IOCTL) {
5423 return smb_IoctlRead(fidp, vcp, inp, outp);
5426 userp = smb_GetUser(vcp, inp);
5428 /* remember this for final results */
5429 smb_SetSMBParm(outp, 0, count);
5430 smb_SetSMBParm(outp, 1, 0);
5431 smb_SetSMBParm(outp, 2, 0);
5432 smb_SetSMBParm(outp, 3, 0);
5433 smb_SetSMBParm(outp, 4, 0);
5435 /* set the packet data length to 3 bytes for the data block header,
5436 * plus the size of the data.
5438 smb_SetSMBDataLength(outp, count+3);
5440 /* get op ptr after putting in the parms, since otherwise we don't
5441 * know where the data really is.
5443 op = smb_GetSMBData(outp, NULL);
5445 /* now emit the data block header: 1 byte of type and 2 bytes of length */
5446 *op++ = 1; /* data block marker */
5447 *op++ = (unsigned char) (count & 0xff);
5448 *op++ = (unsigned char) ((count >> 8) & 0xff);
5451 code = smb_ReadData(fidp, &offset, count, op, userp, &finalCount);
5453 code = smb_ReadData(fidp, &offset, count, op, userp, &finalCount, FALSE);
5456 /* fix some things up */
5457 smb_SetSMBParm(outp, 0, finalCount);
5458 smb_SetSMBDataLength(outp, finalCount+3);
5460 smb_ReleaseFID(fidp);
5462 cm_ReleaseUser(userp);
5466 long smb_ReceiveCoreMakeDir(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5473 cm_scache_t *dscp; /* dir we're dealing with */
5474 cm_scache_t *scp; /* file we're creating */
5476 int initialModeBits;
5486 /* compute initial mode bits based on read-only flag in attributes */
5487 initialModeBits = 0777;
5489 tp = smb_GetSMBData(inp, NULL);
5490 pathp = smb_ParseASCIIBlock(tp, &tp);
5492 if (strcmp(pathp, "\\") == 0)
5493 return CM_ERROR_EXISTS;
5495 spacep = inp->spacep;
5496 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
5498 userp = smb_GetUser(vcp, inp);
5500 caseFold = CM_FLAG_CASEFOLD;
5502 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
5504 code = cm_NameI(cm_rootSCachep, spacep->data,
5505 caseFold | CM_FLAG_FOLLOW | CM_FLAG_CHECKPATH,
5506 userp, tidPathp, &req, &dscp);
5509 cm_ReleaseUser(userp);
5513 /* otherwise, scp points to the parent directory. Do a lookup, and
5514 * fail if we find it. Otherwise, we do the create.
5520 code = cm_Lookup(dscp, lastNamep, 0, userp, &req, &scp);
5521 if (scp) cm_ReleaseSCache(scp);
5522 if (code != CM_ERROR_NOSUCHFILE) {
5523 if (code == 0) code = CM_ERROR_EXISTS;
5524 cm_ReleaseSCache(dscp);
5525 cm_ReleaseUser(userp);
5529 setAttr.mask = CM_ATTRMASK_CLIENTMODTIME;
5530 setAttr.clientModTime = time(NULL);
5531 code = cm_MakeDir(dscp, lastNamep, 0, &setAttr, userp, &req);
5532 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
5533 smb_NotifyChange(FILE_ACTION_ADDED,
5534 FILE_NOTIFY_CHANGE_DIR_NAME,
5535 dscp, lastNamep, NULL, TRUE);
5537 /* we don't need this any longer */
5538 cm_ReleaseSCache(dscp);
5541 /* something went wrong creating or truncating the file */
5542 cm_ReleaseUser(userp);
5546 /* otherwise we succeeded */
5547 smb_SetSMBDataLength(outp, 0);
5548 cm_ReleaseUser(userp);
5553 BOOL smb_IsLegalFilename(char *filename)
5556 * Find the longest substring of filename that does not contain
5557 * any of the chars in illegalChars. If that substring is less
5558 * than the length of the whole string, then one or more of the
5559 * illegal chars is in filename.
5561 if (strcspn(filename, illegalChars) < strlen(filename))
5567 long smb_ReceiveCoreCreate(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5575 cm_scache_t *dscp; /* dir we're dealing with */
5576 cm_scache_t *scp; /* file we're creating */
5578 int initialModeBits;
5590 excl = (inp->inCom == 0x03)? 0 : 1;
5592 attributes = smb_GetSMBParm(inp, 0);
5593 dosTime = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
5595 /* compute initial mode bits based on read-only flag in attributes */
5596 initialModeBits = 0666;
5597 if (attributes & 1) initialModeBits &= ~0222;
5599 tp = smb_GetSMBData(inp, NULL);
5600 pathp = smb_ParseASCIIBlock(tp, &tp);
5602 spacep = inp->spacep;
5603 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
5605 userp = smb_GetUser(vcp, inp);
5607 caseFold = CM_FLAG_CASEFOLD;
5609 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
5610 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold | CM_FLAG_FOLLOW,
5611 userp, tidPathp, &req, &dscp);
5614 cm_ReleaseUser(userp);
5618 /* otherwise, scp points to the parent directory. Do a lookup, and
5619 * truncate the file if we find it, otherwise we create the file.
5621 if (!lastNamep) lastNamep = pathp;
5624 if (!smb_IsLegalFilename(lastNamep))
5625 return CM_ERROR_BADNTFILENAME;
5627 osi_Log1(smb_logp, "SMB receive create [%s]", osi_LogSaveString( smb_logp, pathp ));
5628 #ifdef DEBUG_VERBOSE
5631 hexp = osi_HexifyString( lastNamep );
5632 DEBUG_EVENT2("AFS", "CoreCreate H[%s] A[%s]", hexp, lastNamep );
5637 code = cm_Lookup(dscp, lastNamep, 0, userp, &req, &scp);
5638 if (code && code != CM_ERROR_NOSUCHFILE) {
5639 cm_ReleaseSCache(dscp);
5640 cm_ReleaseUser(userp);
5644 /* if we get here, if code is 0, the file exists and is represented by
5645 * scp. Otherwise, we have to create it.
5649 /* oops, file shouldn't be there */
5650 cm_ReleaseSCache(dscp);
5651 cm_ReleaseSCache(scp);
5652 cm_ReleaseUser(userp);
5653 return CM_ERROR_EXISTS;
5656 setAttr.mask = CM_ATTRMASK_LENGTH;
5657 setAttr.length.LowPart = 0;
5658 setAttr.length.HighPart = 0;
5659 code = cm_SetAttr(scp, &setAttr, userp, &req);
5662 setAttr.mask = CM_ATTRMASK_CLIENTMODTIME;
5663 smb_UnixTimeFromDosUTime(&setAttr.clientModTime, dosTime);
5664 code = cm_Create(dscp, lastNamep, 0, &setAttr, &scp, userp,
5666 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
5667 smb_NotifyChange(FILE_ACTION_ADDED,
5668 FILE_NOTIFY_CHANGE_FILE_NAME,
5669 dscp, lastNamep, NULL, TRUE);
5670 if (!excl && code == CM_ERROR_EXISTS) {
5671 /* not an exclusive create, and someone else tried
5672 * creating it already, then we open it anyway. We
5673 * don't bother retrying after this, since if this next
5674 * fails, that means that the file was deleted after
5675 * we started this call.
5677 code = cm_Lookup(dscp, lastNamep, caseFold, userp,
5680 setAttr.mask = CM_ATTRMASK_LENGTH;
5681 setAttr.length.LowPart = 0;
5682 setAttr.length.HighPart = 0;
5683 code = cm_SetAttr(scp, &setAttr, userp, &req);
5688 /* we don't need this any longer */
5689 cm_ReleaseSCache(dscp);
5692 /* something went wrong creating or truncating the file */
5693 if (scp) cm_ReleaseSCache(scp);
5694 cm_ReleaseUser(userp);
5698 /* make sure we only open files */
5699 if (scp->fileType != CM_SCACHETYPE_FILE) {
5700 cm_ReleaseSCache(scp);
5701 cm_ReleaseUser(userp);
5702 return CM_ERROR_ISDIR;
5705 /* now all we have to do is open the file itself */
5706 fidp = smb_FindFID(vcp, 0, SMB_FLAG_CREATE);
5709 /* save a pointer to the vnode */
5712 /* always create it open for read/write */
5713 fidp->flags |= (SMB_FID_OPENREAD | SMB_FID_OPENWRITE);
5715 smb_ReleaseFID(fidp);
5717 smb_SetSMBParm(outp, 0, fidp->fid);
5718 smb_SetSMBDataLength(outp, 0);
5720 cm_Open(scp, 0, userp);
5722 cm_ReleaseUser(userp);
5723 /* leave scp held since we put it in fidp->scp */
5727 long smb_ReceiveCoreSeek(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5740 fd = smb_GetSMBParm(inp, 0);
5741 whence = smb_GetSMBParm(inp, 1);
5742 offset = smb_GetSMBParm(inp, 2) | (smb_GetSMBParm(inp, 3) << 16);
5744 /* try to find the file descriptor */
5745 fd = smb_ChainFID(fd, inp);
5746 fidp = smb_FindFID(vcp, fd, 0);
5747 if (!fidp || (fidp->flags & SMB_FID_IOCTL)) {
5748 return CM_ERROR_BADFD;
5751 userp = smb_GetUser(vcp, inp);
5753 lock_ObtainMutex(&fidp->mx);
5755 lock_ObtainMutex(&scp->mx);
5756 code = cm_SyncOp(scp, NULL, userp, &req, 0,
5757 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
5760 /* offset from current offset */
5761 offset += fidp->offset;
5763 else if (whence == 2) {
5764 /* offset from current EOF */
5765 offset += scp->length.LowPart;
5767 fidp->offset = offset;
5768 smb_SetSMBParm(outp, 0, offset & 0xffff);
5769 smb_SetSMBParm(outp, 1, (offset>>16) & 0xffff);
5770 smb_SetSMBDataLength(outp, 0);
5772 lock_ReleaseMutex(&scp->mx);
5773 lock_ReleaseMutex(&fidp->mx);
5774 smb_ReleaseFID(fidp);
5775 cm_ReleaseUser(userp);
5779 /* dispatch all of the requests received in a packet. Due to chaining, this may
5780 * be more than one request.
5782 void smb_DispatchPacket(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp,
5783 NCB *ncbp, raw_write_cont_t *rwcp)
5787 unsigned long code = 0;
5788 unsigned char *outWctp;
5789 int nparms; /* # of bytes of parameters */
5791 int nbytes; /* bytes of data, excluding count */
5794 unsigned short errCode;
5795 unsigned long NTStatus;
5797 unsigned char errClass;
5798 unsigned int oldGen;
5799 DWORD oldTime, newTime;
5801 /* get easy pointer to the data */
5802 smbp = (smb_t *) inp->data;
5804 if (!(outp->flags & SMB_PACKETFLAG_SUSPENDED)) {
5805 /* setup the basic parms for the initial request in the packet */
5806 inp->inCom = smbp->com;
5807 inp->wctp = &smbp->wct;
5809 inp->ncb_length = ncbp->ncb_length;
5814 if (ncbp->ncb_length < offsetof(struct smb, vdata)) {
5815 /* log it and discard it */
5820 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
5821 sprintf(s, "SMB message too short, len %d", ncbp->ncb_length);
5823 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1007, NULL,
5824 1, ncbp->ncb_length, ptbuf, inp);
5825 DeregisterEventSource(h);
5827 osi_Log1(smb_logp, "SMB message too short, len %d",
5834 /* We are an ongoing op */
5835 thrd_Increment(&ongoingOps);
5837 /* set up response packet for receiving output */
5838 if (!(outp->flags & SMB_PACKETFLAG_SUSPENDED))
5839 smb_FormatResponsePacket(vcp, inp, outp);
5840 outWctp = outp->wctp;
5842 /* Remember session generation number and time */
5843 oldGen = sessionGen;
5844 oldTime = GetCurrentTime();
5846 while(inp->inCom != 0xff) {
5847 dp = &smb_dispatchTable[inp->inCom];
5849 if (outp->flags & SMB_PACKETFLAG_SUSPENDED) {
5850 outp->flags &= ~SMB_PACKETFLAG_SUSPENDED;
5851 code = outp->resumeCode;
5855 /* process each request in the packet; inCom, wctp and inCount
5856 * are already set up.
5858 osi_Log2(smb_logp, "SMB received op 0x%x lsn %d", inp->inCom,
5861 /* now do the dispatch */
5862 /* start by formatting the response record a little, as a default */
5863 if (dp->flags & SMB_DISPATCHFLAG_CHAINED) {
5865 outWctp[1] = 0xff; /* no operation */
5866 outWctp[2] = 0; /* padding */
5871 /* not a chained request, this is a more reasonable default */
5872 outWctp[0] = 0; /* wct of zero */
5873 outWctp[1] = 0; /* and bcc (word) of zero */
5877 /* once set, stays set. Doesn't matter, since we never chain
5878 * "no response" calls.
5880 if (dp->flags & SMB_DISPATCHFLAG_NORESPONSE)
5884 /* we have a recognized operation */
5886 if (inp->inCom == 0x1d)
5888 code = smb_ReceiveCoreWriteRaw (vcp, inp, outp,
5891 osi_LogEvent("AFS Dispatch %s",(myCrt_Dispatch(inp->inCom)),"vcp[%x] lana[%d] lsn[%d]",(int)vcp,vcp->lana,vcp->lsn);
5892 osi_Log4(smb_logp,"Dispatch %s vcp[%x] lana[%d] lsn[%d]",(myCrt_Dispatch(inp->inCom)),vcp,vcp->lana,vcp->lsn);
5893 code = (*(dp->procp)) (vcp, inp, outp);
5894 osi_LogEvent("AFS Dispatch return",NULL,"Code[%d]",(code==0)?0:code-CM_ERROR_BASE);
5895 osi_Log1(smb_logp,"Dispatch return code[%d]",(code==0)?0:code-CM_ERROR_BASE);
5898 if (oldGen != sessionGen) {
5903 newTime = GetCurrentTime();
5904 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
5905 sprintf(s, "Pkt straddled session startup, took %d ms, ncb length %d",
5906 newTime - oldTime, ncbp->ncb_length);
5908 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0,
5909 1005, NULL, 1, ncbp->ncb_length, ptbuf, smbp);
5910 DeregisterEventSource(h);
5912 osi_Log1(smb_logp, "Pkt straddled session startup, "
5913 "ncb length %d", ncbp->ncb_length);
5918 /* bad opcode, fail the request, after displaying it */
5921 #endif /* NOTSERVICE */
5925 sprintf(tbuffer, "Received bad SMB req 0x%x", inp->inCom);
5926 code = (*smb_MBfunc)(NULL, tbuffer, "Cancel: don't show again",
5927 MB_OKCANCEL|MB_SERVICE_NOTIFICATION);
5928 if (code == IDCANCEL) showErrors = 0;
5931 code = CM_ERROR_BADOP;
5934 /* catastrophic failure: log as much as possible */
5935 if (code == CM_ERROR_BADSMB) {
5942 "Invalid SMB, ncb_length %d",
5945 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
5946 sprintf(s, "Invalid SMB message, length %d",
5949 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1002, NULL,
5950 1, ncbp->ncb_length, ptbuf, smbp);
5951 DeregisterEventSource(h);
5954 #endif /* NOTSERVICE */
5956 osi_Log1(smb_logp, "Invalid SMB message, length %d",
5960 code = CM_ERROR_INVAL;
5963 if (outp->flags & SMB_PACKETFLAG_NOSEND) {
5964 thrd_Decrement(&ongoingOps);
5969 /* now, if we failed, turn the current response into an empty
5970 * one, and fill in the response packet's error code.
5973 if (vcp->flags & SMB_VCFLAG_STATUS32) {
5974 smb_MapNTError(code, &NTStatus);
5975 outWctp = outp->wctp;
5976 smbp = (smb_t *) &outp->data;
5977 if (code != CM_ERROR_PARTIALWRITE
5978 && code != CM_ERROR_BUFFERTOOSMALL
5979 && code != CM_ERROR_GSSCONTINUE) {
5980 /* nuke wct and bcc. For a partial
5981 * write or an in-process authentication handshake,
5982 * assume they're OK.
5988 smbp->rcls = (unsigned char) (NTStatus & 0xff);
5989 smbp->reh = (unsigned char) ((NTStatus >> 8) & 0xff);
5990 smbp->errLow = (unsigned char) ((NTStatus >> 16) & 0xff);
5991 smbp->errHigh = (unsigned char) ((NTStatus >> 24) & 0xff);
5992 smbp->flg2 |= 0x4000;
5996 smb_MapCoreError(code, vcp, &errCode, &errClass);
5997 outWctp = outp->wctp;
5998 smbp = (smb_t *) &outp->data;
5999 if (code != CM_ERROR_PARTIALWRITE) {
6000 /* nuke wct and bcc. For a partial
6001 * write, assume they're OK.
6007 smbp->errLow = (unsigned char) (errCode & 0xff);
6008 smbp->errHigh = (unsigned char) ((errCode >> 8) & 0xff);
6009 smbp->rcls = errClass;
6012 } /* error occurred */
6014 /* if we're here, we've finished one request. Look to see if
6015 * this is a chained opcode. If it is, setup things to process
6016 * the chained request, and setup the output buffer to hold the
6017 * chained response. Start by finding the next input record.
6019 if (!(dp->flags & SMB_DISPATCHFLAG_CHAINED))
6020 break; /* not a chained req */
6021 tp = inp->wctp; /* points to start of last request */
6022 /* in a chained request, the first two
6023 * parm fields are required, and are
6024 * AndXCommand/AndXReserved and
6026 if (tp[0] < 2) break;
6027 if (tp[1] == 0xff) break; /* no more chained opcodes */
6029 inp->wctp = inp->data + tp[3] + (tp[4] << 8);
6032 /* and now append the next output request to the end of this
6033 * last request. Begin by finding out where the last response
6034 * ends, since that's where we'll put our new response.
6036 outWctp = outp->wctp; /* ptr to out parameters */
6037 osi_assert (outWctp[0] >= 2); /* need this for all chained requests */
6038 nparms = outWctp[0] << 1;
6039 tp = outWctp + nparms + 1; /* now points to bcc field */
6040 nbytes = tp[0] + (tp[1] << 8); /* # of data bytes */
6041 tp += 2 /* for the count itself */ + nbytes;
6042 /* tp now points to the new output record; go back and patch the
6043 * second parameter (off2) to point to the new record.
6045 temp = (unsigned int)tp - ((unsigned int) outp->data);
6046 outWctp[3] = (unsigned char) (temp & 0xff);
6047 outWctp[4] = (unsigned char) ((temp >> 8) & 0xff);
6048 outWctp[2] = 0; /* padding */
6049 outWctp[1] = inp->inCom; /* next opcode */
6051 /* finally, setup for the next iteration */
6054 } /* while loop over all requests in the packet */
6056 /* done logging out, turn off logging-out flag */
6057 if (!(inp->flags & SMB_PACKETFLAG_PROFILE_UPDATE_OK)) {
6058 vcp->justLoggedOut = NULL;
6061 free(loggedOutName);
6062 loggedOutName = NULL;
6063 smb_ReleaseUID(loggedOutUserp);
6064 loggedOutUserp = NULL;
6068 /* now send the output packet, and return */
6070 smb_SendPacket(vcp, outp);
6071 thrd_Decrement(&ongoingOps);
6073 if (!(vcp->flags & SMB_VCFLAG_ALREADYDEAD)) {
6075 smb_ReleaseVC(active_vcp);
6077 "Replacing active_vcp %x with %x", active_vcp, vcp);
6081 last_msg_time = GetCurrentTime();
6083 else if (active_vcp == vcp) {
6084 smb_ReleaseVC(active_vcp);
6092 /* Wait for Netbios() calls to return, and make the results available to server
6093 * threads. Note that server threads can't wait on the NCBevents array
6094 * themselves, because NCB events are manual-reset, and the servers would race
6095 * each other to reset them.
6097 void smb_ClientWaiter(void *parmp)
6103 code = thrd_WaitForMultipleObjects_Event(numNCBs, NCBevents,
6105 if (code == WAIT_OBJECT_0)
6108 /* error checking */
6109 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numNCBs))
6111 int abandonIdx = code - WAIT_ABANDONED_0;
6112 afsi_log("Error: smb_ClientWaiter event %d abandoned, errno %d\n", abandonIdx, GetLastError());
6115 if (code == WAIT_IO_COMPLETION)
6117 afsi_log("Error: smb_ClientWaiter WAIT_IO_COMPLETION\n");
6121 if (code == WAIT_TIMEOUT)
6123 afsi_log("Error: smb_ClientWaiter WAIT_TIMEOUT, errno %d\n", GetLastError());
6126 if (code == WAIT_FAILED)
6128 afsi_log("Error: smb_ClientWaiter WAIT_FAILED, errno %d\n", GetLastError());
6131 idx = code - WAIT_OBJECT_0;
6133 /* check idx range! */
6134 if (idx < 0 || idx > (sizeof(NCBevents) / sizeof(NCBevents[0])))
6136 /* this is fatal - log as much as possible */
6137 afsi_log("Fatal: NCBevents idx [ %d ] out of range.\n", idx);
6141 thrd_ResetEvent(NCBevents[idx]);
6142 thrd_SetEvent(NCBreturns[0][idx]);
6148 * Try to have one NCBRECV request waiting for every live session. Not more
6149 * than one, because if there is more than one, it's hard to handle Write Raw.
6151 void smb_ServerWaiter(void *parmp)
6154 int idx_session, idx_NCB;
6162 code = thrd_WaitForMultipleObjects_Event(numSessions, SessionEvents,
6164 if (code == WAIT_OBJECT_0)
6167 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numSessions))
6169 int abandonIdx = code - WAIT_ABANDONED_0;
6170 afsi_log("Error: smb_ServerWaiter (SessionEvents) event %d abandoned, errno %d\n", abandonIdx, GetLastError());
6173 if (code == WAIT_IO_COMPLETION)
6175 afsi_log("Error: smb_ServerWaiter (SessionEvents) WAIT_IO_COMPLETION\n");
6179 if (code == WAIT_TIMEOUT)
6181 afsi_log("Error: smb_ServerWaiter (SessionEvents) WAIT_TIMEOUT, errno %d\n", GetLastError());
6184 if (code == WAIT_FAILED)
6186 afsi_log("Error: smb_ServerWaiter (SessionEvents) WAIT_FAILED, errno %d\n", GetLastError());
6189 idx_session = code - WAIT_OBJECT_0;
6191 /* check idx range! */
6192 if (idx_session < 0 || idx_session > (sizeof(SessionEvents) / sizeof(SessionEvents[0])))
6194 /* this is fatal - log as much as possible */
6195 afsi_log("Fatal: session idx [ %d ] out of range.\n", idx_session);
6201 code = thrd_WaitForMultipleObjects_Event(numNCBs, NCBavails,
6203 if (code == WAIT_OBJECT_0)
6206 /* error checking */
6207 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numNCBs))
6209 int abandonIdx = code - WAIT_ABANDONED_0;
6210 afsi_log("Error: smb_ClientWaiter (NCBavails) event %d abandoned, errno %d\n", abandonIdx, GetLastError());
6213 if (code == WAIT_IO_COMPLETION)
6215 afsi_log("Error: smb_ClientWaiter (NCBavails) WAIT_IO_COMPLETION\n");
6219 if (code == WAIT_TIMEOUT)
6221 afsi_log("Error: smb_ClientWaiter (NCBavails) WAIT_TIMEOUT, errno %d\n", GetLastError());
6224 if (code == WAIT_FAILED)
6226 afsi_log("Error: smb_ClientWaiter (NCBavails) WAIT_FAILED, errno %d\n", GetLastError());
6229 idx_NCB = code - WAIT_OBJECT_0;
6231 /* check idx range! */
6232 if (idx_NCB < 0 || idx_NCB > (sizeof(NCBsessions) / sizeof(NCBsessions[0])))
6234 /* this is fatal - log as much as possible */
6235 afsi_log("Fatal: idx_NCB [ %d ] out of range.\n", idx_NCB);
6239 /* Link them together */
6240 NCBsessions[idx_NCB] = idx_session;
6243 ncbp = NCBs[idx_NCB];
6245 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6247 ncbp->ncb_lsn = (unsigned char) LSNs[idx_session];
6248 ncbp->ncb_command = NCBRECV | ASYNCH;
6249 ncbp->ncb_lana_num = lanas[idx_session];
6251 ncbp->ncb_buffer = (unsigned char *) bufs[idx_NCB];
6252 ncbp->ncb_event = NCBevents[idx_NCB];
6253 ncbp->ncb_length = SMB_PACKETSIZE;
6256 ncbp->ncb_buffer = bufs[idx_NCB]->dos_pkt;
6257 ((smb_ncb_t*)ncbp)->orig_pkt = bufs[idx_NCB];
6258 ncbp->ncb_event = NCBreturns[0][idx_NCB];
6259 ncbp->ncb_length = SMB_PACKETSIZE;
6260 Netbios(ncbp, dos_ncb);
6266 * The top level loop for handling SMB request messages. Each server thread
6267 * has its own NCB and buffer for sending replies (outncbp, outbufp), but the
6268 * NCB and buffer for the incoming request are loaned to us.
6270 * Write Raw trickery starts here. When we get a Write Raw, we are supposed
6271 * to immediately send a request for the rest of the data. This must come
6272 * before any other traffic for that session, so we delay setting the session
6273 * event until that data has come in.
6275 void smb_Server(VOID *parmp)
6277 int myIdx = (int) parmp;
6281 smb_packet_t *outbufp;
6283 int idx_NCB, idx_session;
6285 smb_vc_t *vcp = NULL;
6292 outbufp = GetPacket();
6293 outbufp->ncbp = outncbp;
6297 /* check for demo expiration */
6299 unsigned long tod = time((void *) 0);
6300 if (tod > EXPIREDATE) {
6301 (*smb_MBfunc)(NULL, "AFS demo expiration",
6303 MB_OK|MB_ICONSTOP|MB_SETFOREGROUND|MB_SERVICE_NOTIFICATION);
6307 #endif /* !NOEXPIRE */
6309 code = thrd_WaitForMultipleObjects_Event(numNCBs, NCBreturns[myIdx],
6311 if (code == WAIT_OBJECT_0) {
6315 /* error checking */
6316 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numNCBs))
6318 int abandonIdx = code - WAIT_ABANDONED_0;
6319 afsi_log("Error: smb_Server ( NCBreturns[%d] ) event %d abandoned, errno %d\n", myIdx, abandonIdx, GetLastError());
6322 if (code == WAIT_IO_COMPLETION)
6324 afsi_log("Error: smb_Server ( NCBreturns[%d] ) WAIT_IO_COMPLETION\n", myIdx);
6328 if (code == WAIT_TIMEOUT)
6330 afsi_log("Error: smb_Server ( NCBreturns[%d] ) WAIT_TIMEOUT, errno %d\n", myIdx, GetLastError());
6333 if (code == WAIT_FAILED)
6335 afsi_log("Error: smb_Server ( NCBreturns[%d] ) WAIT_FAILED, errno %d\n", myIdx, GetLastError());
6338 idx_NCB = code - WAIT_OBJECT_0;
6340 /* check idx range! */
6341 if (idx_NCB < 0 || idx_NCB > (sizeof(NCBs) / sizeof(NCBs[0])))
6343 /* this is fatal - log as much as possible */
6344 afsi_log("Fatal: idx_NCB [ %d ] out of range.\n", idx_NCB);
6348 ncbp = NCBs[idx_NCB];
6350 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6352 idx_session = NCBsessions[idx_NCB];
6353 rc = ncbp->ncb_retcode;
6355 if (rc != NRC_PENDING && rc != NRC_GOODRET)
6356 osi_Log1(smb_logp, "NCBRECV failure code %d", rc);
6359 case NRC_GOODRET: break;
6362 /* Can this happen? Or is it just my
6369 /* Client closed session */
6370 if (reportSessionStartups)
6372 afsi_log("session [ %d ] closed", idx_session);
6374 dead_sessions[idx_session] = TRUE;
6377 vcp = smb_FindVC(ncbp->ncb_lsn, 0, lanas[idx_session]);
6378 /* Should also release vcp. [done] 2004-05-11 jaltman
6380 * sanity check that all TID's are gone.
6382 * TODO: check if we could use LSNs[idx_session] instead,
6383 * also cleanup after dead vcp
6388 "dead_vcp already set, %x",
6390 if (!dead_vcp && !(vcp->flags & SMB_VCFLAG_ALREADYDEAD)) {
6392 "setting dead_vcp %x, user struct %x",
6396 vcp->flags |= SMB_VCFLAG_ALREADYDEAD;
6398 if (vcp->justLoggedOut) {
6400 loggedOutTime = vcp->logoffTime;
6402 strdup(vcp->justLoggedOut->unp->name);
6403 loggedOutUserp = vcp->justLoggedOut;
6404 lock_ObtainWrite(&smb_rctLock);
6405 loggedOutUserp->refCount++;
6406 lock_ReleaseWrite(&smb_rctLock);
6412 /* Treat as transient error */
6419 osi_Log1(smb_logp, "dispatch smb recv failed, message incomplete, ncb_length %d",
6421 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
6422 sprintf(s, "SMB message incomplete, length %d",
6425 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0,
6427 ncbp->ncb_length, ptbuf,
6429 DeregisterEventSource(h);
6432 "dispatch smb recv failed, message incomplete, ncb_length %d",
6435 "SMB message incomplete, "
6436 "length %d", ncbp->ncb_length);
6440 * We used to discard the packet.
6441 * Instead, try handling it normally.
6449 /* A weird error code. Log it, sleep, and
6451 if (vcp && vcp->errorCount++ > 3) {
6452 afsi_log("session [ %d ] closed, vcp->errorCount = %d", idx_session, vcp->errorCount);
6453 dead_sessions[idx_session] = TRUE;
6457 thrd_SetEvent(SessionEvents[idx_session]);
6462 /* Success, so now dispatch on all the data in the packet */
6464 smb_concurrentCalls++;
6465 if (smb_concurrentCalls > smb_maxObsConcurrentCalls)
6466 smb_maxObsConcurrentCalls = smb_concurrentCalls;
6470 vcp = smb_FindVC(ncbp->ncb_lsn, 0, ncbp->ncb_lana_num);
6472 * If at this point vcp is NULL (implies that packet was invalid)
6473 * then we are in big trouble. This means either :
6474 * a) we have the wrong NCB.
6475 * b) Netbios screwed up the call.
6476 * Obviously this implies that
6477 * ( LSNs[idx_session] != ncbp->ncb_lsn ||
6478 * lanas[idx_session] != ncbp->ncb_lana_num )
6479 * Either way, we can't do anything with this packet.
6480 * Log, sleep and resume.
6489 "LSNs[idx_session]=[%d],"
6490 "lanas[idx_session]=[%d],"
6491 "ncbp->ncb_lsn=[%d],"
6492 "ncbp->ncb_lana_num=[%d]",
6496 ncbp->ncb_lana_num);
6500 h = RegisterEventSource(NULL,AFS_DAEMON_EVENT_NAME);
6502 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1001, NULL,1,sizeof(*ncbp),ptbuf,(void*)ncbp);
6503 DeregisterEventSource(h);
6506 /* Also log in the trace log. */
6507 osi_Log4(smb_logp, "Server: BAD VCP!"
6508 "LSNs[idx_session]=[%d],"
6509 "lanas[idx_session]=[%d],"
6510 "ncbp->ncb_lsn=[%d],"
6511 "ncbp->ncb_lana_num=[%d]",
6515 ncbp->ncb_lana_num);
6517 /* thrd_Sleep(1000); Don't bother sleeping */
6518 thrd_SetEvent(SessionEvents[idx_session]);
6519 smb_concurrentCalls--;
6524 vcp->errorCount = 0;
6525 bufp = (struct smb_packet *) ncbp->ncb_buffer;
6527 bufp = ((smb_ncb_t *) ncbp)->orig_pkt;
6528 /* copy whole packet to virtual memory */
6529 /*fprintf(stderr, "smb_Server: copying dos packet at 0x%x, "
6531 bufp->dos_pkt / 16, bufp);*/
6533 dosmemget(bufp->dos_pkt, ncbp->ncb_length, bufp->data);
6535 smbp = (smb_t *)bufp->data;
6538 #if !defined(DJGPP) && !defined(AFS_WIN32_ENV)
6542 if (smbp->com == 0x1d) {
6543 /* Special handling for Write Raw */
6544 raw_write_cont_t rwc;
6545 EVENT_HANDLE rwevent;
6546 char eventName[MAX_PATH];
6548 smb_DispatchPacket(vcp, bufp, outbufp, ncbp, &rwc);
6549 if (rwc.code == 0) {
6550 rwevent = thrd_CreateEvent(NULL, FALSE, FALSE, TEXT("smb_Server() rwevent"));
6551 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6552 afsi_log("Event Object Already Exists: %s", eventName);
6553 ncbp->ncb_command = NCBRECV | ASYNCH;
6554 ncbp->ncb_lsn = (unsigned char) vcp->lsn;
6555 ncbp->ncb_lana_num = vcp->lana;
6556 ncbp->ncb_buffer = rwc.buf;
6557 ncbp->ncb_length = 65535;
6558 ncbp->ncb_event = rwevent;
6562 Netbios(ncbp, dos_ncb);
6564 rcode = thrd_WaitForSingleObject_Event(rwevent, RAWTIMEOUT);
6565 thrd_CloseHandle(rwevent);
6567 thrd_SetEvent(SessionEvents[idx_session]);
6569 smb_CompleteWriteRaw(vcp, bufp, outbufp, ncbp, &rwc);
6570 } else if (smbp->com == 0xa0) {
6572 * Serialize the handling for NT Transact
6575 smb_DispatchPacket(vcp, bufp, outbufp, ncbp, NULL);
6576 thrd_SetEvent(SessionEvents[idx_session]);
6578 thrd_SetEvent(SessionEvents[idx_session]);
6579 /* TODO: what else needs to be serialized? */
6580 smb_DispatchPacket(vcp, bufp, outbufp, ncbp, NULL);
6582 #if !defined(DJGPP) && !defined(AFS_WIN95_ENV)
6584 __except( smb_ServerExceptionFilter() ) {
6588 smb_concurrentCalls--;
6591 thrd_SetEvent(NCBavails[idx_NCB]);
6598 * Exception filter for the server threads. If an exception occurs in the
6599 * dispatch routines, which is where exceptions are most common, then do a
6600 * force trace and give control to upstream exception handlers. Useful for
6603 #if !defined(DJGPP) && !defined(AFS_WIN95_ENV)
6604 DWORD smb_ServerExceptionFilter(void) {
6605 /* While this is not the best time to do a trace, if it succeeds, then
6606 * we have a trace (assuming tracing was enabled). Otherwise, this should
6607 * throw a second exception.
6612 ptbuf[0] = "Unhandled exception forcing trace";
6614 h = RegisterEventSource(NULL,AFS_DAEMON_EVENT_NAME);
6616 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1001, NULL,1,0,ptbuf,NULL);
6617 DeregisterEventSource(h);
6620 afsd_ForceTrace(TRUE);
6621 return EXCEPTION_CONTINUE_SEARCH;
6626 * Create a new NCB and associated events, packet buffer, and "space" buffer.
6627 * If the number of server threads is M, and the number of live sessions is
6628 * N, then the number of NCB's in use at any time either waiting for, or
6629 * holding, received messages is M + N, so that is how many NCB's get created.
6631 void InitNCBslot(int idx)
6633 struct smb_packet *bufp;
6634 EVENT_HANDLE retHandle;
6636 char eventName[MAX_PATH];
6638 osi_assert( idx < (sizeof(NCBs) / sizeof(NCBs[0])) );
6640 NCBs[idx] = GetNCB();
6641 sprintf(eventName,"NCBavails[%d]", idx);
6642 NCBavails[idx] = thrd_CreateEvent(NULL, FALSE, TRUE, eventName);
6643 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6644 afsi_log("Event Object Already Exists: %s", eventName);
6646 sprintf(eventName,"NCBevents[%d]", idx);
6647 NCBevents[idx] = thrd_CreateEvent(NULL, TRUE, FALSE, eventName);
6648 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6649 afsi_log("Event Object Already Exists: %s", eventName);
6651 sprintf(eventName,"NCBReturns[0<=i<smb_NumServerThreads][%d]", idx);
6652 retHandle = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6653 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6654 afsi_log("Event Object Already Exists: %s", eventName);
6655 for (i=0; i<smb_NumServerThreads; i++)
6656 NCBreturns[i][idx] = retHandle;
6658 bufp->spacep = cm_GetSpace();
6662 /* listen for new connections */
6663 void smb_Listener(void *parmp)
6671 char rname[NCBNAMSZ+1];
6672 char cname[MAX_COMPUTERNAME_LENGTH+1];
6673 int cnamelen = MAX_COMPUTERNAME_LENGTH+1;
6678 int lana = (int) parmp;
6682 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6685 /* retrieve computer name */
6686 GetComputerName(cname, &cnamelen);
6690 memset(ncbp, 0, sizeof(NCB));
6694 /* check for demo expiration */
6696 unsigned long tod = time((void *) 0);
6697 if (tod > EXPIREDATE) {
6698 (*smb_MBfunc)(NULL, "AFS demo expiration",
6700 MB_OK|MB_ICONSTOP|MB_SETFOREGROUND|MB_SERVICE_NOTIFICATION);
6708 #endif /* !NOEXPIRE */
6710 ncbp->ncb_command = NCBLISTEN;
6711 ncbp->ncb_rto = 0; /* No receive timeout */
6712 ncbp->ncb_sto = 0; /* No send timeout */
6714 /* pad out with spaces instead of null termination */
6715 len = strlen(smb_localNamep);
6716 strncpy(ncbp->ncb_name, smb_localNamep, NCBNAMSZ);
6717 for(i=len; i<NCBNAMSZ; i++) ncbp->ncb_name[i] = ' ';
6719 strcpy(ncbp->ncb_callname, "*");
6720 for(i=1; i<NCBNAMSZ; i++) ncbp->ncb_callname[i] = ' ';
6722 ncbp->ncb_lana_num = lana;
6725 code = Netbios(ncbp);
6727 code = Netbios(ncbp, dos_ncb);
6736 /* terminate silently if shutdown flag is set */
6737 if (smbShutdownFlag == 1) {
6746 "NCBLISTEN lana=%d failed with code %d",
6747 ncbp->ncb_lana_num, code);
6749 "Client exiting due to network failure. Please restart client.\n");
6753 "Client exiting due to network failure. Please restart client.\n"
6754 "NCBLISTEN lana=%d failed with code %d",
6755 ncbp->ncb_lana_num, code);
6757 code = (*smb_MBfunc)(NULL, tbuffer, "AFS Client Service: Fatal Error",
6758 MB_OK|MB_SERVICE_NOTIFICATION);
6759 osi_assert(tbuffer);
6762 fprintf(stderr, "NCBLISTEN lana=%d failed with code %d\n",
6763 ncbp->ncb_lana_num, code);
6764 fprintf(stderr, "\nClient exiting due to network failure "
6765 "(possibly due to power-saving mode)\n");
6766 fprintf(stderr, "Please restart client.\n");
6767 afs_exit(AFS_EXITCODE_NETWORK_FAILURE);
6771 /* check for remote conns */
6772 /* first get remote name and insert null terminator */
6773 memcpy(rname, ncbp->ncb_callname, NCBNAMSZ);
6774 for (i=NCBNAMSZ; i>0; i--) {
6775 if (rname[i-1] != ' ' && rname[i-1] != 0) {
6781 /* compare with local name */
6783 if (strncmp(rname, cname, NCBNAMSZ) != 0)
6784 flags |= SMB_VCFLAG_REMOTECONN;
6786 osi_Log1(smb_logp, "New session lsn %d", ncbp->ncb_lsn);
6788 lock_ObtainMutex(&smb_ListenerLock);
6790 /* New generation */
6793 /* Log session startup */
6795 fprintf(stderr, "New session(ncb_lsn,ncb_lana_num) %d,%d starting from host "
6797 ncbp->ncb_lsn,ncbp->ncb_lana_num, rname);
6799 afsi_log("New session(ncb_lsn,ncb_lana_num) (%d,%d) starting from host %s, %d ongoing ops",
6800 ncbp->ncb_lsn,ncbp->ncb_lana_num, rname, ongoingOps);
6802 if (reportSessionStartups) {
6808 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
6809 sprintf(s, "SMB session startup, %d ongoing ops", ongoingOps);
6811 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1004, NULL,
6813 DeregisterEventSource(h);
6815 afsi_log("NCBLISTEN completed, call from %s",rname);
6816 osi_Log1(smb_logp, "SMB session startup, %d ongoing ops",
6819 fprintf(stderr, "%s: New session %d starting from host %s\n",
6820 asctime(localtime(&now)), ncbp->ncb_lsn, rname);
6825 /* now ncbp->ncb_lsn is the connection ID */
6826 vcp = smb_FindVC(ncbp->ncb_lsn, SMB_FLAG_CREATE, ncbp->ncb_lana_num);
6827 vcp->flags |= flags;
6828 strcpy(vcp->rname, rname);
6830 /* Allocate slot in session arrays */
6831 /* Re-use dead session if possible, otherwise add one more */
6832 /* But don't look at session[0], it is reserved */
6833 for (i = 1; i < numSessions; i++) {
6834 if (dead_sessions[i]) {
6835 afsi_log("connecting to dead session [ %d ]", i);
6836 dead_sessions[i] = FALSE;
6841 /* assert that we do not exceed the maximum number of sessions or NCBs.
6842 * we should probably want to wait for a session to be freed in case
6846 osi_assert(i < Sessionmax - 1);
6847 osi_assert(numNCBs < NCBmax - 1); /* if we pass this test we can allocate one more */
6849 LSNs[i] = ncbp->ncb_lsn;
6850 lanas[i] = ncbp->ncb_lana_num;
6852 if (i == numSessions) {
6853 /* Add new NCB for new session */
6854 char eventName[MAX_PATH];
6856 osi_Log1(smb_logp, "smb_Listener creating new session %d", i);
6858 InitNCBslot(numNCBs);
6860 thrd_SetEvent(NCBavails[0]);
6861 thrd_SetEvent(NCBevents[0]);
6862 for (j = 0; j < smb_NumServerThreads; j++)
6863 thrd_SetEvent(NCBreturns[j][0]);
6864 /* Also add new session event */
6865 sprintf(eventName, "SessionEvents[%d]", i);
6866 SessionEvents[i] = thrd_CreateEvent(NULL, FALSE, TRUE, eventName);
6867 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6868 afsi_log("Event Object Already Exists: %s", eventName);
6870 afsi_log("increasing numNCBs [ %d ] numSessions [ %d ]", numNCBs, numSessions);
6871 thrd_SetEvent(SessionEvents[0]);
6873 thrd_SetEvent(SessionEvents[i]);
6876 lock_ReleaseMutex(&smb_ListenerLock);
6878 } /* dispatch while loop */
6881 /* initialize Netbios */
6882 void smb_NetbiosInit()
6888 int i, lana, code, l;
6890 int delname_tried=0;
6893 OSVERSIONINFO Version;
6895 /* AFAIK, this is the default for the ms loopback adapter.*/
6896 unsigned char kWLA_MAC[6] = { 0x02, 0x00, 0x4c, 0x4f, 0x4f, 0x50 };
6897 /*******************************************************************/
6899 /* Get the version of Windows */
6900 memset(&Version, 0x00, sizeof(Version));
6901 Version.dwOSVersionInfoSize = sizeof(Version);
6902 GetVersionEx(&Version);
6904 /* setup the NCB system */
6907 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6911 if (smb_LANadapter == -1) {
6912 ncbp->ncb_command = NCBENUM;
6913 ncbp->ncb_buffer = (PUCHAR)&lana_list;
6914 ncbp->ncb_length = sizeof(lana_list);
6915 code = Netbios(ncbp);
6917 sprintf(s, "Netbios NCBENUM error code %d", code);
6919 osi_panic(s, __FILE__, __LINE__);
6923 lana_list.length = 1;
6924 lana_list.lana[0] = smb_LANadapter;
6927 for (i = 0; i < lana_list.length; i++) {
6928 /* reset the adaptor: in Win32, this is required for every process, and
6929 * acts as an init call, not as a real hardware reset.
6931 ncbp->ncb_command = NCBRESET;
6932 ncbp->ncb_callname[0] = 100;
6933 ncbp->ncb_callname[2] = 100;
6934 ncbp->ncb_lana_num = lana_list.lana[i];
6935 code = Netbios(ncbp);
6937 code = ncbp->ncb_retcode;
6939 sprintf(s, "Netbios NCBRESET lana %d error code %d", lana_list.lana[i], code);
6941 lana_list.lana[i] = 255; /* invalid lana */
6943 sprintf(s, "Netbios NCBRESET lana %d succeeded", lana_list.lana[i]);
6948 /* for DJGPP, there is no NCBENUM and NCBRESET is a real reset. so
6949 we will just fake the LANA list */
6950 if (smb_LANadapter == -1) {
6951 for (i = 0; i < 8; i++)
6952 lana_list.lana[i] = i;
6953 lana_list.length = 8;
6956 lana_list.length = 1;
6957 lana_list.lana[0] = smb_LANadapter;
6961 /* and declare our name so we can receive connections */
6962 memset(ncbp, 0, sizeof(*ncbp));
6963 len=lstrlen(smb_localNamep);
6964 memset(smb_sharename,' ',NCBNAMSZ);
6965 memcpy(smb_sharename,smb_localNamep,len);
6966 sprintf(s, "lana_list.length %d", lana_list.length);
6969 /* Keep the name so we can unregister it later */
6970 for (l = 0; l < lana_list.length; l++) {
6971 lana = lana_list.lana[l];
6973 ncbp->ncb_command = NCBADDNAME;
6974 ncbp->ncb_lana_num = lana;
6975 memcpy(ncbp->ncb_name,smb_sharename,NCBNAMSZ);
6977 code = Netbios(ncbp);
6979 code = Netbios(ncbp, dos_ncb);
6982 afsi_log("Netbios NCBADDNAME lana=%d code=%d retcode=%d complete=%d",
6983 lana, code, ncbp->ncb_retcode,ncbp->ncb_cmd_cplt);
6985 char name[NCBNAMSZ+1];
6987 memcpy(name,ncbp->ncb_name,NCBNAMSZ);
6988 afsi_log("Netbios NCBADDNAME added new name >%s<",name);
6991 if (code == 0) code = ncbp->ncb_retcode;
6993 afsi_log("Netbios NCBADDNAME succeeded on lana %d\n", lana);
6995 /* we only use one LANA with djgpp */
6996 lana_list.lana[0] = lana;
6997 lana_list.length = 1;
7001 sprintf(s, "Netbios NCBADDNAME lana %d error code %d", lana, code);
7003 if (code == NRC_BRIDGE) { /* invalid LANA num */
7004 lana_list.lana[l] = 255;
7007 else if (code == NRC_DUPNAME) {
7008 afsi_log("Name already exists; try to delete it");
7009 memset(ncbp, 0, sizeof(*ncbp));
7010 ncbp->ncb_command = NCBDELNAME;
7011 memcpy(ncbp->ncb_name,smb_sharename,NCBNAMSZ);
7012 ncbp->ncb_lana_num = lana;
7014 code = Netbios(ncbp);
7016 code = Netbios(ncbp, dos_ncb);
7018 if (code == 0) code = ncbp->ncb_retcode;
7020 sprintf(s, "Netbios NCBDELNAME lana %d error code %d\n", lana, code);
7023 if (code != 0 || delname_tried) {
7024 lana_list.lana[l] = 255;
7026 else if (code == 0) {
7027 if (!delname_tried) {
7035 sprintf(s, "Netbios NCBADDNAME lana %d error code %d", lana, code);
7037 lana_list.lana[l] = 255; /* invalid lana */
7038 osi_panic(s, __FILE__, __LINE__);
7042 lana_found = 1; /* at least one worked */
7049 osi_assert(lana_list.length >= 0);
7051 sprintf(s, "No valid LANA numbers found!");
7052 osi_panic(s, __FILE__, __LINE__);
7055 /* we're done with the NCB now */
7059 void smb_Init(osi_log_t *logp, char *snamep, int useV3, int LANadapt,
7076 EVENT_HANDLE retHandle;
7077 char eventName[MAX_PATH];
7080 smb_MBfunc = aMBfunc;
7084 /* check for demo expiration */
7086 unsigned long tod = time((void *) 0);
7087 if (tod > EXPIREDATE) {
7089 (*smb_MBfunc)(NULL, "AFS demo expiration", "afsd",
7090 MB_OK|MB_ICONSTOP|MB_SETFOREGROUND|MB_SERVICE_NOTIFICATION);
7093 fprintf(stderr, "AFS demo expiration\n");
7098 #endif /* !NOEXPIRE */
7101 smb_LANadapter = LANadapt;
7103 /* Initialize smb_localZero */
7104 myTime.tm_isdst = -1; /* compute whether on DST or not */
7105 myTime.tm_year = 70;
7111 smb_localZero = mktime(&myTime);
7113 /* Initialize kludge-GMT */
7114 smb_CalculateNowTZ();
7116 /* initialize the remote debugging log */
7119 /* remember the name */
7120 len = strlen(snamep);
7121 smb_localNamep = malloc(len+1);
7122 strcpy(smb_localNamep, snamep);
7123 afsi_log("smb_localNamep is >%s<", smb_localNamep);
7125 /* and the global lock */
7126 lock_InitializeRWLock(&smb_globalLock, "smb global lock");
7127 lock_InitializeRWLock(&smb_rctLock, "smb refct and tree struct lock");
7129 /* Raw I/O data structures */
7130 lock_InitializeMutex(&smb_RawBufLock, "smb raw buffer lock");
7132 lock_InitializeMutex(&smb_ListenerLock, "smb listener lock");
7134 /* 4 Raw I/O buffers */
7136 smb_RawBufs = calloc(65536,1);
7137 *((char **)smb_RawBufs) = NULL;
7138 for (i=0; i<3; i++) {
7139 char *rawBuf = calloc(65536,1);
7140 *((char **)rawBuf) = smb_RawBufs;
7141 smb_RawBufs = rawBuf;
7144 npar = 65536 >> 4; /* number of paragraphs */
7145 seg = __dpmi_allocate_dos_memory(npar, &smb_RawBufSel[0]);
7147 afsi_log("Cannot allocate %d paragraphs of DOS memory",
7149 osi_panic("",__FILE__,__LINE__);
7152 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X",
7155 smb_RawBufs = (seg * 16) + 0; /* DOS physical address */
7157 _farpokel(_dos_ds, smb_RawBufs, NULL);
7158 for (i=0; i<SMB_RAW_BUFS-1; i++) {
7159 npar = 65536 >> 4; /* number of paragraphs */
7160 seg = __dpmi_allocate_dos_memory(npar, &smb_RawBufSel[i+1]);
7162 afsi_log("Cannot allocate %d paragraphs of DOS memory",
7164 osi_panic("",__FILE__,__LINE__);
7167 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X",
7170 rawBuf = (seg * 16) + 0; /* DOS physical address */
7171 /*_farpokel(_dos_ds, smb_RawBufs, smb_RawBufs);*/
7172 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
7173 smb_RawBufs = rawBuf;
7177 /* global free lists */
7178 smb_ncbFreeListp = NULL;
7179 smb_packetFreeListp = NULL;
7183 /* Initialize listener and server structures */
7185 memset(dead_sessions, 0, sizeof(dead_sessions));
7186 sprintf(eventName, "SessionEvents[0]");
7187 SessionEvents[0] = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
7188 if ( GetLastError() == ERROR_ALREADY_EXISTS )
7189 afsi_log("Event Object Already Exists: %s", eventName);
7191 smb_NumServerThreads = nThreads;
7192 sprintf(eventName, "NCBavails[0]");
7193 NCBavails[0] = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
7194 if ( GetLastError() == ERROR_ALREADY_EXISTS )
7195 afsi_log("Event Object Already Exists: %s", eventName);
7196 sprintf(eventName, "NCBevents[0]");
7197 NCBevents[0] = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
7198 if ( GetLastError() == ERROR_ALREADY_EXISTS )
7199 afsi_log("Event Object Already Exists: %s", eventName);
7200 NCBreturns = malloc(nThreads * sizeof(EVENT_HANDLE *));
7201 sprintf(eventName, "NCBreturns[0<=i<smb_NumServerThreads][0]");
7202 retHandle = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
7203 if ( GetLastError() == ERROR_ALREADY_EXISTS )
7204 afsi_log("Event Object Already Exists: %s", eventName);
7205 for (i = 0; i < smb_NumServerThreads; i++) {
7206 NCBreturns[i] = malloc(NCBmax * sizeof(EVENT_HANDLE));
7207 NCBreturns[i][0] = retHandle;
7209 for (i = 1; i <= nThreads; i++)
7211 numNCBs = nThreads + 1;
7213 /* Initialize dispatch table */
7214 memset(&smb_dispatchTable, 0, sizeof(smb_dispatchTable));
7215 smb_dispatchTable[0x00].procp = smb_ReceiveCoreMakeDir;
7216 smb_dispatchTable[0x01].procp = smb_ReceiveCoreRemoveDir;
7217 smb_dispatchTable[0x02].procp = smb_ReceiveCoreOpen;
7218 smb_dispatchTable[0x03].procp = smb_ReceiveCoreCreate;
7219 smb_dispatchTable[0x04].procp = smb_ReceiveCoreClose;
7220 smb_dispatchTable[0x05].procp = smb_ReceiveCoreFlush;
7221 smb_dispatchTable[0x06].procp = smb_ReceiveCoreUnlink;
7222 smb_dispatchTable[0x07].procp = smb_ReceiveCoreRename;
7223 smb_dispatchTable[0x08].procp = smb_ReceiveCoreGetFileAttributes;
7224 smb_dispatchTable[0x09].procp = smb_ReceiveCoreSetFileAttributes;
7225 smb_dispatchTable[0x0a].procp = smb_ReceiveCoreRead;
7226 smb_dispatchTable[0x0b].procp = smb_ReceiveCoreWrite;
7227 smb_dispatchTable[0x0c].procp = smb_ReceiveCoreLockRecord;
7228 smb_dispatchTable[0x0d].procp = smb_ReceiveCoreUnlockRecord;
7229 smb_dispatchTable[0x0e].procp = smb_SendCoreBadOp; /* create temporary */
7230 smb_dispatchTable[0x0f].procp = smb_ReceiveCoreCreate;
7231 smb_dispatchTable[0x10].procp = smb_ReceiveCoreCheckPath;
7232 smb_dispatchTable[0x11].procp = smb_SendCoreBadOp; /* process exit */
7233 smb_dispatchTable[0x12].procp = smb_ReceiveCoreSeek;
7234 smb_dispatchTable[0x1a].procp = smb_ReceiveCoreReadRaw;
7235 /* Set NORESPONSE because smb_ReceiveCoreReadRaw() does the responses itself */
7236 smb_dispatchTable[0x1a].flags |= SMB_DISPATCHFLAG_NORESPONSE;
7237 smb_dispatchTable[0x1d].procp = smb_ReceiveCoreWriteRawDummy;
7238 smb_dispatchTable[0x22].procp = smb_ReceiveV3SetAttributes;
7239 smb_dispatchTable[0x23].procp = smb_ReceiveV3GetAttributes;
7240 smb_dispatchTable[0x24].procp = smb_ReceiveV3LockingX;
7241 smb_dispatchTable[0x24].flags |= SMB_DISPATCHFLAG_CHAINED;
7242 smb_dispatchTable[0x25].procp = smb_ReceiveV3Trans;
7243 smb_dispatchTable[0x25].flags |= SMB_DISPATCHFLAG_NORESPONSE;
7244 smb_dispatchTable[0x26].procp = smb_ReceiveV3Trans;
7245 smb_dispatchTable[0x26].flags |= SMB_DISPATCHFLAG_NORESPONSE;
7246 smb_dispatchTable[0x29].procp = smb_SendCoreBadOp; /* copy file */
7247 smb_dispatchTable[0x2b].procp = smb_ReceiveCoreEcho;
7248 /* Set NORESPONSE because smb_ReceiveCoreEcho() does the responses itself */
7249 smb_dispatchTable[0x2b].flags |= SMB_DISPATCHFLAG_NORESPONSE;
7250 smb_dispatchTable[0x2d].procp = smb_ReceiveV3OpenX;
7251 smb_dispatchTable[0x2d].flags |= SMB_DISPATCHFLAG_CHAINED;
7252 smb_dispatchTable[0x2e].procp = smb_ReceiveV3ReadX;
7253 smb_dispatchTable[0x2e].flags |= SMB_DISPATCHFLAG_CHAINED;
7254 smb_dispatchTable[0x32].procp = smb_ReceiveV3Tran2A; /* both are same */
7255 smb_dispatchTable[0x32].flags |= SMB_DISPATCHFLAG_NORESPONSE;
7256 smb_dispatchTable[0x33].procp = smb_ReceiveV3Tran2A;
7257 smb_dispatchTable[0x33].flags |= SMB_DISPATCHFLAG_NORESPONSE;
7258 smb_dispatchTable[0x34].procp = smb_ReceiveV3FindClose;
7259 smb_dispatchTable[0x35].procp = smb_ReceiveV3FindNotifyClose;
7260 smb_dispatchTable[0x70].procp = smb_ReceiveCoreTreeConnect;
7261 smb_dispatchTable[0x71].procp = smb_ReceiveCoreTreeDisconnect;
7262 smb_dispatchTable[0x72].procp = smb_ReceiveNegotiate;
7263 smb_dispatchTable[0x73].procp = smb_ReceiveV3SessionSetupX;
7264 smb_dispatchTable[0x73].flags |= SMB_DISPATCHFLAG_CHAINED;
7265 smb_dispatchTable[0x74].procp = smb_ReceiveV3UserLogoffX;
7266 smb_dispatchTable[0x74].flags |= SMB_DISPATCHFLAG_CHAINED;
7267 smb_dispatchTable[0x75].procp = smb_ReceiveV3TreeConnectX;
7268 smb_dispatchTable[0x75].flags |= SMB_DISPATCHFLAG_CHAINED;
7269 smb_dispatchTable[0x80].procp = smb_ReceiveCoreGetDiskAttributes;
7270 smb_dispatchTable[0x81].procp = smb_ReceiveCoreSearchDir;
7271 smb_dispatchTable[0xA0].procp = smb_ReceiveNTTransact;
7272 smb_dispatchTable[0xA2].procp = smb_ReceiveNTCreateX;
7273 smb_dispatchTable[0xA2].flags |= SMB_DISPATCHFLAG_CHAINED;
7274 smb_dispatchTable[0xA4].procp = smb_ReceiveNTCancel;
7275 smb_dispatchTable[0xA4].flags |= SMB_DISPATCHFLAG_NORESPONSE;
7276 smb_dispatchTable[0xc0].procp = smb_SendCoreBadOp;
7277 smb_dispatchTable[0xc1].procp = smb_SendCoreBadOp;
7278 smb_dispatchTable[0xc2].procp = smb_SendCoreBadOp;
7279 smb_dispatchTable[0xc3].procp = smb_SendCoreBadOp;
7280 for(i=0xd0; i<= 0xd7; i++) {
7281 smb_dispatchTable[i].procp = smb_SendCoreBadOp;
7284 /* setup tran 2 dispatch table */
7285 smb_tran2DispatchTable[0].procp = smb_ReceiveTran2Open;
7286 smb_tran2DispatchTable[1].procp = smb_ReceiveTran2SearchDir; /* FindFirst */
7287 smb_tran2DispatchTable[2].procp = smb_ReceiveTran2SearchDir; /* FindNext */
7288 smb_tran2DispatchTable[3].procp = smb_ReceiveTran2QFSInfo;
7289 smb_tran2DispatchTable[4].procp = smb_ReceiveTran2SetFSInfo;
7290 smb_tran2DispatchTable[5].procp = smb_ReceiveTran2QPathInfo;
7291 smb_tran2DispatchTable[6].procp = smb_ReceiveTran2SetPathInfo;
7292 smb_tran2DispatchTable[7].procp = smb_ReceiveTran2QFileInfo;
7293 smb_tran2DispatchTable[8].procp = smb_ReceiveTran2SetFileInfo;
7294 smb_tran2DispatchTable[9].procp = smb_ReceiveTran2FSCTL;
7295 smb_tran2DispatchTable[10].procp = smb_ReceiveTran2IOCTL;
7296 smb_tran2DispatchTable[11].procp = smb_ReceiveTran2FindNotifyFirst;
7297 smb_tran2DispatchTable[12].procp = smb_ReceiveTran2FindNotifyNext;
7298 smb_tran2DispatchTable[13].procp = smb_ReceiveTran2MKDir;
7300 /* setup the rap dispatch table */
7301 memset(smb_rapDispatchTable, 0, sizeof(smb_rapDispatchTable));
7302 smb_rapDispatchTable[0].procp = smb_ReceiveRAPNetShareEnum;
7303 smb_rapDispatchTable[1].procp = smb_ReceiveRAPNetShareGetInfo;
7304 smb_rapDispatchTable[63].procp = smb_ReceiveRAPNetWkstaGetInfo;
7305 smb_rapDispatchTable[13].procp = smb_ReceiveRAPNetServerGetInfo;
7309 /* if we are doing SMB authentication we have register outselves as a logon process */
7310 if (smb_authType != SMB_AUTH_NONE) {
7312 LSA_STRING afsProcessName;
7313 LSA_OPERATIONAL_MODE dummy; /*junk*/
7315 afsProcessName.Buffer = "OpenAFSClientDaemon";
7316 afsProcessName.Length = strlen(afsProcessName.Buffer);
7317 afsProcessName.MaximumLength = afsProcessName.Length + 1;
7319 nts = LsaRegisterLogonProcess(&afsProcessName, &smb_lsaHandle, &dummy);
7321 if (nts == STATUS_SUCCESS) {
7322 LSA_STRING packageName;
7323 /* we are registered. Find out the security package id */
7324 packageName.Buffer = MSV1_0_PACKAGE_NAME;
7325 packageName.Length = strlen(packageName.Buffer);
7326 packageName.MaximumLength = packageName.Length + 1;
7327 nts = LsaLookupAuthenticationPackage(smb_lsaHandle, &packageName , &smb_lsaSecPackage);
7328 if (nts == STATUS_SUCCESS) {
7329 smb_lsaLogonOrigin.Buffer = "OpenAFS";
7330 smb_lsaLogonOrigin.Length = strlen(smb_lsaLogonOrigin.Buffer);
7331 smb_lsaLogonOrigin.MaximumLength = smb_lsaLogonOrigin.Length + 1;
7333 afsi_log("Can't determine security package name for NTLM!! NTSTATUS=[%l]",nts);
7336 afsi_log("Can't register logon process!! NTSTATUS=[%l]",nts);
7339 if (nts != STATUS_SUCCESS) {
7340 /* something went wrong. We report the error and revert back to no authentication
7341 because we can't perform any auth requests without a successful lsa handle
7342 or sec package id. */
7343 afsi_log("Reverting to NO SMB AUTH");
7344 smb_authType = SMB_AUTH_NONE;
7345 } else if ( smb_authType == SMB_AUTH_EXTENDED) {
7346 /* Test to see if there is anything to negotiate. If SPNEGO is not going to be used
7347 * then the only option is NTLMSSP anyway; so just fallback.
7352 smb_NegotiateExtendedSecurity(&secBlob, &secBlobLength);
7353 if (secBlobLength == 0) {
7354 smb_authType = SMB_AUTH_NTLM;
7355 afsi_log("Reverting to SMB AUTH NTLM");
7363 /* Now get ourselves a domain name. */
7364 /* For now we are using the local computer name as the domain name.
7365 * It is actually the domain for local logins, and we are acting as
7366 * a local SMB server.
7368 bufsize = sizeof(smb_ServerDomainName) - 1;
7369 GetComputerName(smb_ServerDomainName, &bufsize);
7370 smb_ServerDomainNameLength = bufsize + 1; /* bufsize doesn't include terminator */
7371 afsi_log("Setting SMB server domain name to [%s]", smb_ServerDomainName);
7374 /* Start listeners, waiters, servers, and daemons */
7376 for (i = 0; i < lana_list.length; i++) {
7377 if (lana_list.lana[i] == 255) continue;
7378 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_Listener,
7379 (void*)lana_list.lana[i], 0, &lpid, "smb_Listener");
7380 osi_assert(phandle != NULL);
7381 thrd_CloseHandle(phandle);
7385 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_ClientWaiter,
7386 NULL, 0, &lpid, "smb_ClientWaiter");
7387 osi_assert(phandle != NULL);
7388 thrd_CloseHandle(phandle);
7391 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_ServerWaiter,
7392 NULL, 0, &lpid, "smb_ServerWaiter");
7393 osi_assert(phandle != NULL);
7394 thrd_CloseHandle(phandle);
7396 for (i=0; i<nThreads; i++) {
7397 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_Server,
7398 (void *) i, 0, &lpid, "smb_Server");
7399 osi_assert(phandle != NULL);
7400 thrd_CloseHandle(phandle);
7403 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_Daemon,
7404 NULL, 0, &lpid, "smb_Daemon");
7405 osi_assert(phandle != NULL);
7406 thrd_CloseHandle(phandle);
7408 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_WaitingLocksDaemon,
7409 NULL, 0, &lpid, "smb_WaitingLocksDaemon");
7410 osi_assert(phandle != NULL);
7411 thrd_CloseHandle(phandle);
7420 void smb_Shutdown(void)
7429 /*fprintf(stderr, "Entering smb_Shutdown\n");*/
7431 /* setup the NCB system */
7434 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
7437 /* Block new sessions by setting shutdown flag */
7438 smbShutdownFlag = 1;
7440 /* Hang up all sessions */
7441 memset((char *)ncbp, 0, sizeof(NCB));
7442 for (i = 1; i < numSessions; i++)
7444 if (dead_sessions[i])
7447 /*fprintf(stderr, "NCBHANGUP session %d LSN %d\n", i, LSNs[i]);*/
7448 ncbp->ncb_command = NCBHANGUP;
7449 ncbp->ncb_lana_num = lanas[i]; /*smb_LANadapter;*/
7450 ncbp->ncb_lsn = LSNs[i];
7452 code = Netbios(ncbp);
7454 code = Netbios(ncbp, dos_ncb);
7456 /*fprintf(stderr, "returned from NCBHANGUP session %d LSN %d\n", i, LSNs[i]);*/
7457 if (code == 0) code = ncbp->ncb_retcode;
7459 osi_Log1(smb_logp, "Netbios NCBHANGUP error code %d", code);
7460 fprintf(stderr, "Session %d Netbios NCBHANGUP error code %d", i, code);
7464 /* Delete Netbios name */
7465 memset((char *)ncbp, 0, sizeof(NCB));
7466 for (i = 0; i < lana_list.length; i++) {
7467 if (lana_list.lana[i] == 255) continue;
7468 ncbp->ncb_command = NCBDELNAME;
7469 ncbp->ncb_lana_num = lana_list.lana[i];
7470 memcpy(ncbp->ncb_name,smb_sharename,NCBNAMSZ);
7472 code = Netbios(ncbp);
7474 code = Netbios(ncbp, dos_ncb);
7476 if (code == 0) code = ncbp->ncb_retcode;
7478 fprintf(stderr, "Netbios NCBDELNAME lana %d error code %d",
7479 ncbp->ncb_lana_num, code);
7485 /* Get the UNC \\<servername>\<sharename> prefix. */
7486 char *smb_GetSharename()
7490 /* Make sure we have been properly initialized. */
7491 if (smb_localNamep == NULL)
7494 /* Allocate space for \\<servername>\<sharename>, plus the
7497 name = malloc(strlen(smb_localNamep) + strlen("ALL") + 4);
7498 sprintf(name, "\\\\%s\\%s", smb_localNamep, "ALL");
7504 void smb_LogPacket(smb_packet_t *packet)
7507 unsigned length, paramlen, datalen, i, j;
7509 char hex[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
7513 osi_Log0(smb_logp, "*** SMB packet dump ***");
7515 vp = (BYTE *) packet->data;
7517 datalen = *((WORD*)(vp + (paramlen = ((unsigned)*(vp+20)) << 1)));
7518 length = paramlen + 2 + datalen;
7521 for(i=0;i < length; i+=16)
7523 memset( buf, ' ', 80 );
7528 buf[strlen(buf)] = ' ';
7530 cp = (BYTE*) buf + 7;
7532 for(j=0;j < 16 && (i+j)<length; j++)
7534 *(cp++) = hex[vp[i+j] >> 4];
7535 *(cp++) = hex[vp[i+j] & 0xf];
7545 for(j=0;j < 16 && (i+j)<length;j++)
7547 *(cp++) = ( 32 <= vp[i+j] && 128 > vp[i+j] )? vp[i+j]:'.';
7558 osi_Log0( smb_logp, buf );
7561 osi_Log0(smb_logp, "*** End SMB packet dump ***");
7565 #endif /* NOTSERVICE */
7567 int smb_DumpVCP(FILE *outputFile, char *cookie)
7574 lock_ObtainRead(&smb_rctLock);
7576 sprintf(output, "begin dumping vcpsp\n");
7577 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7579 for(vcp = smb_allVCsp; vcp; vcp=vcp->nextp)
7583 sprintf(output, "%s vcp=0x%08X, refCount=%d, flags=%d, vcID=%d, lsn=%d, uidCounter=%d, tidCounter=%d, fidCounter=%d\n",
7584 cookie, vcp, vcp->refCount, vcp->flags, vcp->vcID, vcp->lsn, vcp->uidCounter, vcp->tidCounter, vcp->fidCounter);
7585 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7587 sprintf(output, "begin dumping fidsp\n");
7588 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7590 for (fidp = vcp->fidsp; fidp; fidp = (smb_fid_t *) osi_QNext(&fidp->q))
7592 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",
7593 cookie, fidp, fidp->refCount, fidp->fid, fidp->vcp, fidp->scp, fidp->ioctlp,
7594 fidp->NTopen_pathp ? fidp->NTopen_pathp : "NULL",
7595 fidp->NTopen_wholepathp ? fidp->NTopen_wholepathp : "NULL");
7596 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7599 sprintf(output, "done dumping fidsp\n");
7600 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7603 sprintf(output, "done dumping vcpsp\n");
7604 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7606 lock_ReleaseRead(&smb_rctLock);