2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
12 #define NOMOREFILESFIX 1
14 #include <afs/param.h>
20 #include <sys/timeb.h>
36 #include "lanahelper.h"
38 /* These characters are illegal in Windows filenames */
39 static char *illegalChars = "\\/:*?\"<>|";
40 BOOL isWindows2000 = FALSE;
42 smb_vc_t *dead_vcp = NULL;
43 smb_vc_t *active_vcp = NULL;
45 /* TODO; logout mechanism needs to be thread-safe */
46 char *loggedOutName = NULL;
47 smb_user_t *loggedOutUserp = NULL;
48 unsigned long loggedOutTime;
50 int smbShutdownFlag = 0;
52 int smb_LogoffTokenTransfer;
53 unsigned long smb_LogoffTransferTimeout;
55 DWORD last_msg_time = 0;
59 unsigned int sessionGen = 0;
61 extern void afsi_log(char *pattern, ...);
62 extern HANDLE afsi_file;
64 osi_hyper_t hzero = {0, 0};
65 osi_hyper_t hones = {0xFFFFFFFF, -1};
68 osi_rwlock_t smb_globalLock;
69 osi_rwlock_t smb_rctLock;
70 osi_mutex_t smb_ListenerLock;
73 unsigned char smb_sharename[NCBNAMSZ+1] = {0};
76 long smb_maxObsConcurrentCalls=0;
77 long smb_concurrentCalls=0;
79 smb_dispatch_t smb_dispatchTable[SMB_NOPCODES];
81 smb_packet_t *smb_packetFreeListp;
82 smb_ncb_t *smb_ncbFreeListp;
84 int smb_NumServerThreads;
86 int numNCBs, numSessions, numVCs;
88 int smb_maxVCPerServer;
89 int smb_maxMpxRequests;
91 int smb_authType = SMB_AUTH_EXTENDED; /* type of SMB auth to use. One of SMB_AUTH_* */
93 ULONG smb_lsaSecPackage;
94 LSA_STRING smb_lsaLogonOrigin;
96 #define NCBmax MAXIMUM_WAIT_OBJECTS
97 EVENT_HANDLE NCBavails[NCBmax], NCBevents[NCBmax];
98 EVENT_HANDLE **NCBreturns;
99 DWORD NCBsessions[NCBmax];
101 struct smb_packet *bufs[NCBmax];
103 #define Sessionmax MAXIMUM_WAIT_OBJECTS
104 EVENT_HANDLE SessionEvents[Sessionmax];
105 unsigned short LSNs[Sessionmax];
106 int lanas[Sessionmax];
107 BOOL dead_sessions[Sessionmax];
111 osi_mutex_t smb_RawBufLock;
113 #define SMB_RAW_BUFS 4
115 int smb_RawBufSel[SMB_RAW_BUFS];
120 #define SMB_MASKFLAG_TILDE 1
121 #define SMB_MASKFLAG_CASEFOLD 2
123 #define RAWTIMEOUT INFINITE
126 typedef struct raw_write_cont {
139 /* dir search stuff */
140 long smb_dirSearchCounter = 1;
141 smb_dirSearch_t *smb_firstDirSearchp;
142 smb_dirSearch_t *smb_lastDirSearchp;
144 /* hide dot files? */
145 int smb_hideDotFiles;
147 /* global state about V3 protocols */
148 int smb_useV3; /* try to negotiate V3 */
151 static showErrors = 1;
152 /* MessageBox or something like it */
153 int (_stdcall *smb_MBfunc)(HWND, LPCTSTR, LPCTSTR, UINT) = NULL;
154 extern HANDLE WaitToTerminate;
158 * Time in Unix format of midnight, 1/1/1970 local time.
159 * When added to dosUTime, gives Unix (AFS) time.
163 /* Time difference for converting to kludge-GMT */
166 char *smb_localNamep = NULL;
168 smb_vc_t *smb_allVCsp;
170 smb_username_t *usernamesp = NULL;
172 smb_waitingLock_t *smb_allWaitingLocks;
175 void smb_DispatchPacket(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp,
176 NCB *ncbp, raw_write_cont_t *rwcp);
177 void smb_NetbiosInit();
179 #ifndef AFS_WIN95_ENV
180 DWORD smb_ServerExceptionFilter(void);
183 extern char cm_HostName[];
184 extern char cm_confDir[];
188 #define LPTSTR char *
189 #define GetComputerName(str, sizep) \
190 strcpy((str), cm_HostName); \
191 *(sizep) = strlen(cm_HostName)
194 extern char AFSConfigKeyName[];
196 char smb_ServerDomainName[MAX_COMPUTERNAME_LENGTH + 1] = ""; /* domain name */
197 int smb_ServerDomainNameLength = 0;
198 char smb_ServerOS[] = "Windows 5.0"; /* Faux OS String */
199 int smb_ServerOSLength = sizeof(smb_ServerOS);
200 char smb_ServerLanManager[] = "Windows 2000 LAN Manager"; /* Faux LAN Manager string */
201 int smb_ServerLanManagerLength = sizeof(smb_ServerLanManager);
203 GUID smb_ServerGUID = { 0x40015cb8, 0x058a, 0x44fc, { 0xae, 0x7e, 0xbb, 0x29, 0x52, 0xee, 0x7e, 0xff }};
208 * To build an expiring version, comment out the definition of NOEXPIRE,
209 * and set the definition of EXPIREDATE to the desired value.
212 #define EXPIREDATE 834000000 /* Wed Jun 5 1996 */
215 char * myCrt_Dispatch(int i)
220 return "unknown SMB op";
222 return "(00)ReceiveCoreMakeDir";
224 return "(01)ReceiveCoreRemoveDir";
226 return "(02)ReceiveCoreOpen";
228 return "(03)ReceiveCoreCreate";
230 return "(04)ReceiveCoreClose";
232 return "(05)ReceiveCoreFlush";
234 return "(06)ReceiveCoreUnlink";
236 return "(07)ReceiveCoreRename";
238 return "(08)ReceiveCoreGetFileAttributes";
240 return "(09)ReceiveCoreSetFileAttributes";
242 return "(0a)ReceiveCoreRead";
244 return "(0b)ReceiveCoreWrite";
246 return "(0c)ReceiveCoreLockRecord";
248 return "(0d)ReceiveCoreUnlockRecord";
250 return "(0e)SendCoreBadOp";
252 return "(0f)ReceiveCoreCreate";
254 return "(10)ReceiveCoreCheckPath";
256 return "(11)SendCoreBadOp";
258 return "(12)ReceiveCoreSeek";
260 return "(1a)ReceiveCoreReadRaw";
262 return "(1d)ReceiveCoreWriteRawDummy";
264 return "(22)ReceiveV3SetAttributes";
266 return "(23)ReceiveV3GetAttributes";
268 return "(24)ReceiveV3LockingX";
270 return "(29)SendCoreBadOp";
272 return "(2b)ReceiveCoreEcho";
274 return "(2d)ReceiveV3OpenX";
276 return "(2e)ReceiveV3ReadX";
278 return "(32)ReceiveV3Tran2A";
280 return "(33)ReceiveV3Tran2A";
282 return "(34)ReceiveV3FindClose";
284 return "(35)ReceiveV3FindNotifyClose";
286 return "(70)ReceiveCoreTreeConnect";
288 return "(71)ReceiveCoreTreeDisconnect";
290 return "(72)ReceiveNegotiate";
292 return "(73)ReceiveV3SessionSetupX";
294 return "(74)ReceiveV3UserLogoffX";
296 return "(75)ReceiveV3TreeConnectX";
298 return "(80)ReceiveCoreGetDiskAttributes";
300 return "(81)ReceiveCoreSearchDir";
302 return "(A0)ReceiveNTTransact";
304 return "(A2)ReceiveNTCreateX";
306 return "(A4)ReceiveNTCancel";
308 return "(c0)SendCoreBadOp";
310 return "(c1)SendCoreBadOp";
312 return "(c2)SendCoreBadOp";
314 return "(c3)SendCoreBadOp";
318 char * myCrt_2Dispatch(int i)
323 return "unknown SMB op-2";
325 return "S(00)CreateFile";
327 return "S(01)FindFirst";
329 return "S(02)FindNext"; /* FindNext */
331 return "S(03)QueryFileSystem_ReceiveTran2QFSInfo";
335 return "S(05)QueryFileInfo_ReceiveTran2QPathInfo";
337 return "S(06)SetFileInfo_ReceiveTran2SetPathInfo";
339 return "S(07)SetInfoHandle_ReceiveTran2QFileInfo";
341 return "S(08)??_ReceiveTran2SetFileInfo";
343 return "S(09)??_ReceiveTran2FSCTL";
345 return "S(0a)_ReceiveTran2IOCTL";
347 return "S(0b)_ReceiveTran2FindNotifyFirst";
349 return "S(0c)_ReceiveTran2FindNotifyNext";
351 return "S(0d)CreateDirectory_ReceiveTran2MKDir";
355 /* scache must be locked */
356 unsigned int smb_Attributes(cm_scache_t *scp)
360 if (scp->fileType == CM_SCACHETYPE_DIRECTORY
361 || scp->fileType == CM_SCACHETYPE_MOUNTPOINT)
362 attrs = SMB_ATTR_DIRECTORY;
367 * We used to mark a file RO if it was in an RO volume, but that
368 * turns out to be impolitic in NT. See defect 10007.
371 if ((scp->unixModeBits & 0222) == 0 || (scp->flags & CM_SCACHEFLAG_RO))
373 if ((scp->unixModeBits & 0222) == 0)
374 attrs |= SMB_ATTR_READONLY; /* turn on read-only flag */
379 /* Check if the named file/dir is a dotfile/dotdir */
380 /* String pointed to by lastComp can have leading slashes, but otherwise should have
381 no other patch components */
382 unsigned int smb_IsDotFile(char *lastComp) {
385 /* skip over slashes */
386 for(s=lastComp;*s && (*s == '\\' || *s == '/'); s++);
391 /* nulls, curdir and parent dir doesn't count */
394 if(!*(s + 1)) return 0;
395 if(*(s+1) == '.' && !*(s + 2)) return 0;
401 static int ExtractBits(WORD bits, short start, short len)
408 num = bits << (16 - end);
409 num = num >> ((16 - end) + start);
415 void ShowUnixTime(char *FuncName, long unixTime)
420 smb_LargeSearchTimeFromUnixTime(&ft, unixTime);
422 if (!FileTimeToDosDateTime(&ft, &wDate, &wTime))
423 osi_Log1(smb_logp, "Failed to convert filetime to dos datetime: %d", GetLastError());
425 int day, month, year, sec, min, hour;
428 day = ExtractBits(wDate, 0, 5);
429 month = ExtractBits(wDate, 5, 4);
430 year = ExtractBits(wDate, 9, 7) + 1980;
432 sec = ExtractBits(wTime, 0, 5);
433 min = ExtractBits(wTime, 5, 6);
434 hour = ExtractBits(wTime, 11, 5);
436 sprintf(msg, "%s = %02d-%02d-%04d %02d:%02d:%02d", FuncName, month, day, year, hour, min, sec);
437 osi_Log1(smb_logp, "%s", osi_LogSaveString(smb_logp, msg));
443 /* Determine if we are observing daylight savings time */
444 void GetTimeZoneInfo(BOOL *pDST, LONG *pDstBias, LONG *pBias)
446 TIME_ZONE_INFORMATION timeZoneInformation;
447 SYSTEMTIME utc, local, localDST;
449 /* Get the time zone info. NT uses this to calc if we are in DST. */
450 GetTimeZoneInformation(&timeZoneInformation);
452 /* Return the daylight bias */
453 *pDstBias = timeZoneInformation.DaylightBias;
455 /* Return the bias */
456 *pBias = timeZoneInformation.Bias;
458 /* Now determine if DST is being observed */
460 /* Get the UTC (GMT) time */
463 /* Convert UTC time to local time using the time zone info. If we are
464 observing DST, the calculated local time will include this.
466 SystemTimeToTzSpecificLocalTime(&timeZoneInformation, &utc, &localDST);
468 /* Set the daylight bias to 0. The daylight bias is the amount of change
469 in time that we use for daylight savings time. By setting this to 0
470 we cause there to be no change in time during daylight savings time.
472 timeZoneInformation.DaylightBias = 0;
474 /* Convert the utc time to local time again, but this time without any
475 adjustment for daylight savings time.
477 SystemTimeToTzSpecificLocalTime(&timeZoneInformation, &utc, &local);
479 /* If the two times are different, then it means that the localDST that
480 we calculated includes the daylight bias, and therefore we are
481 observing daylight savings time.
483 *pDST = localDST.wHour != local.wHour;
486 /* Determine if we are observing daylight savings time */
487 void GetTimeZoneInfo(BOOL *pDST, LONG *pDstBias, LONG *pBias)
493 *pDstBias = -60; /* where can this be different? */
499 void CompensateForSmbClientLastWriteTimeBugs(long *pLastWriteTime)
501 BOOL dst; /* Will be TRUE if observing DST */
502 LONG dstBias; /* Offset from local time if observing DST */
503 LONG bias; /* Offset from GMT for local time */
506 * This function will adjust the last write time to compensate
507 * for two bugs in the smb client:
509 * 1) During Daylight Savings Time, the LastWriteTime is ahead
510 * in time by the DaylightBias (ignoring the sign - the
511 * DaylightBias is always stored as a negative number). If
512 * the DaylightBias is -60, then the LastWriteTime will be
513 * ahead by 60 minutes.
515 * 2) If the local time zone is a positive offset from GMT, then
516 * the LastWriteTime will be the correct local time plus the
517 * Bias (ignoring the sign - a positive offset from GMT is
518 * always stored as a negative Bias). If the Bias is -120,
519 * then the LastWriteTime will be ahead by 120 minutes.
521 * These bugs can occur at the same time.
524 GetTimeZoneInfo(&dst, &dstBias, &bias);
526 /* First adjust for DST */
528 *pLastWriteTime -= (-dstBias * 60); /* Convert dstBias to seconds */
530 /* Now adjust for a positive offset from GMT (a negative bias). */
532 *pLastWriteTime -= (-bias * 60); /* Convert bias to seconds */
536 * Calculate the difference (in seconds) between local time and GMT.
537 * This enables us to convert file times to kludge-GMT.
543 struct tm gmt_tm, local_tm;
544 int days, hours, minutes, seconds;
547 gmt_tm = *(gmtime(&t));
548 local_tm = *(localtime(&t));
550 days = local_tm.tm_yday - gmt_tm.tm_yday;
551 hours = 24 * days + local_tm.tm_hour - gmt_tm.tm_hour
553 /* There is a problem with DST immediately after the time change
554 * which may continue to exist until the machine is rebooted
556 - (local_tm.tm_isdst ? 1 : 0)
559 minutes = 60 * hours + local_tm.tm_min - gmt_tm.tm_min;
560 seconds = 60 * minutes + local_tm.tm_sec - gmt_tm.tm_sec;
566 void smb_LargeSearchTimeFromUnixTime(FILETIME *largeTimep, long unixTime)
571 long ersatz_unixTime;
574 * Must use kludge-GMT instead of real GMT.
575 * kludge-GMT is computed by adding time zone difference to localtime.
578 * ltp = gmtime(&unixTime);
580 ersatz_unixTime = unixTime - smb_NowTZ;
581 ltp = localtime(&ersatz_unixTime);
583 /* if we fail, make up something */
586 localJunk.tm_year = 89 - 20;
587 localJunk.tm_mon = 4;
588 localJunk.tm_mday = 12;
589 localJunk.tm_hour = 0;
590 localJunk.tm_min = 0;
591 localJunk.tm_sec = 0;
594 stm.wYear = ltp->tm_year + 1900;
595 stm.wMonth = ltp->tm_mon + 1;
596 stm.wDayOfWeek = ltp->tm_wday;
597 stm.wDay = ltp->tm_mday;
598 stm.wHour = ltp->tm_hour;
599 stm.wMinute = ltp->tm_min;
600 stm.wSecond = ltp->tm_sec;
601 stm.wMilliseconds = 0;
603 SystemTimeToFileTime(&stm, largeTimep);
606 void smb_LargeSearchTimeFromUnixTime(FILETIME *largeTimep, long unixTime)
608 /* unixTime: seconds since 1/1/1970 00:00:00 GMT */
609 /* FILETIME: 100ns intervals since 1/1/1601 00:00:00 ??? */
610 LARGE_INTEGER *ft = (LARGE_INTEGER *) largeTimep;
612 int leap_years = 89; /* leap years betw 1/1/1601 and 1/1/1970 */
614 /* set ft to number of 100ns intervals betw 1/1/1601 and 1/1/1970 GMT */
615 *ft = ConvertLongToLargeInteger(((EPOCH_YEAR-1601) * 365 + leap_years)
617 *ft = LargeIntegerMultiplyByLong(*ft, 60);
618 *ft = LargeIntegerMultiplyByLong(*ft, 10000000);
621 ut = ConvertLongToLargeInteger(unixTime);
622 ut = LargeIntegerMultiplyByLong(ut, 10000000);
623 *ft = LargeIntegerAdd(*ft, ut);
628 void smb_UnixTimeFromLargeSearchTime(long *unixTimep, FILETIME *largeTimep)
634 FileTimeToSystemTime(largeTimep, &stm);
636 lt.tm_year = stm.wYear - 1900;
637 lt.tm_mon = stm.wMonth - 1;
638 lt.tm_wday = stm.wDayOfWeek;
639 lt.tm_mday = stm.wDay;
640 lt.tm_hour = stm.wHour;
641 lt.tm_min = stm.wMinute;
642 lt.tm_sec = stm.wSecond;
645 save_timezone = _timezone;
646 _timezone += smb_NowTZ;
647 *unixTimep = mktime(<);
648 _timezone = save_timezone;
651 void smb_UnixTimeFromLargeSearchTime(long *unixTimep, FILETIME *largeTimep)
653 /* unixTime: seconds since 1/1/1970 00:00:00 GMT */
654 /* FILETIME: 100ns intervals since 1/1/1601 00:00:00 GMT? */
655 LARGE_INTEGER *ft = (LARGE_INTEGER *) largeTimep;
659 /* set to number of 100ns intervals betw 1/1/1601 and 1/1/1970 */
660 a = ConvertLongToLargeInteger(((EPOCH_YEAR-1601) * 365 + leap_years) * 24 * 60);
661 a = LargeIntegerMultiplyByLong(a, 60);
662 a = LargeIntegerMultiplyByLong(a, 10000000);
664 /* subtract it from ft */
665 a = LargeIntegerSubtract(*ft, a);
667 /* divide down to seconds */
668 *unixTimep = LargeIntegerDivideByLong(a, 10000000);
672 void smb_SearchTimeFromUnixTime(long *dosTimep, long unixTime)
679 ltp = localtime((time_t*) &unixTime);
681 /* if we fail, make up something */
684 localJunk.tm_year = 89 - 20;
685 localJunk.tm_mon = 4;
686 localJunk.tm_mday = 12;
687 localJunk.tm_hour = 0;
688 localJunk.tm_min = 0;
689 localJunk.tm_sec = 0;
692 dosDate = ((ltp->tm_year-80)<<9) | ((ltp->tm_mon+1) << 5) | (ltp->tm_mday);
693 dosTime = (ltp->tm_hour<<11) | (ltp->tm_min << 5) | (ltp->tm_sec / 2);
694 *dosTimep = (dosDate<<16) | dosTime;
697 void smb_UnixTimeFromSearchTime(long *unixTimep, long searchTime)
699 unsigned short dosDate;
700 unsigned short dosTime;
703 dosDate = searchTime & 0xffff;
704 dosTime = (searchTime >> 16) & 0xffff;
706 localTm.tm_year = 80 + ((dosDate>>9) & 0x3f);
707 localTm.tm_mon = ((dosDate >> 5) & 0xf) - 1; /* January is 0 in localTm */
708 localTm.tm_mday = (dosDate) & 0x1f;
709 localTm.tm_hour = (dosTime>>11) & 0x1f;
710 localTm.tm_min = (dosTime >> 5) & 0x3f;
711 localTm.tm_sec = (dosTime & 0x1f) * 2;
712 localTm.tm_isdst = -1; /* compute whether DST in effect */
714 *unixTimep = mktime(&localTm);
717 void smb_DosUTimeFromUnixTime(long *dosUTimep, long unixTime)
719 *dosUTimep = unixTime - smb_localZero;
722 void smb_UnixTimeFromDosUTime(long *unixTimep, long dosTime)
725 *unixTimep = dosTime + smb_localZero;
727 /* dosTime seems to be already adjusted for GMT */
728 *unixTimep = dosTime;
732 smb_vc_t *smb_FindVC(unsigned short lsn, int flags, int lana)
736 lock_ObtainWrite(&smb_rctLock);
737 for(vcp = smb_allVCsp; vcp; vcp=vcp->nextp) {
738 if (lsn == vcp->lsn && lana == vcp->lana) {
743 if (!vcp && (flags & SMB_FLAG_CREATE)) {
744 vcp = malloc(sizeof(*vcp));
745 memset(vcp, 0, sizeof(*vcp));
746 vcp->vcID = numVCs++;
750 vcp->uidCounter = 1; /* UID 0 is reserved for blank user */
751 vcp->nextp = smb_allVCsp;
753 lock_InitializeMutex(&vcp->mx, "vc_t mutex");
758 if (smb_authType == SMB_AUTH_NTLM || smb_authType == SMB_AUTH_EXTENDED) {
759 /* We must obtain a challenge for extended auth
760 * in case the client negotiates smb v3
763 MSV1_0_LM20_CHALLENGE_REQUEST lsaReq;
764 PMSV1_0_LM20_CHALLENGE_RESPONSE lsaResp;
767 lsaReq.MessageType = MsV1_0Lm20ChallengeRequest;
769 nts = LsaCallAuthenticationPackage( smb_lsaHandle,
776 osi_assert(nts == STATUS_SUCCESS); /* this had better work! */
778 memcpy(vcp->encKey, lsaResp->ChallengeToClient, MSV1_0_CHALLENGE_LENGTH);
779 LsaFreeReturnBuffer(lsaResp);
782 memset(vcp->encKey, 0, MSV1_0_CHALLENGE_LENGTH);
784 lock_ReleaseWrite(&smb_rctLock);
788 int smb_IsStarMask(char *maskp)
793 for(i=0; i<11; i++) {
795 if (tc == '?' || tc == '*' || tc == '>') return 1;
800 void smb_ReleaseVC(smb_vc_t *vcp)
802 lock_ObtainWrite(&smb_rctLock);
803 osi_assert(vcp->refCount-- > 0);
804 lock_ReleaseWrite(&smb_rctLock);
807 void smb_HoldVC(smb_vc_t *vcp)
809 lock_ObtainWrite(&smb_rctLock);
811 lock_ReleaseWrite(&smb_rctLock);
814 smb_tid_t *smb_FindTID(smb_vc_t *vcp, unsigned short tid, int flags)
818 lock_ObtainWrite(&smb_rctLock);
819 for(tidp = vcp->tidsp; tidp; tidp = tidp->nextp) {
820 if (tid == tidp->tid) {
825 if (!tidp && (flags & SMB_FLAG_CREATE)) {
826 tidp = malloc(sizeof(*tidp));
827 memset(tidp, 0, sizeof(*tidp));
828 tidp->nextp = vcp->tidsp;
833 lock_InitializeMutex(&tidp->mx, "tid_t mutex");
836 lock_ReleaseWrite(&smb_rctLock);
840 void smb_ReleaseTID(smb_tid_t *tidp)
849 lock_ObtainWrite(&smb_rctLock);
850 osi_assert(tidp->refCount-- > 0);
851 if (tidp->refCount == 0 && (tidp->flags & SMB_TIDFLAG_DELETE)) {
852 ltpp = &tidp->vcp->tidsp;
853 for(tp = *ltpp; tp; ltpp = &tp->nextp, tp = *ltpp) {
854 if (tp == tidp) break;
856 osi_assert(tp != NULL);
858 lock_FinalizeMutex(&tidp->mx);
859 userp = tidp->userp; /* remember to drop ref later */
862 lock_ReleaseWrite(&smb_rctLock);
864 cm_ReleaseUser(userp);
871 smb_user_t *smb_FindUID(smb_vc_t *vcp, unsigned short uid, int flags)
873 smb_user_t *uidp = NULL;
875 lock_ObtainWrite(&smb_rctLock);
876 for(uidp = vcp->usersp; uidp; uidp = uidp->nextp) {
877 if (uid == uidp->userID) {
879 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 : "");
883 if (!uidp && (flags & SMB_FLAG_CREATE)) {
884 uidp = malloc(sizeof(*uidp));
885 memset(uidp, 0, sizeof(*uidp));
886 uidp->nextp = vcp->usersp;
891 lock_InitializeMutex(&uidp->mx, "user_t mutex");
893 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 : ""));
895 lock_ReleaseWrite(&smb_rctLock);
899 smb_username_t *smb_FindUserByName(char *usern, char *machine, int flags)
901 smb_username_t *unp= NULL;
903 lock_ObtainWrite(&smb_rctLock);
904 for(unp = usernamesp; unp; unp = unp->nextp) {
905 if (stricmp(unp->name, usern) == 0 &&
906 stricmp(unp->machine, machine) == 0) {
911 if (!unp && (flags & SMB_FLAG_CREATE)) {
912 unp = malloc(sizeof(*unp));
913 memset(unp, 0, sizeof(*unp));
915 unp->nextp = usernamesp;
916 unp->name = strdup(usern);
917 unp->machine = strdup(machine);
919 lock_InitializeMutex(&unp->mx, "username_t mutex");
921 lock_ReleaseWrite(&smb_rctLock);
925 smb_user_t *smb_FindUserByNameThisSession(smb_vc_t *vcp, char *usern)
927 smb_user_t *uidp= NULL;
929 lock_ObtainWrite(&smb_rctLock);
930 for(uidp = vcp->usersp; uidp; uidp = uidp->nextp) {
933 if (stricmp(uidp->unp->name, usern) == 0) {
935 osi_LogEvent("AFS smb_FindUserByNameThisSession",NULL,"VCP[%x] uid[%d] match-name[%s]",(int)vcp,uidp->userID,usern);
940 lock_ReleaseWrite(&smb_rctLock);
943 void smb_ReleaseUID(smb_user_t *uidp)
952 lock_ObtainWrite(&smb_rctLock);
953 osi_assert(uidp->refCount-- > 0);
954 if (uidp->refCount == 0 && (uidp->flags & SMB_USERFLAG_DELETE)) {
955 lupp = &uidp->vcp->usersp;
956 for(up = *lupp; up; lupp = &up->nextp, up = *lupp) {
957 if (up == uidp) break;
959 osi_assert(up != NULL);
961 lock_FinalizeMutex(&uidp->mx);
963 userp = uidp->unp->userp; /* remember to drop ref later */
964 uidp->unp->userp = NULL;
969 lock_ReleaseWrite(&smb_rctLock);
971 cm_ReleaseUserVCRef(userp);
972 cm_ReleaseUser(userp);
979 /* retrieve a held reference to a user structure corresponding to an incoming
981 * corresponding release function is cm_ReleaseUser.
983 cm_user_t *smb_GetUser(smb_vc_t *vcp, smb_packet_t *inp)
989 smbp = (smb_t *) inp;
990 uidp = smb_FindUID(vcp, smbp->uid, 0);
991 if ((!uidp) || (!uidp->unp))
994 lock_ObtainMutex(&uidp->mx);
995 up = uidp->unp->userp;
997 lock_ReleaseMutex(&uidp->mx);
999 smb_ReleaseUID(uidp);
1005 * Return a pointer to a pathname extracted from a TID structure. The
1006 * TID structure is not held; assume it won't go away.
1008 char *smb_GetTIDPath(smb_vc_t *vcp, unsigned short tid)
1013 tidp = smb_FindTID(vcp, tid, 0);
1016 tpath = tidp->pathname;
1017 smb_ReleaseTID(tidp);
1021 /* check to see if we have a chained fid, that is, a fid that comes from an
1022 * OpenAndX message that ran earlier in this packet. In this case, the fid
1023 * field in a read, for example, request, isn't set, since the value is
1024 * supposed to be inherited from the openAndX call.
1026 int smb_ChainFID(int fid, smb_packet_t *inp)
1028 if (inp->fid == 0 || inp->inCount == 0)
1034 /* are we a priv'd user? What does this mean on NT? */
1035 int smb_SUser(cm_user_t *userp)
1040 /* find a file ID. If we pass in 0 we select an used File ID.
1041 * If the SMB_FLAG_CREATE flag is set, we allocate a new
1042 * smb_fid_t data structure if desired File ID cannot be found.
1044 smb_fid_t *smb_FindFID(smb_vc_t *vcp, unsigned short fid, int flags)
1049 if (fid == 0 && !(flags & SMB_FLAG_CREATE))
1052 lock_ObtainWrite(&smb_rctLock);
1053 /* figure out if we need to allocate a new file ID */
1056 fid = vcp->fidCounter;
1060 for(fidp = vcp->fidsp; fidp; fidp = (smb_fid_t *) osi_QNext(&fidp->q)) {
1061 if (fid == fidp->fid) {
1072 if (!fidp && (flags & SMB_FLAG_CREATE)) {
1073 char eventName[MAX_PATH];
1075 sprintf(eventName,"fid_t event vcp=%d fid=%d", vcp->vcID, fid);
1076 event = thrd_CreateEvent(NULL, FALSE, TRUE, eventName);
1077 if ( GetLastError() == ERROR_ALREADY_EXISTS ) {
1078 afsi_log("Event Object Already Exists: %s", eventName);
1079 thrd_CloseHandle(event);
1086 fidp = malloc(sizeof(*fidp));
1087 memset(fidp, 0, sizeof(*fidp));
1088 osi_QAdd((osi_queue_t **)&vcp->fidsp, &fidp->q);
1092 lock_InitializeMutex(&fidp->mx, "fid_t mutex");
1094 fidp->curr_chunk = fidp->prev_chunk = -2;
1095 fidp->raw_write_event = event;
1097 vcp->fidCounter = fid+1;
1098 if (vcp->fidCounter == 0)
1099 vcp->fidCounter = 1;
1102 lock_ReleaseWrite(&smb_rctLock);
1106 void smb_ReleaseFID(smb_fid_t *fidp)
1109 smb_vc_t *vcp = NULL;
1110 smb_ioctl_t *ioctlp;
1116 lock_ObtainWrite(&smb_rctLock);
1117 osi_assert(fidp->refCount-- > 0);
1118 if (fidp->refCount == 0 && (fidp->flags & SMB_FID_DELETE)) {
1120 if (!(fidp->flags & SMB_FID_IOCTL))
1122 osi_QRemove((osi_queue_t **) &vcp->fidsp, &fidp->q);
1123 thrd_CloseHandle(fidp->raw_write_event);
1125 /* and see if there is ioctl stuff to free */
1126 ioctlp = fidp->ioctlp;
1128 if (ioctlp->prefix) cm_FreeSpace(ioctlp->prefix);
1129 if (ioctlp->inAllocp) free(ioctlp->inAllocp);
1130 if (ioctlp->outAllocp) free(ioctlp->outAllocp);
1136 /* do not call smb_ReleaseVC() because we already have the lock */
1139 lock_ReleaseWrite(&smb_rctLock);
1141 /* now release the scache structure */
1143 cm_ReleaseSCache(scp);
1147 * Case-insensitive search for one string in another;
1148 * used to find variable names in submount pathnames.
1150 static char *smb_stristr(char *str1, char *str2)
1154 for (cursor = str1; *cursor; cursor++)
1155 if (stricmp(cursor, str2) == 0)
1162 * Substitute a variable value for its name in a submount pathname. Variable
1163 * name has been identified by smb_stristr() and is in substr. Variable name
1164 * length (plus one) is in substr_size. Variable value is in newstr.
1166 static void smb_subst(char *str1, char *substr, unsigned int substr_size,
1171 strcpy(temp, substr + substr_size - 1);
1172 strcpy(substr, newstr);
1176 char VNUserName[] = "%USERNAME%";
1177 char VNLCUserName[] = "%LCUSERNAME%";
1178 char VNComputerName[] = "%COMPUTERNAME%";
1179 char VNLCComputerName[] = "%LCCOMPUTERNAME%";
1181 /* List available shares */
1182 int smb_ListShares()
1186 char shareBuf[4096];
1194 /*strcpy(shareNameList[num_shares], "all");
1195 strcpy(pathNameList[num_shares++], "/afs");*/
1196 fprintf(stderr, "The following shares are available:\n");
1197 fprintf(stderr, "Share Name (AFS Path)\n");
1198 fprintf(stderr, "---------------------\n");
1199 fprintf(stderr, "\\\\%s\\%-16s (%s)\n", smb_localNamep, "ALL", cm_mountRoot);
1202 code = GetWindowsDirectory(sbmtpath, sizeof(sbmtpath));
1203 if (code == 0 || code > sizeof(sbmtpath)) return -1;
1205 strcpy(sbmtpath, cm_confDir);
1207 strcat(sbmtpath, "/afsdsbmt.ini");
1208 len = GetPrivateProfileString("AFS Submounts", NULL, NULL,
1209 shareBuf, sizeof(shareBuf),
1215 this_share = shareBuf;
1219 /*strcpy(shareNameList[num_shares], this_share);*/
1220 len = GetPrivateProfileString("AFS Submounts", this_share,
1227 if (strncmp(p, cm_mountRoot, strlen(cm_mountRoot)) != 0)
1230 if (*p == '\\') *p = '/'; /* change to / */
1234 fprintf(stderr, "\\\\%s\\%-16s (%s%s)\n",
1235 smb_localNamep, this_share, (print_afs ? cm_mountRoot : "\0"),
1238 while (*this_share != 0) this_share++; /* find next NUL */
1239 this_share++; /* skip past the NUL */
1240 } while (*this_share != 0); /* stop at final NUL */
1245 /* find a shareName in the table of submounts */
1246 int smb_FindShare(smb_vc_t *vcp, smb_user_t *uidp, char *shareName,
1250 char pathName[1024];
1254 char sbmtpath[MAX_PATH];
1258 DWORD allSubmount = 1;
1260 if (strcmp(shareName, "IPC$") == 0) {
1265 /* if allSubmounts == 0, only return the //mountRoot/all share
1266 * if in fact it has been been created in the subMounts table.
1267 * This is to allow sites that want to restrict access to the
1270 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSConfigKeyName,
1271 0, KEY_QUERY_VALUE, &parmKey);
1272 if (code == ERROR_SUCCESS) {
1273 len = sizeof(allSubmount);
1274 code = RegQueryValueEx(parmKey, "AllSubmount", NULL, NULL,
1275 (BYTE *) &allSubmount, &len);
1276 if (code != ERROR_SUCCESS) {
1279 RegCloseKey (parmKey);
1282 if (allSubmount && _stricmp(shareName, "all") == 0) {
1287 /* In case, the all share is disabled we need to still be able
1288 * to handle ioctl requests
1290 if (_stricmp(shareName, "ioctl$") == 0) {
1291 *pathNamep = strdup("/.__ioctl__");
1296 strcpy(sbmtpath, "afsdsbmt.ini");
1298 strcpy(sbmtpath, cm_confDir);
1299 strcat(sbmtpath, "/afsdsbmt.ini");
1301 len = GetPrivateProfileString("AFS Submounts", shareName, "",
1302 pathName, sizeof(pathName), sbmtpath);
1303 if (len != 0 && len != sizeof(pathName) - 1) {
1304 /* We can accept either unix or PC style AFS pathnames. Convert
1305 * Unix-style to PC style here for internal use.
1308 if (strncmp(p, cm_mountRoot, strlen(cm_mountRoot)) == 0)
1309 p += strlen(cm_mountRoot); /* skip mount path */
1312 if (*q == '/') *q = '\\'; /* change to \ */
1318 if (var = smb_stristr(p, VNUserName)) {
1319 if (uidp && uidp->unp)
1320 smb_subst(p, var, sizeof(VNUserName),uidp->unp->name);
1322 smb_subst(p, var, sizeof(VNUserName)," ");
1324 else if (var = smb_stristr(p, VNLCUserName))
1326 if (uidp && uidp->unp)
1327 strcpy(temp, uidp->unp->name);
1331 smb_subst(p, var, sizeof(VNLCUserName), temp);
1333 else if (var = smb_stristr(p, VNComputerName))
1335 sizeTemp = sizeof(temp);
1336 GetComputerName((LPTSTR)temp, &sizeTemp);
1337 smb_subst(p, var, sizeof(VNComputerName), temp);
1339 else if (var = smb_stristr(p, VNLCComputerName))
1341 sizeTemp = sizeof(temp);
1342 GetComputerName((LPTSTR)temp, &sizeTemp);
1344 smb_subst(p, var, sizeof(VNLCComputerName), temp);
1349 *pathNamep = strdup(p);
1352 else /* create \\<netbiosName>\<cellname> */
1354 char * p = shareName;
1361 /* Get the full name for this cell */
1362 code = cm_SearchCellFile(p, temp, 0, 0);
1363 #ifdef AFS_AFSDB_ENV
1364 if (code && cm_dnsEnabled) {
1366 code = cm_SearchCellByDNS(p, temp, &ttl, 0, 0);
1369 /* construct the path */
1371 sprintf(pathName,rw ? "/.%s/" : "/%s/",temp);
1372 *pathNamep = strdup(strlwr(pathName));
1381 /* Client-side offline caching policy types */
1382 #define CSC_POLICY_MANUAL 0
1383 #define CSC_POLICY_DOCUMENTS 1
1384 #define CSC_POLICY_PROGRAMS 2
1385 #define CSC_POLICY_DISABLE 3
1387 int smb_FindShareCSCPolicy(char *shareName)
1393 int retval = CSC_POLICY_MANUAL;
1395 RegCreateKeyEx( HKEY_LOCAL_MACHINE,
1396 "SOFTWARE\\OpenAFS\\Client\\CSCPolicy",
1399 REG_OPTION_NON_VOLATILE,
1405 len = sizeof(policy);
1406 if ( RegQueryValueEx( hkCSCPolicy, shareName, 0, &dwType, policy, &len ) ||
1408 retval = CSC_POLICY_MANUAL;
1410 else if (stricmp(policy, "documents") == 0)
1412 retval = CSC_POLICY_DOCUMENTS;
1414 else if (stricmp(policy, "programs") == 0)
1416 retval = CSC_POLICY_PROGRAMS;
1418 else if (stricmp(policy, "disable") == 0)
1420 retval = CSC_POLICY_DISABLE;
1423 RegCloseKey(hkCSCPolicy);
1427 /* find a dir search structure by cookie value, and return it held.
1428 * Must be called with smb_globalLock held.
1430 smb_dirSearch_t *smb_FindDirSearchNL(long cookie)
1432 smb_dirSearch_t *dsp;
1434 for(dsp = smb_firstDirSearchp; dsp; dsp = (smb_dirSearch_t *) osi_QNext(&dsp->q)) {
1435 if (dsp->cookie == cookie) {
1436 if (dsp != smb_firstDirSearchp) {
1437 /* move to head of LRU queue, too, if we're not already there */
1438 if (smb_lastDirSearchp == (smb_dirSearch_t *) &dsp->q)
1439 smb_lastDirSearchp = (smb_dirSearch_t *)
1441 osi_QRemove((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1442 osi_QAdd((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1443 if (!smb_lastDirSearchp)
1444 smb_lastDirSearchp = (smb_dirSearch_t *) &dsp->q;
1453 void smb_DeleteDirSearch(smb_dirSearch_t *dsp)
1455 lock_ObtainWrite(&smb_globalLock);
1456 dsp->flags |= SMB_DIRSEARCH_DELETE;
1457 lock_ReleaseWrite(&smb_globalLock);
1458 lock_ObtainMutex(&dsp->mx);
1459 if(dsp->scp != NULL) {
1460 lock_ObtainMutex(&dsp->scp->mx);
1461 if (dsp->flags & SMB_DIRSEARCH_BULKST) {
1462 dsp->flags &= ~SMB_DIRSEARCH_BULKST;
1463 dsp->scp->flags &= ~CM_SCACHEFLAG_BULKSTATTING;
1464 dsp->scp->bulkStatProgress = hones;
1466 lock_ReleaseMutex(&dsp->scp->mx);
1468 lock_ReleaseMutex(&dsp->mx);
1471 void smb_ReleaseDirSearch(smb_dirSearch_t *dsp)
1477 lock_ObtainWrite(&smb_globalLock);
1478 osi_assert(dsp->refCount-- > 0);
1479 if (dsp->refCount == 0 && (dsp->flags & SMB_DIRSEARCH_DELETE)) {
1480 if (&dsp->q == (osi_queue_t *) smb_lastDirSearchp)
1481 smb_lastDirSearchp = (smb_dirSearch_t *) osi_QPrev(&smb_lastDirSearchp->q);
1482 osi_QRemove((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1483 lock_FinalizeMutex(&dsp->mx);
1487 lock_ReleaseWrite(&smb_globalLock);
1489 /* do this now to avoid spurious locking hierarchy creation */
1490 if (scp) cm_ReleaseSCache(scp);
1493 /* find a dir search structure by cookie value, and return it held */
1494 smb_dirSearch_t *smb_FindDirSearch(long cookie)
1496 smb_dirSearch_t *dsp;
1498 lock_ObtainWrite(&smb_globalLock);
1499 dsp = smb_FindDirSearchNL(cookie);
1500 lock_ReleaseWrite(&smb_globalLock);
1504 /* GC some dir search entries, in the address space expected by the specific protocol.
1505 * Must be called with smb_globalLock held; release the lock temporarily.
1507 #define SMB_DIRSEARCH_GCMAX 10 /* how many at once */
1508 void smb_GCDirSearches(int isV3)
1510 smb_dirSearch_t *prevp;
1511 smb_dirSearch_t *tp;
1512 smb_dirSearch_t *victimsp[SMB_DIRSEARCH_GCMAX];
1516 victimCount = 0; /* how many have we got so far */
1517 for(tp = smb_lastDirSearchp; tp; tp=prevp) {
1518 /* we'll move tp from queue, so
1521 prevp = (smb_dirSearch_t *) osi_QPrev(&tp->q);
1522 /* if no one is using this guy, and we're either in the new protocol,
1523 * or we're in the old one and this is a small enough ID to be useful
1524 * to the old protocol, GC this guy.
1526 if (tp->refCount == 0 && (isV3 || tp->cookie <= 255)) {
1527 /* hold and delete */
1528 tp->flags |= SMB_DIRSEARCH_DELETE;
1529 victimsp[victimCount++] = tp;
1533 /* don't do more than this */
1534 if (victimCount >= SMB_DIRSEARCH_GCMAX) break;
1537 /* now release them */
1538 lock_ReleaseWrite(&smb_globalLock);
1539 for(i = 0; i < victimCount; i++) {
1540 smb_ReleaseDirSearch(victimsp[i]);
1542 lock_ObtainWrite(&smb_globalLock);
1545 /* function for allocating a dir search entry. We need these to remember enough context
1546 * since we don't get passed the path from call to call during a directory search.
1548 * Returns a held dir search structure, and bumps the reference count on the vnode,
1549 * since it saves a pointer to the vnode.
1551 smb_dirSearch_t *smb_NewDirSearch(int isV3)
1553 smb_dirSearch_t *dsp;
1557 lock_ObtainWrite(&smb_globalLock);
1560 /* what's the biggest ID allowed in this version of the protocol */
1561 if (isV3) maxAllowed = 65535;
1562 else maxAllowed = 255;
1565 /* twice so we have enough tries to find guys we GC after one pass;
1566 * 10 extra is just in case I mis-counted.
1568 if (++counter > 2*maxAllowed+10) osi_panic("afsd: dir search cookie leak",
1569 __FILE__, __LINE__);
1570 if (smb_dirSearchCounter > maxAllowed) {
1571 smb_dirSearchCounter = 1;
1572 smb_GCDirSearches(isV3); /* GC some (drops global lock) */
1574 dsp = smb_FindDirSearchNL(smb_dirSearchCounter);
1576 /* don't need to watch for refcount zero and deleted, since
1577 * we haven't dropped the global lock.
1580 ++smb_dirSearchCounter;
1584 dsp = malloc(sizeof(*dsp));
1585 memset(dsp, 0, sizeof(*dsp));
1586 osi_QAdd((osi_queue_t **) &smb_firstDirSearchp, &dsp->q);
1587 if (!smb_lastDirSearchp) smb_lastDirSearchp = (smb_dirSearch_t *) &dsp->q;
1588 dsp->cookie = smb_dirSearchCounter;
1589 ++smb_dirSearchCounter;
1591 lock_InitializeMutex(&dsp->mx, "cm_dirSearch_t");
1592 dsp->lastTime = osi_Time();
1595 lock_ReleaseWrite(&smb_globalLock);
1599 static smb_packet_t *GetPacket(void)
1603 unsigned int npar, seg, tb_sel;
1606 lock_ObtainWrite(&smb_globalLock);
1607 tbp = smb_packetFreeListp;
1609 smb_packetFreeListp = tbp->nextp;
1610 lock_ReleaseWrite(&smb_globalLock);
1613 tbp = calloc(65540,1);
1615 tbp = malloc(sizeof(smb_packet_t));
1617 tbp->magic = SMB_PACKETMAGIC;
1620 tbp->resumeCode = 0;
1626 tbp->ncb_length = 0;
1631 npar = SMB_PACKETSIZE >> 4; /* number of paragraphs */
1634 __dpmi_allocate_dos_memory(npar, &tb_sel); /* DOS segment */
1636 afsi_log("Cannot allocate %d paragraphs of DOS memory",
1638 osi_panic("",__FILE__,__LINE__);
1641 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X",
1646 tbp->dos_pkt = (seg * 16) + 0; /* DOS physical address */
1647 tbp->dos_pkt_sel = tb_sel;
1650 osi_assert(tbp->magic == SMB_PACKETMAGIC);
1655 smb_packet_t *smb_CopyPacket(smb_packet_t *pkt)
1659 memcpy(tbp, pkt, sizeof(smb_packet_t));
1660 tbp->wctp = tbp->data + ((unsigned int)pkt->wctp - (unsigned int)pkt->data);
1664 static NCB *GetNCB(void)
1669 unsigned int npar, seg, tb_sel;
1672 lock_ObtainWrite(&smb_globalLock);
1673 tbp = smb_ncbFreeListp;
1675 smb_ncbFreeListp = tbp->nextp;
1676 lock_ReleaseWrite(&smb_globalLock);
1679 tbp = calloc(sizeof(*tbp),1);
1681 tbp = malloc(sizeof(*tbp));
1682 npar = (sizeof(NCB)+15) >> 4; /* number of paragraphs */
1685 __dpmi_allocate_dos_memory(npar, &tb_sel); /* DOS segment */
1687 afsi_log("Cannot allocate %d paragraphs of DOS mem in GetNCB",
1689 osi_panic("",__FILE__,__LINE__);
1691 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X in GetNCB",
1696 tbp->dos_ncb = (seg * 16) + 0; /* DOS physical address */
1697 tbp->dos_ncb_sel = tb_sel;
1699 tbp->magic = SMB_NCBMAGIC;
1702 osi_assert(tbp->magic == SMB_NCBMAGIC);
1704 memset(&tbp->ncb, 0, sizeof(NCB));
1707 dos_memset(tbp->dos_ncb, 0, sizeof(NCB));
1712 void smb_FreePacket(smb_packet_t *tbp)
1714 osi_assert(tbp->magic == SMB_PACKETMAGIC);
1716 lock_ObtainWrite(&smb_globalLock);
1717 tbp->nextp = smb_packetFreeListp;
1718 smb_packetFreeListp = tbp;
1719 tbp->magic = SMB_PACKETMAGIC;
1722 tbp->resumeCode = 0;
1728 tbp->ncb_length = 0;
1730 lock_ReleaseWrite(&smb_globalLock);
1733 static void FreeNCB(NCB *bufferp)
1737 tbp = (smb_ncb_t *) bufferp;
1738 osi_assert(tbp->magic == SMB_NCBMAGIC);
1740 lock_ObtainWrite(&smb_globalLock);
1741 tbp->nextp = smb_ncbFreeListp;
1742 smb_ncbFreeListp = tbp;
1743 lock_ReleaseWrite(&smb_globalLock);
1746 /* get a ptr to the data part of a packet, and its count */
1747 unsigned char *smb_GetSMBData(smb_packet_t *smbp, int *nbytesp)
1751 unsigned char *afterParmsp;
1753 parmBytes = *smbp->wctp << 1;
1754 afterParmsp = smbp->wctp + parmBytes + 1;
1756 dataBytes = afterParmsp[0] + (afterParmsp[1]<<8);
1757 if (nbytesp) *nbytesp = dataBytes;
1759 /* don't forget to skip the data byte count, since it follows
1760 * the parameters; that's where the "2" comes from below.
1762 return (unsigned char *) (afterParmsp + 2);
1765 /* must set all the returned parameters before playing around with the
1766 * data region, since the data region is located past the end of the
1767 * variable number of parameters.
1769 void smb_SetSMBDataLength(smb_packet_t *smbp, unsigned int dsize)
1771 unsigned char *afterParmsp;
1773 afterParmsp = smbp->wctp + ((*smbp->wctp)<<1) + 1;
1775 *afterParmsp++ = dsize & 0xff;
1776 *afterParmsp = (dsize>>8) & 0xff;
1779 /* return the parm'th parameter in the smbp packet */
1780 unsigned int smb_GetSMBParm(smb_packet_t *smbp, int parm)
1783 unsigned char *parmDatap;
1785 parmCount = *smbp->wctp;
1787 if (parm >= parmCount) {
1792 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
1793 sprintf(s, "Bad SMB param %d out of %d, ncb len %d",
1794 parm, parmCount, smbp->ncb_length);
1796 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1006, NULL,
1797 1, smbp->ncb_length, ptbuf, smbp);
1798 DeregisterEventSource(h);
1802 sprintf(s, "Bad SMB param %d out of %d, ncb len %d",
1803 parm, parmCount, smbp->ncb_length);
1804 osi_Log0(smb_logp, s);
1806 osi_panic(s, __FILE__, __LINE__);
1808 parmDatap = smbp->wctp + (2*parm) + 1;
1810 return parmDatap[0] + (parmDatap[1] << 8);
1813 /* return the parm'th parameter in the smbp packet */
1814 unsigned int smb_GetSMBOffsetParm(smb_packet_t *smbp, int parm, int offset)
1817 unsigned char *parmDatap;
1819 parmCount = *smbp->wctp;
1821 if (parm * 2 + offset >= parmCount * 2) {
1826 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
1827 sprintf(s, "Bad SMB param %d offset %d out of %d, ncb len %d",
1828 parm, offset, parmCount, smbp->ncb_length);
1830 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1006, NULL,
1831 1, smbp->ncb_length, ptbuf, smbp);
1832 DeregisterEventSource(h);
1836 sprintf(s, "Bad SMB param %d offset %d out of %d, "
1838 parm, offset, parmCount, smbp->ncb_length);
1839 osi_Log0(smb_logp, s);
1842 osi_panic(s, __FILE__, __LINE__);
1844 parmDatap = smbp->wctp + (2*parm) + 1 + offset;
1846 return parmDatap[0] + (parmDatap[1] << 8);
1849 void smb_SetSMBParm(smb_packet_t *smbp, int slot, unsigned int parmValue)
1853 /* make sure we have enough slots */
1854 if (*smbp->wctp <= slot) *smbp->wctp = slot+1;
1856 parmDatap = smbp->wctp + 2*slot + 1 + smbp->oddByte;
1857 *parmDatap++ = parmValue & 0xff;
1858 *parmDatap = (parmValue>>8) & 0xff;
1861 void smb_SetSMBParmLong(smb_packet_t *smbp, int slot, unsigned int parmValue)
1865 /* make sure we have enough slots */
1866 if (*smbp->wctp <= slot) *smbp->wctp = slot+2;
1868 parmDatap = smbp->wctp + 2*slot + 1 + smbp->oddByte;
1869 *parmDatap++ = parmValue & 0xff;
1870 *parmDatap++ = (parmValue>>8) & 0xff;
1871 *parmDatap++ = (parmValue>>16) & 0xff;
1872 *parmDatap++ = (parmValue>>24) & 0xff;
1875 void smb_SetSMBParmDouble(smb_packet_t *smbp, int slot, char *parmValuep)
1880 /* make sure we have enough slots */
1881 if (*smbp->wctp <= slot) *smbp->wctp = slot+4;
1883 parmDatap = smbp->wctp + 2*slot + 1 + smbp->oddByte;
1885 *parmDatap++ = *parmValuep++;
1888 void smb_SetSMBParmByte(smb_packet_t *smbp, int slot, unsigned int parmValue)
1892 /* make sure we have enough slots */
1893 if (*smbp->wctp <= slot) {
1894 if (smbp->oddByte) {
1896 *smbp->wctp = slot+1;
1901 parmDatap = smbp->wctp + 2*slot + 1 + (1 - smbp->oddByte);
1902 *parmDatap++ = parmValue & 0xff;
1905 void smb_StripLastComponent(char *outPathp, char **lastComponentp, char *inPathp)
1909 lastSlashp = strrchr(inPathp, '\\');
1911 *lastComponentp = lastSlashp;
1914 if (inPathp == lastSlashp)
1916 *outPathp++ = *inPathp++;
1925 unsigned char *smb_ParseASCIIBlock(unsigned char *inp, char **chainpp)
1930 *chainpp = inp + strlen(inp) + 1; /* skip over null-terminated string */
1935 unsigned char *smb_ParseVblBlock(unsigned char *inp, char **chainpp, int *lengthp)
1941 tlen = inp[0] + (inp[1]<<8);
1942 inp += 2; /* skip length field */
1945 *chainpp = inp + tlen;
1954 /* format a packet as a response */
1955 void smb_FormatResponsePacket(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *op)
1960 outp = (smb_t *) op;
1962 /* zero the basic structure through the smb_wct field, and zero the data
1963 * size field, assuming that wct stays zero; otherwise, you have to
1964 * explicitly set the data size field, too.
1966 inSmbp = (smb_t *) inp;
1967 memset(outp, 0, sizeof(smb_t)+2);
1973 outp->com = inSmbp->com;
1974 outp->tid = inSmbp->tid;
1975 outp->pid = inSmbp->pid;
1976 outp->uid = inSmbp->uid;
1977 outp->mid = inSmbp->mid;
1978 outp->res[0] = inSmbp->res[0];
1979 outp->res[1] = inSmbp->res[1];
1980 op->inCom = inSmbp->com;
1982 outp->reb = 0x80; /* SERVER_RESP */
1983 outp->flg2 = 0x1; /* KNOWS_LONG_NAMES */
1985 /* copy fields in generic packet area */
1986 op->wctp = &outp->wct;
1989 /* send a (probably response) packet; vcp tells us to whom to send it.
1990 * we compute the length by looking at wct and bcc fields.
1992 void smb_SendPacket(smb_vc_t *vcp, smb_packet_t *inp)
2009 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
2012 memset((char *)ncbp, 0, sizeof(NCB));
2014 extra = 2 * (*inp->wctp); /* space used by parms, in bytes */
2015 tp = inp->wctp + 1+ extra; /* points to count of data bytes */
2016 extra += tp[0] + (tp[1]<<8);
2017 extra += ((unsigned int)inp->wctp - (unsigned int)inp->data); /* distance to last wct field */
2018 extra += 3; /* wct and length fields */
2020 ncbp->ncb_length = extra; /* bytes to send */
2021 ncbp->ncb_lsn = (unsigned char) vcp->lsn; /* vc to use */
2022 ncbp->ncb_lana_num = vcp->lana;
2023 ncbp->ncb_command = NCBSEND; /* op means send data */
2025 ncbp->ncb_buffer = (char *) inp;/* packet */
2026 code = Netbios(ncbp);
2028 ncbp->ncb_buffer = inp->dos_pkt;/* packet */
2029 ((smb_ncb_t*)ncbp)->orig_pkt = inp;
2031 /* copy header information from virtual to DOS address space */
2032 dosmemput((char*)inp, SMB_PACKETSIZE, inp->dos_pkt);
2033 code = Netbios(ncbp, dos_ncb);
2037 osi_Log1(smb_logp, "SendPacket failure code %d", code);
2043 void smb_MapNTError(long code, unsigned long *NTStatusp)
2045 unsigned long NTStatus;
2047 /* map CM_ERROR_* errors to NT 32-bit status codes */
2048 /* NT Status codes are listed in ntstatus.h not winerror.h */
2049 if (code == CM_ERROR_NOSUCHCELL) {
2050 NTStatus = 0xC000000FL; /* No such file */
2052 else if (code == CM_ERROR_NOSUCHVOLUME) {
2053 NTStatus = 0xC000000FL; /* No such file */
2055 else if (code == CM_ERROR_TIMEDOUT) {
2056 NTStatus = 0xC00000CFL; /* Sharing Paused */
2058 else if (code == CM_ERROR_RETRY) {
2059 NTStatus = 0xC000022DL; /* Retry */
2061 else if (code == CM_ERROR_NOACCESS) {
2062 NTStatus = 0xC0000022L; /* Access denied */
2064 else if (code == CM_ERROR_READONLY) {
2065 NTStatus = 0xC00000A2L; /* Write protected */
2067 else if (code == CM_ERROR_NOSUCHFILE) {
2068 NTStatus = 0xC000000FL; /* No such file */
2070 else if (code == CM_ERROR_NOSUCHPATH) {
2071 NTStatus = 0xC000003AL; /* Object path not found */
2073 else if (code == CM_ERROR_TOOBIG) {
2074 NTStatus = 0xC000007BL; /* Invalid image format */
2076 else if (code == CM_ERROR_INVAL) {
2077 NTStatus = 0xC000000DL; /* Invalid parameter */
2079 else if (code == CM_ERROR_BADFD) {
2080 NTStatus = 0xC0000008L; /* Invalid handle */
2082 else if (code == CM_ERROR_BADFDOP) {
2083 NTStatus = 0xC0000022L; /* Access denied */
2085 else if (code == CM_ERROR_EXISTS) {
2086 NTStatus = 0xC0000035L; /* Object name collision */
2088 else if (code == CM_ERROR_NOTEMPTY) {
2089 NTStatus = 0xC0000101L; /* Directory not empty */
2091 else if (code == CM_ERROR_CROSSDEVLINK) {
2092 NTStatus = 0xC00000D4L; /* Not same device */
2094 else if (code == CM_ERROR_NOTDIR) {
2095 NTStatus = 0xC0000103L; /* Not a directory */
2097 else if (code == CM_ERROR_ISDIR) {
2098 NTStatus = 0xC00000BAL; /* File is a directory */
2100 else if (code == CM_ERROR_BADOP) {
2101 NTStatus = 0xC09820FFL; /* SMB no support */
2103 else if (code == CM_ERROR_BADSHARENAME) {
2104 NTStatus = 0xC00000CCL; /* Bad network name */
2106 else if (code == CM_ERROR_NOIPC) {
2108 NTStatus = 0xC0000022L; /* Access Denied */
2110 NTStatus = 0xC000013DL; /* Remote Resources */
2113 else if (code == CM_ERROR_CLOCKSKEW) {
2114 NTStatus = 0xC0000133L; /* Time difference at DC */
2116 else if (code == CM_ERROR_BADTID) {
2117 NTStatus = 0xC0982005L; /* SMB bad TID */
2119 else if (code == CM_ERROR_USESTD) {
2120 NTStatus = 0xC09820FBL; /* SMB use standard */
2122 else if (code == CM_ERROR_QUOTA) {
2123 NTStatus = 0xC0000044L; /* Quota exceeded */
2125 else if (code == CM_ERROR_SPACE) {
2126 NTStatus = 0xC000007FL; /* Disk full */
2128 else if (code == CM_ERROR_ATSYS) {
2129 NTStatus = 0xC0000033L; /* Object name invalid */
2131 else if (code == CM_ERROR_BADNTFILENAME) {
2132 NTStatus = 0xC0000033L; /* Object name invalid */
2134 else if (code == CM_ERROR_WOULDBLOCK) {
2135 NTStatus = 0xC0000055L; /* Lock not granted */
2137 else if (code == CM_ERROR_PARTIALWRITE) {
2138 NTStatus = 0xC000007FL; /* Disk full */
2140 else if (code == CM_ERROR_BUFFERTOOSMALL) {
2141 NTStatus = 0xC0000023L; /* Buffer too small */
2143 else if (code == CM_ERROR_AMBIGUOUS_FILENAME) {
2144 NTStatus = 0xC0000035L; /* Object name collision */
2146 else if (code == CM_ERROR_BADPASSWORD) {
2147 NTStatus = 0xC000006DL; /* unknown username or bad password */
2149 else if (code == CM_ERROR_BADLOGONTYPE) {
2150 NTStatus = 0xC000015BL; /* logon type not granted */
2152 else if (code == CM_ERROR_GSSCONTINUE) {
2153 NTStatus = 0xC0000016L; /* more processing required */
2156 NTStatus = 0xC0982001L; /* SMB non-specific error */
2159 *NTStatusp = NTStatus;
2160 osi_Log2(smb_logp, "SMB SEND code %x as NT %x", code, NTStatus);
2163 void smb_MapCoreError(long code, smb_vc_t *vcp, unsigned short *scodep,
2164 unsigned char *classp)
2166 unsigned char class;
2167 unsigned short error;
2169 /* map CM_ERROR_* errors to SMB errors */
2170 if (code == CM_ERROR_NOSUCHCELL) {
2172 error = 3; /* bad path */
2174 else if (code == CM_ERROR_NOSUCHVOLUME) {
2176 error = 3; /* bad path */
2178 else if (code == CM_ERROR_TIMEDOUT) {
2180 error = 81; /* server is paused */
2182 else if (code == CM_ERROR_RETRY) {
2183 class = 2; /* shouldn't happen */
2186 else if (code == CM_ERROR_NOACCESS) {
2188 error = 4; /* bad access */
2190 else if (code == CM_ERROR_READONLY) {
2192 error = 19; /* read only */
2194 else if (code == CM_ERROR_NOSUCHFILE) {
2196 error = 2; /* ENOENT! */
2198 else if (code == CM_ERROR_NOSUCHPATH) {
2200 error = 3; /* Bad path */
2202 else if (code == CM_ERROR_TOOBIG) {
2204 error = 11; /* bad format */
2206 else if (code == CM_ERROR_INVAL) {
2207 class = 2; /* server non-specific error code */
2210 else if (code == CM_ERROR_BADFD) {
2212 error = 6; /* invalid file handle */
2214 else if (code == CM_ERROR_BADFDOP) {
2215 class = 1; /* invalid op on FD */
2218 else if (code == CM_ERROR_EXISTS) {
2220 error = 80; /* file already exists */
2222 else if (code == CM_ERROR_NOTEMPTY) {
2224 error = 5; /* delete directory not empty */
2226 else if (code == CM_ERROR_CROSSDEVLINK) {
2228 error = 17; /* EXDEV */
2230 else if (code == CM_ERROR_NOTDIR) {
2231 class = 1; /* bad path */
2234 else if (code == CM_ERROR_ISDIR) {
2235 class = 1; /* access denied; DOS doesn't have a good match */
2238 else if (code == CM_ERROR_BADOP) {
2242 else if (code == CM_ERROR_BADSHARENAME) {
2246 else if (code == CM_ERROR_NOIPC) {
2248 error = 4; /* bad access */
2250 else if (code == CM_ERROR_CLOCKSKEW) {
2251 class = 1; /* invalid function */
2254 else if (code == CM_ERROR_BADTID) {
2258 else if (code == CM_ERROR_USESTD) {
2262 else if (code == CM_ERROR_REMOTECONN) {
2266 else if (code == CM_ERROR_QUOTA) {
2267 if (vcp->flags & SMB_VCFLAG_USEV3) {
2269 error = 39; /* disk full */
2273 error = 5; /* access denied */
2276 else if (code == CM_ERROR_SPACE) {
2277 if (vcp->flags & SMB_VCFLAG_USEV3) {
2279 error = 39; /* disk full */
2283 error = 5; /* access denied */
2286 else if (code == CM_ERROR_PARTIALWRITE) {
2288 error = 39; /* disk full */
2290 else if (code == CM_ERROR_ATSYS) {
2292 error = 2; /* ENOENT */
2294 else if (code == CM_ERROR_WOULDBLOCK) {
2296 error = 33; /* lock conflict */
2298 else if (code == CM_ERROR_NOFILES) {
2300 error = 18; /* no files in search */
2302 else if (code == CM_ERROR_RENAME_IDENTICAL) {
2304 error = 183; /* Samba uses this */
2306 else if (code == CM_ERROR_BADPASSWORD || code == CM_ERROR_BADLOGONTYPE) {
2307 /* we don't have a good way of reporting CM_ERROR_BADLOGONTYPE */
2309 error = 2; /* bad password */
2318 osi_Log3(smb_logp, "SMB SEND code %x as SMB %d: %d", code, class, error);
2321 long smb_SendCoreBadOp(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2323 return CM_ERROR_BADOP;
2326 long smb_ReceiveCoreEcho(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2328 unsigned short EchoCount, i;
2329 char *data, *outdata;
2332 EchoCount = (unsigned short) smb_GetSMBParm(inp, 0);
2334 for (i=1; i<=EchoCount; i++) {
2335 data = smb_GetSMBData(inp, &dataSize);
2336 smb_SetSMBParm(outp, 0, i);
2337 smb_SetSMBDataLength(outp, dataSize);
2338 outdata = smb_GetSMBData(outp, NULL);
2339 memcpy(outdata, data, dataSize);
2340 smb_SendPacket(vcp, outp);
2346 long smb_ReceiveCoreReadRaw(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2349 long count, minCount, finalCount;
2353 cm_user_t *userp = NULL;
2357 char *rawBuf = NULL;
2359 dos_ptr rawBuf = NULL;
2366 fd = smb_GetSMBParm(inp, 0);
2367 count = smb_GetSMBParm(inp, 3);
2368 minCount = smb_GetSMBParm(inp, 4);
2369 offset.HighPart = 0; /* too bad */
2370 offset.LowPart = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
2372 osi_Log3(smb_logp, "smb_ReceieveCoreReadRaw fd %d, off 0x%x, size 0x%x",
2373 fd, offset.LowPart, count);
2375 fidp = smb_FindFID(vcp, fd, 0);
2379 lock_ObtainMutex(&smb_RawBufLock);
2381 /* Get a raw buf, from head of list */
2382 rawBuf = smb_RawBufs;
2384 smb_RawBufs = *(char **)smb_RawBufs;
2386 smb_RawBufs = _farpeekl(_dos_ds, smb_RawBufs);
2389 lock_ReleaseMutex(&smb_RawBufLock);
2393 if (fidp->flags & SMB_FID_IOCTL)
2396 rc = smb_IoctlReadRaw(fidp, vcp, inp, outp);
2398 rc = smb_IoctlReadRaw(fidp, vcp, inp, outp, rawBuf);
2401 /* Give back raw buffer */
2402 lock_ObtainMutex(&smb_RawBufLock);
2404 *((char **) rawBuf) = smb_RawBufs;
2406 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
2409 smb_RawBufs = rawBuf;
2410 lock_ReleaseMutex(&smb_RawBufLock);
2413 smb_ReleaseFID(fidp);
2417 userp = smb_GetUser(vcp, inp);
2420 code = smb_ReadData(fidp, &offset, count, rawBuf, userp, &finalCount);
2422 /* have to give ReadData flag so it will treat buffer as DOS mem. */
2423 code = smb_ReadData(fidp, &offset, count, (unsigned char *)rawBuf,
2424 userp, &finalCount, TRUE /* rawFlag */);
2431 cm_ReleaseUser(userp);
2434 smb_ReleaseFID(fidp);
2439 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
2441 memset((char *)ncbp, 0, sizeof(NCB));
2443 ncbp->ncb_length = (unsigned short) finalCount;
2444 ncbp->ncb_lsn = (unsigned char) vcp->lsn;
2445 ncbp->ncb_lana_num = vcp->lana;
2446 ncbp->ncb_command = NCBSEND;
2447 ncbp->ncb_buffer = rawBuf;
2450 code = Netbios(ncbp);
2452 code = Netbios(ncbp, dos_ncb);
2455 osi_Log1(smb_logp, "ReadRaw send failure code %d", code);
2458 /* Give back raw buffer */
2459 lock_ObtainMutex(&smb_RawBufLock);
2461 *((char **) rawBuf) = smb_RawBufs;
2463 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
2466 smb_RawBufs = rawBuf;
2467 lock_ReleaseMutex(&smb_RawBufLock);
2473 long smb_ReceiveCoreLockRecord(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2478 long smb_ReceiveCoreUnlockRecord(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2483 long smb_ReceiveNegotiate(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2490 int protoIndex; /* index we're using */
2495 char protocol_array[10][1024]; /* protocol signature of the client */
2496 int caps; /* capabilities */
2499 TIME_ZONE_INFORMATION tzi;
2501 osi_Log1(smb_logp, "SMB receive negotiate; %d + 1 ongoing ops",
2505 DWORD now = GetCurrentTime();
2506 if (now - last_msg_time >= 30000
2507 && now - last_msg_time <= 90000) {
2509 "Setting dead_vcp %x", active_vcp);
2511 smb_ReleaseVC(dead_vcp);
2513 "Previous dead_vcp %x", dead_vcp);
2515 smb_HoldVC(active_vcp);
2516 dead_vcp = active_vcp;
2517 dead_vcp->flags |= SMB_VCFLAG_ALREADYDEAD;
2522 inp->flags |= SMB_PACKETFLAG_PROFILE_UPDATE_OK;
2524 namep = smb_GetSMBData(inp, &dbytes);
2527 coreProtoIndex = -1; /* not found */
2530 while(namex < dbytes) {
2531 osi_Log1(smb_logp, "Protocol %s",
2532 osi_LogSaveString(smb_logp, namep+1));
2533 strcpy(protocol_array[tcounter], namep+1);
2535 /* namep points at the first protocol, or really, a 0x02
2536 * byte preceding the null-terminated ASCII name.
2538 if (strcmp("PC NETWORK PROGRAM 1.0", namep+1) == 0) {
2539 coreProtoIndex = tcounter;
2541 else if (smb_useV3 && strcmp("LM1.2X002", namep+1) == 0) {
2542 v3ProtoIndex = tcounter;
2544 else if (smb_useV3 && strcmp("NT LM 0.12", namep+1) == 0) {
2545 NTProtoIndex = tcounter;
2548 /* compute size of protocol entry */
2549 entryLength = strlen(namep+1);
2550 entryLength += 2; /* 0x02 bytes and null termination */
2552 /* advance over this protocol entry */
2553 namex += entryLength;
2554 namep += entryLength;
2555 tcounter++; /* which proto entry we're looking at */
2557 #ifndef NOMOREFILESFIX
2559 * NOTE: We can determine what OS (NT4.0, W2K, W9X, etc)
2560 * the client is running by reading the protocol signature.
2561 * ie. the order in which it sends us the protocol list.
2563 * Special handling for Windows 2000 clients (defect 11765 )
2564 * <asanka:11Jun03> Proto signature is the same for Win XP. </>
2566 if (tcounter == 6) {
2568 smb_t *ip = (smb_t *) inp;
2569 smb_t *op = (smb_t *) outp;
2571 if ((strcmp("PC NETWORK PROGRAM 1.0", protocol_array[0]) == 0) &&
2572 (strcmp("LANMAN1.0", protocol_array[1]) == 0) &&
2573 (strcmp("Windows for Workgroups 3.1a", protocol_array[2]) == 0) &&
2574 (strcmp("LM1.2X002", protocol_array[3]) == 0) &&
2575 (strcmp("LANMAN2.1", protocol_array[4]) == 0) &&
2576 (strcmp("NT LM 0.12", protocol_array[5]) == 0)) {
2577 isWindows2000 = TRUE;
2578 osi_Log0(smb_logp, "Looks like a Windows 2000 client");
2580 * HACK: for now - just negotiate a lower protocol till we
2581 * figure out which flag/flag2 or some other field
2582 * (capabilities maybe?) to set in order for this to work
2583 * correctly with Windows 2000 clients (defect 11765)
2586 /* Things to try (after looking at tcpdump output could be
2587 * setting flags and flags2 to 0x98 and 0xc853 like this
2588 * op->reb = 0x98; op->flg2 = 0xc853;
2589 * osi_Log2(smb_logp, "Flags:0x%x Flags2:0x%x", ip->reb, ip->flg2);
2593 #endif /* NOMOREFILESFIX */
2595 if (NTProtoIndex != -1) {
2596 protoIndex = NTProtoIndex;
2597 vcp->flags |= (SMB_VCFLAG_USENT | SMB_VCFLAG_USEV3);
2599 else if (v3ProtoIndex != -1) {
2600 protoIndex = v3ProtoIndex;
2601 vcp->flags |= SMB_VCFLAG_USEV3;
2603 else if (coreProtoIndex != -1) {
2604 protoIndex = coreProtoIndex;
2605 vcp->flags |= SMB_VCFLAG_USECORE;
2607 else protoIndex = -1;
2609 if (protoIndex == -1)
2610 return CM_ERROR_INVAL;
2611 else if (NTProtoIndex != -1) {
2612 smb_SetSMBParm(outp, 0, protoIndex);
2613 if (smb_authType != SMB_AUTH_NONE) {
2614 smb_SetSMBParmByte(outp, 1,
2615 NEGOTIATE_SECURITY_USER_LEVEL |
2616 NEGOTIATE_SECURITY_CHALLENGE_RESPONSE); /* user level security, challenge response */
2618 smb_SetSMBParmByte(outp, 1, 0); /* share level auth with plaintext password. */
2620 smb_SetSMBParm(outp, 1, smb_maxMpxRequests); /* max multiplexed requests */
2621 smb_SetSMBParm(outp, 2, smb_maxVCPerServer); /* max VCs per consumer/server connection */
2622 smb_SetSMBParmLong(outp, 3, SMB_PACKETSIZE); /* xmit buffer size */
2623 smb_SetSMBParmLong(outp, 5, SMB_MAXRAWSIZE); /* raw buffer size */
2624 /* The session key is not a well documented field however most clients
2625 * will echo back the session key to the server. Currently we are using
2626 * the same value for all sessions. We should generate a random value
2627 * and store it into the vcp
2629 smb_SetSMBParm(outp, 7, 1); /* next 2: session key */
2630 smb_SetSMBParm(outp, 8, 1);
2632 * Tried changing the capabilities to support for W2K - defect 117695
2633 * Maybe something else needs to be changed here?
2637 smb_SetSMBParmLong(outp, 9, 0x43fd);
2639 smb_SetSMBParmLong(outp, 9, 0x251);
2642 * 32-bit error codes *
2646 caps = NTNEGOTIATE_CAPABILITY_NTSTATUS |
2647 NTNEGOTIATE_CAPABILITY_NTFIND |
2648 NTNEGOTIATE_CAPABILITY_RAWMODE |
2649 NTNEGOTIATE_CAPABILITY_NTSMB;
2651 if ( smb_authType == SMB_AUTH_EXTENDED )
2652 caps |= NTNEGOTIATE_CAPABILITY_EXTENDED_SECURITY;
2654 smb_SetSMBParmLong(outp, 9, caps);
2656 smb_SearchTimeFromUnixTime(&dosTime, unixTime);
2657 smb_SetSMBParmLong(outp, 11, LOWORD(dosTime));/* server time */
2658 smb_SetSMBParmLong(outp, 13, HIWORD(dosTime));/* server date */
2660 GetTimeZoneInformation(&tzi);
2661 smb_SetSMBParm(outp, 15, (unsigned short) tzi.Bias); /* server tzone */
2663 if (smb_authType == SMB_AUTH_NTLM) {
2664 smb_SetSMBParmByte(outp, 16, MSV1_0_CHALLENGE_LENGTH);/* Encryption key length */
2665 smb_SetSMBDataLength(outp, MSV1_0_CHALLENGE_LENGTH + smb_ServerDomainNameLength);
2666 /* paste in encryption key */
2667 datap = smb_GetSMBData(outp, NULL);
2668 memcpy(datap,vcp->encKey,MSV1_0_CHALLENGE_LENGTH);
2669 /* and the faux domain name */
2670 strcpy(datap + MSV1_0_CHALLENGE_LENGTH,smb_ServerDomainName);
2671 } else if ( smb_authType == SMB_AUTH_EXTENDED ) {
2675 smb_SetSMBParmByte(outp, 16, 0); /* Encryption key length */
2677 smb_NegotiateExtendedSecurity(&secBlob, &secBlobLength);
2679 smb_SetSMBDataLength(outp, secBlobLength + sizeof(smb_ServerGUID));
2681 datap = smb_GetSMBData(outp, NULL);
2682 memcpy(datap, &smb_ServerGUID, sizeof(smb_ServerGUID));
2685 datap += sizeof(smb_ServerGUID);
2686 memcpy(datap, secBlob, secBlobLength);
2690 smb_SetSMBParmByte(outp, 16, 0); /* Encryption key length */
2691 smb_SetSMBDataLength(outp, 0); /* Perhaps we should specify 8 bytes anyway */
2694 else if (v3ProtoIndex != -1) {
2695 smb_SetSMBParm(outp, 0, protoIndex);
2697 /* NOTE: Extended authentication cannot be negotiated with v3
2698 * therefore we fail over to NTLM
2700 if (smb_authType == SMB_AUTH_NTLM || smb_authType == SMB_AUTH_EXTENDED) {
2701 smb_SetSMBParm(outp, 1,
2702 NEGOTIATE_SECURITY_USER_LEVEL |
2703 NEGOTIATE_SECURITY_CHALLENGE_RESPONSE); /* user level security, challenge response */
2705 smb_SetSMBParm(outp, 1, 0); /* share level auth with clear password */
2707 smb_SetSMBParm(outp, 2, SMB_PACKETSIZE);
2708 smb_SetSMBParm(outp, 3, smb_maxMpxRequests); /* max multiplexed requests */
2709 smb_SetSMBParm(outp, 4, smb_maxVCPerServer); /* max VCs per consumer/server connection */
2710 smb_SetSMBParm(outp, 5, 0); /* no support of block mode for read or write */
2711 smb_SetSMBParm(outp, 6, 1); /* next 2: session key */
2712 smb_SetSMBParm(outp, 7, 1);
2714 smb_SearchTimeFromUnixTime(&dosTime, unixTime);
2715 smb_SetSMBParm(outp, 8, LOWORD(dosTime)); /* server time */
2716 smb_SetSMBParm(outp, 9, HIWORD(dosTime)); /* server date */
2718 GetTimeZoneInformation(&tzi);
2719 smb_SetSMBParm(outp, 10, (unsigned short) tzi.Bias); /* server tzone */
2721 /* NOTE: Extended authentication cannot be negotiated with v3
2722 * therefore we fail over to NTLM
2724 if (smb_authType == SMB_AUTH_NTLM || smb_authType == SMB_AUTH_EXTENDED) {
2725 smb_SetSMBParm(outp, 11, MSV1_0_CHALLENGE_LENGTH); /* encryption key length */
2726 smb_SetSMBParm(outp, 12, 0); /* resvd */
2727 smb_SetSMBDataLength(outp, MSV1_0_CHALLENGE_LENGTH + smb_ServerDomainNameLength); /* perhaps should specify 8 bytes anyway */
2728 datap = smb_GetSMBData(outp, NULL);
2729 /* paste in a new encryption key */
2730 memcpy(datap, vcp->encKey, MSV1_0_CHALLENGE_LENGTH);
2731 /* and the faux domain name */
2732 strcpy(datap + MSV1_0_CHALLENGE_LENGTH, smb_ServerDomainName);
2734 smb_SetSMBParm(outp, 11, 0); /* encryption key length */
2735 smb_SetSMBParm(outp, 12, 0); /* resvd */
2736 smb_SetSMBDataLength(outp, 0);
2739 else if (coreProtoIndex != -1) { /* not really supported anymore */
2740 smb_SetSMBParm(outp, 0, protoIndex);
2741 smb_SetSMBDataLength(outp, 0);
2746 void smb_Daemon(void *parmp)
2753 if ((count % 360) == 0) { /* every hour */
2756 /* Initialize smb_localZero */
2757 myTime.tm_isdst = -1; /* compute whether on DST or not */
2758 myTime.tm_year = 70;
2764 smb_localZero = mktime(&myTime);
2766 smb_CalculateNowTZ();
2768 /* XXX GC dir search entries */
2772 void smb_WaitingLocksDaemon()
2774 smb_waitingLock_t *wL, *nwL;
2777 smb_packet_t *inp, *outp;
2782 lock_ObtainWrite(&smb_globalLock);
2783 nwL = smb_allWaitingLocks;
2785 osi_SleepW((long)&smb_allWaitingLocks, &smb_globalLock);
2794 lock_ObtainWrite(&smb_globalLock);
2796 nwL = (smb_waitingLock_t *) osi_QNext(&wL->q);
2797 lock_ReleaseWrite(&smb_globalLock);
2798 code = cm_RetryLock((cm_file_lock_t *) wL->lockp,
2799 wL->vcp->flags & SMB_VCFLAG_ALREADYDEAD);
2800 if (code == CM_ERROR_WOULDBLOCK) {
2802 if (wL->timeRemaining != 0xffffffff
2803 && (wL->timeRemaining -= 1000) < 0)
2812 ncbp->ncb_length = inp->ncb_length;
2813 inp->spacep = cm_GetSpace();
2815 /* Remove waitingLock from list */
2816 lock_ObtainWrite(&smb_globalLock);
2817 osi_QRemove((osi_queue_t **)&smb_allWaitingLocks,
2819 lock_ReleaseWrite(&smb_globalLock);
2821 /* Resume packet processing */
2823 smb_SetSMBDataLength(outp, 0);
2824 outp->flags |= SMB_PACKETFLAG_SUSPENDED;
2825 outp->resumeCode = code;
2827 smb_DispatchPacket(vcp, inp, outp, ncbp, NULL);
2830 cm_FreeSpace(inp->spacep);
2831 smb_FreePacket(inp);
2832 smb_FreePacket(outp);
2840 long smb_ReceiveCoreGetDiskAttributes(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
2842 osi_Log0(smb_logp, "SMB receive get disk attributes");
2844 smb_SetSMBParm(outp, 0, 32000);
2845 smb_SetSMBParm(outp, 1, 64);
2846 smb_SetSMBParm(outp, 2, 1024);
2847 smb_SetSMBParm(outp, 3, 30000);
2848 smb_SetSMBParm(outp, 4, 0);
2849 smb_SetSMBDataLength(outp, 0);
2853 long smb_ReceiveCoreTreeConnect(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *rsp)
2857 unsigned short newTid;
2858 char shareName[256];
2866 osi_Log0(smb_logp, "SMB receive tree connect");
2868 /* parse input parameters */
2869 tp = smb_GetSMBData(inp, NULL);
2870 pathp = smb_ParseASCIIBlock(tp, &tp);
2871 passwordp = smb_ParseASCIIBlock(tp, &tp);
2872 tp = strrchr(pathp, '\\');
2874 return CM_ERROR_BADSMB;
2875 strcpy(shareName, tp+1);
2877 userp = smb_GetUser(vcp, inp);
2879 lock_ObtainMutex(&vcp->mx);
2880 newTid = vcp->tidCounter++;
2881 lock_ReleaseMutex(&vcp->mx);
2883 tidp = smb_FindTID(vcp, newTid, SMB_FLAG_CREATE);
2884 uidp = smb_FindUID(vcp, ((smb_t *)inp)->uid, 0);
2885 shareFound = smb_FindShare(vcp, uidp, shareName, &sharePath);
2887 smb_ReleaseUID(uidp);
2889 smb_ReleaseTID(tidp);
2890 return CM_ERROR_BADSHARENAME;
2892 lock_ObtainMutex(&tidp->mx);
2893 tidp->userp = userp;
2894 tidp->pathname = sharePath;
2895 lock_ReleaseMutex(&tidp->mx);
2896 smb_ReleaseTID(tidp);
2898 smb_SetSMBParm(rsp, 0, SMB_PACKETSIZE);
2899 smb_SetSMBParm(rsp, 1, newTid);
2900 smb_SetSMBDataLength(rsp, 0);
2902 osi_Log1(smb_logp, "SMB tree connect created ID %d", newTid);
2906 unsigned char *smb_ParseDataBlock(unsigned char *inp, char **chainpp, int *lengthp)
2910 if (*inp++ != 0x1) return NULL;
2911 tlen = inp[0] + (inp[1]<<8);
2912 inp += 2; /* skip length field */
2915 *chainpp = inp + tlen;
2918 if (lengthp) *lengthp = tlen;
2923 /* set maskp to the mask part of the incoming path.
2924 * Mask is 11 bytes long (8.3 with the dot elided).
2925 * Returns true if succeeds with a valid name, otherwise it does
2926 * its best, but returns false.
2928 int smb_Get8Dot3MaskFromPath(unsigned char *maskp, unsigned char *pathp)
2936 /* starts off valid */
2939 /* mask starts out all blanks */
2940 memset(maskp, ' ', 11);
2942 /* find last backslash, or use whole thing if there is none */
2943 tp = strrchr(pathp, '\\');
2944 if (!tp) tp = pathp;
2945 else tp++; /* skip slash */
2949 /* names starting with a dot are illegal */
2950 if (*tp == '.') valid8Dot3 = 0;
2954 if (tc == 0) return valid8Dot3;
2955 if (tc == '.' || tc == '"') break;
2956 if (i < 8) *up++ = tc;
2957 else valid8Dot3 = 0;
2960 /* if we get here, tp point after the dot */
2961 up = maskp+8; /* ext goes here */
2968 if (tc == '.' || tc == '"')
2971 /* copy extension if not too long */
2981 int smb_Match8Dot3Mask(char *unixNamep, char *maskp)
2991 /* XXX redo this, calling smb_V3MatchMask with a converted mask */
2993 valid = smb_Get8Dot3MaskFromPath(umask, unixNamep);
2997 /* otherwise, we have a valid 8.3 name; see if we have a match,
2998 * treating '?' as a wildcard in maskp (but not in the file name).
3000 tp1 = umask; /* real name, in mask format */
3001 tp2 = maskp; /* mask, in mask format */
3002 for(i=0; i<11; i++) {
3003 tc1 = *tp1++; /* char from real name */
3004 tc2 = *tp2++; /* char from mask */
3005 tc1 = (char) cm_foldUpper[(unsigned char)tc1];
3006 tc2 = (char) cm_foldUpper[(unsigned char)tc2];
3009 if (tc2 == '?' && tc1 != ' ')
3016 /* we got a match */
3020 char *smb_FindMask(char *pathp)
3024 tp = strrchr(pathp, '\\'); /* find last slash */
3027 return tp+1; /* skip the slash */
3029 return pathp; /* no slash, return the entire path */
3032 long smb_ReceiveCoreSearchVolume(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3034 unsigned char *pathp;
3036 unsigned char mask[11];
3037 unsigned char *statBlockp;
3038 unsigned char initStatBlock[21];
3041 osi_Log0(smb_logp, "SMB receive search volume");
3043 /* pull pathname and stat block out of request */
3044 tp = smb_GetSMBData(inp, NULL);
3045 pathp = smb_ParseASCIIBlock(tp, (char **) &tp);
3046 osi_assert(pathp != NULL);
3047 statBlockp = smb_ParseVblBlock(tp, (char **) &tp, &statLen);
3048 osi_assert(statBlockp != NULL);
3050 statBlockp = initStatBlock;
3054 /* for returning to caller */
3055 smb_Get8Dot3MaskFromPath(mask, pathp);
3057 smb_SetSMBParm(outp, 0, 1); /* we're returning one entry */
3058 tp = smb_GetSMBData(outp, NULL);
3060 *tp++ = 43; /* bytes in a dir entry */
3061 *tp++ = 0; /* high byte in counter */
3063 /* now marshall the dir entry, starting with the search status */
3064 *tp++ = statBlockp[0]; /* Reserved */
3065 memcpy(tp, mask, 11); tp += 11; /* FileName */
3067 /* now pass back server use info, with 1st byte non-zero */
3069 memset(tp, 0, 4); tp += 4; /* reserved for server use */
3071 memcpy(tp, statBlockp+17, 4); tp += 4; /* reserved for consumer */
3073 *tp++ = 0x8; /* attribute: volume */
3083 /* 4 byte file size */
3089 /* finally, null-terminated 8.3 pathname, which we set to AFS */
3090 memset(tp, ' ', 13);
3093 /* set the length of the data part of the packet to 43 + 3, for the dir
3094 * entry plus the 5 and the length fields.
3096 smb_SetSMBDataLength(outp, 46);
3100 long smb_ApplyDirListPatches(smb_dirListPatch_t **dirPatchespp,
3101 cm_user_t *userp, cm_req_t *reqp)
3109 smb_dirListPatch_t *patchp;
3110 smb_dirListPatch_t *npatchp;
3112 for(patchp = *dirPatchespp; patchp; patchp =
3113 (smb_dirListPatch_t *) osi_QNext(&patchp->q)) {
3114 code = cm_GetSCache(&patchp->fid, &scp, userp, reqp);
3116 lock_ObtainMutex(&scp->mx);
3117 code = cm_SyncOp(scp, NULL, userp, reqp, 0,
3118 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3120 lock_ReleaseMutex(&scp->mx);
3121 cm_ReleaseSCache(scp);
3124 dptr = patchp->dptr;
3126 attr = smb_Attributes(scp);
3127 /* check hidden attribute (the flag is only ON when dot file hiding is on ) */
3128 if( patchp->flags & SMB_DIRLISTPATCH_DOTFILE )
3129 attr |= SMB_ATTR_HIDDEN;
3133 smb_SearchTimeFromUnixTime(&dosTime, scp->clientModTime);
3136 shortTemp = dosTime & 0xffff;
3137 *((u_short *)dptr) = shortTemp;
3140 /* and copy out date */
3141 shortTemp = (dosTime>>16) & 0xffff;
3142 *((u_short *)dptr) = shortTemp;
3145 /* copy out file length */
3146 *((u_long *)dptr) = scp->length.LowPart;
3148 lock_ReleaseMutex(&scp->mx);
3149 cm_ReleaseSCache(scp);
3152 /* now free the patches */
3153 for(patchp = *dirPatchespp; patchp; patchp = npatchp) {
3154 npatchp = (smb_dirListPatch_t *) osi_QNext(&patchp->q);
3158 /* and mark the list as empty */
3159 *dirPatchespp = NULL;
3164 long smb_ReceiveCoreSearchDir(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3173 smb_dirListPatch_t *dirListPatchesp;
3174 smb_dirListPatch_t *curPatchp;
3178 osi_hyper_t dirLength;
3179 osi_hyper_t bufferOffset;
3180 osi_hyper_t curOffset;
3182 unsigned char *inCookiep;
3183 smb_dirSearch_t *dsp;
3187 unsigned long clientCookie;
3188 cm_pageHeader_t *pageHeaderp;
3189 cm_user_t *userp = NULL;
3196 long nextEntryCookie;
3197 int numDirChunks; /* # of 32 byte dir chunks in this entry */
3198 char resByte; /* reserved byte from the cookie */
3199 char *op; /* output data ptr */
3200 char *origOp; /* original value of op */
3201 cm_space_t *spacep; /* for pathname buffer */
3212 maxCount = smb_GetSMBParm(inp, 0);
3214 dirListPatchesp = NULL;
3216 caseFold = CM_FLAG_CASEFOLD;
3218 tp = smb_GetSMBData(inp, NULL);
3219 pathp = smb_ParseASCIIBlock(tp, &tp);
3220 inCookiep = smb_ParseVblBlock(tp, &tp, &dataLength);
3222 /* bail out if request looks bad */
3223 if (!tp || !pathp) {
3224 return CM_ERROR_BADSMB;
3227 /* We can handle long names */
3228 if (vcp->flags & SMB_VCFLAG_USENT)
3229 ((smb_t *)outp)->flg2 |= 0x40; /* IS_LONG_NAME */
3231 /* make sure we got a whole search status */
3232 if (dataLength < 21) {
3233 nextCookie = 0; /* start at the beginning of the dir */
3236 attribute = smb_GetSMBParm(inp, 1);
3238 /* handle volume info in another function */
3239 if (attribute & 0x8)
3240 return smb_ReceiveCoreSearchVolume(vcp, inp, outp);
3242 osi_Log2(smb_logp, "SMB receive search dir count %d [%s]",
3243 maxCount, osi_LogSaveString(smb_logp, pathp));
3245 if (*pathp == 0) { /* null pathp, treat as root dir */
3246 if (!(attribute & SMB_ATTR_DIRECTORY)) /* exclude dirs */
3247 return CM_ERROR_NOFILES;
3251 dsp = smb_NewDirSearch(0);
3252 dsp->attribute = attribute;
3253 smb_Get8Dot3MaskFromPath(mask, pathp);
3254 memcpy(dsp->mask, mask, 11);
3256 /* track if this is likely to match a lot of entries */
3257 if (smb_IsStarMask(mask)) starPattern = 1;
3258 else starPattern = 0;
3261 /* pull the next cookie value out of the search status block */
3262 nextCookie = inCookiep[13] + (inCookiep[14]<<8) + (inCookiep[15]<<16)
3263 + (inCookiep[16]<<24);
3264 dsp = smb_FindDirSearch(inCookiep[12]);
3266 /* can't find dir search status; fatal error */
3267 return CM_ERROR_BADFD;
3269 attribute = dsp->attribute;
3270 resByte = inCookiep[0];
3272 /* copy out client cookie, in host byte order. Don't bother
3273 * interpreting it, since we're just passing it through, anyway.
3275 memcpy(&clientCookie, &inCookiep[17], 4);
3277 memcpy(mask, dsp->mask, 11);
3279 /* assume we're doing a star match if it has continued for more
3285 osi_Log3(smb_logp, "SMB dir search cookie 0x%x, connection %d, attr 0x%x",
3286 nextCookie, dsp->cookie, attribute);
3288 userp = smb_GetUser(vcp, inp);
3290 /* try to get the vnode for the path name next */
3291 lock_ObtainMutex(&dsp->mx);
3298 spacep = inp->spacep;
3299 smb_StripLastComponent(spacep->data, NULL, pathp);
3300 lock_ReleaseMutex(&dsp->mx);
3301 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3302 code = cm_NameI(cm_rootSCachep, spacep->data,
3303 caseFold | CM_FLAG_FOLLOW, userp, tidPathp, &req, &scp);
3304 lock_ObtainMutex(&dsp->mx);
3306 if (dsp->scp != 0) cm_ReleaseSCache(dsp->scp);
3308 /* we need one hold for the entry we just stored into,
3309 * and one for our own processing. When we're done with this
3310 * function, we'll drop the one for our own processing.
3311 * We held it once from the namei call, and so we do another hold
3315 lock_ObtainMutex(&scp->mx);
3316 if ((scp->flags & CM_SCACHEFLAG_BULKSTATTING) == 0
3317 && LargeIntegerGreaterOrEqualToZero(scp->bulkStatProgress)) {
3318 scp->flags |= CM_SCACHEFLAG_BULKSTATTING;
3319 dsp->flags |= SMB_DIRSEARCH_BULKST;
3321 lock_ReleaseMutex(&scp->mx);
3324 lock_ReleaseMutex(&dsp->mx);
3326 cm_ReleaseUser(userp);
3327 smb_DeleteDirSearch(dsp);
3328 smb_ReleaseDirSearch(dsp);
3332 /* reserves space for parameter; we'll adjust it again later to the
3333 * real count of the # of entries we returned once we've actually
3334 * assembled the directory listing.
3336 smb_SetSMBParm(outp, 0, 0);
3338 /* get the directory size */
3339 lock_ObtainMutex(&scp->mx);
3340 code = cm_SyncOp(scp, NULL, userp, &req, 0,
3341 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3343 lock_ReleaseMutex(&scp->mx);
3344 cm_ReleaseSCache(scp);
3345 cm_ReleaseUser(userp);
3346 smb_DeleteDirSearch(dsp);
3347 smb_ReleaseDirSearch(dsp);
3351 dirLength = scp->length;
3353 bufferOffset.LowPart = bufferOffset.HighPart = 0;
3354 curOffset.HighPart = 0;
3355 curOffset.LowPart = nextCookie;
3356 origOp = op = smb_GetSMBData(outp, NULL);
3357 /* and write out the basic header */
3358 *op++ = 5; /* variable block */
3359 op += 2; /* skip vbl block length; we'll fill it in later */
3363 /* make sure that curOffset.LowPart doesn't point to the first
3364 * 32 bytes in the 2nd through last dir page, and that it doesn't
3365 * point at the first 13 32-byte chunks in the first dir page,
3366 * since those are dir and page headers, and don't contain useful
3369 temp = curOffset.LowPart & (2048-1);
3370 if (curOffset.HighPart == 0 && curOffset.LowPart < 2048) {
3371 /* we're in the first page */
3372 if (temp < 13*32) temp = 13*32;
3375 /* we're in a later dir page */
3376 if (temp < 32) temp = 32;
3379 /* make sure the low order 5 bits are zero */
3382 /* now put temp bits back ito curOffset.LowPart */
3383 curOffset.LowPart &= ~(2048-1);
3384 curOffset.LowPart |= temp;
3386 /* check if we've returned all the names that will fit in the
3389 if (returnedNames >= maxCount)
3392 /* check if we've passed the dir's EOF */
3393 if (LargeIntegerGreaterThanOrEqualTo(curOffset, dirLength)) break;
3395 /* see if we can use the bufferp we have now; compute in which page
3396 * the current offset would be, and check whether that's the offset
3397 * of the buffer we have. If not, get the buffer.
3399 thyper.HighPart = curOffset.HighPart;
3400 thyper.LowPart = curOffset.LowPart & ~(buf_bufferSize-1);
3401 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
3404 buf_Release(bufferp);
3407 lock_ReleaseMutex(&scp->mx);
3408 lock_ObtainRead(&scp->bufCreateLock);
3409 code = buf_Get(scp, &thyper, &bufferp);
3410 lock_ReleaseRead(&scp->bufCreateLock);
3412 /* now, if we're doing a star match, do bulk fetching of all of
3413 * the status info for files in the dir.
3416 smb_ApplyDirListPatches(&dirListPatchesp, userp,
3418 if ((dsp->flags & SMB_DIRSEARCH_BULKST)
3419 && LargeIntegerGreaterThanOrEqualTo(thyper,
3420 scp->bulkStatProgress)) {
3421 /* Don't bulk stat if risking timeout */
3422 int now = GetCurrentTime();
3423 if (now - req.startTime > 5000) {
3424 scp->bulkStatProgress = thyper;
3425 scp->flags &= ~CM_SCACHEFLAG_BULKSTATTING;
3426 dsp->flags &= ~SMB_DIRSEARCH_BULKST;
3428 cm_TryBulkStat(scp, &thyper, userp, &req);
3432 lock_ObtainMutex(&scp->mx);
3435 bufferOffset = thyper;
3437 /* now get the data in the cache */
3439 code = cm_SyncOp(scp, bufferp, userp, &req,
3441 CM_SCACHESYNC_NEEDCALLBACK
3442 | CM_SCACHESYNC_READ);
3445 if (cm_HaveBuffer(scp, bufferp, 0)) break;
3447 /* otherwise, load the buffer and try again */
3448 code = cm_GetBuffer(scp, bufferp, NULL, userp,
3453 buf_Release(bufferp);
3457 } /* if (wrong buffer) ... */
3459 /* now we have the buffer containing the entry we're interested in; copy
3460 * it out if it represents a non-deleted entry.
3462 entryInDir = curOffset.LowPart & (2048-1);
3463 entryInBuffer = curOffset.LowPart & (buf_bufferSize - 1);
3465 /* page header will help tell us which entries are free. Page header
3466 * can change more often than once per buffer, since AFS 3 dir page size
3467 * may be less than (but not more than a buffer package buffer.
3469 temp = curOffset.LowPart & (buf_bufferSize - 1); /* only look intra-buffer */
3470 temp &= ~(2048 - 1); /* turn off intra-page bits */
3471 pageHeaderp = (cm_pageHeader_t *) (bufferp->datap + temp);
3473 /* now determine which entry we're looking at in the page. If it is
3474 * free (there's a free bitmap at the start of the dir), we should
3475 * skip these 32 bytes.
3477 slotInPage = (entryInDir & 0x7e0) >> 5;
3478 if (!(pageHeaderp->freeBitmap[slotInPage>>3] & (1 << (slotInPage & 0x7)))) {
3479 /* this entry is free */
3480 numDirChunks = 1; /* only skip this guy */
3484 tp = bufferp->datap + entryInBuffer;
3485 dep = (cm_dirEntry_t *) tp; /* now points to AFS3 dir entry */
3487 /* while we're here, compute the next entry's location, too,
3488 * since we'll need it when writing out the cookie into the dir
3491 * XXXX Probably should do more sanity checking.
3493 numDirChunks = cm_NameEntries(dep->name, NULL);
3495 /* compute the offset of the cookie representing the next entry */
3496 nextEntryCookie = curOffset.LowPart + (CM_DIR_CHUNKSIZE * numDirChunks);
3498 /* Compute 8.3 name if necessary */
3499 actualName = dep->name;
3500 if (dep->fid.vnode != 0 && !cm_Is8Dot3(actualName)) {
3501 cm_Gen8Dot3Name(dep, shortName, &shortNameEnd);
3502 actualName = shortName;
3505 if (dep->fid.vnode != 0 && smb_Match8Dot3Mask(actualName, mask)) {
3506 /* this is one of the entries to use: it is not deleted
3507 * and it matches the star pattern we're looking for.
3510 /* Eliminate entries that don't match requested
3513 /* no hidden files */
3514 if(smb_hideDotFiles && !(dsp->attribute & SMB_ATTR_HIDDEN) && smb_IsDotFile(actualName))
3517 if (!(dsp->attribute & SMB_ATTR_DIRECTORY)) /* no directories */
3519 /* We have already done the cm_TryBulkStat above */
3520 fid.cell = scp->fid.cell;
3521 fid.volume = scp->fid.volume;
3522 fid.vnode = ntohl(dep->fid.vnode);
3523 fid.unique = ntohl(dep->fid.unique);
3524 fileType = cm_FindFileType(&fid);
3525 osi_Log2(smb_logp, "smb_ReceiveCoreSearchDir: file %s "
3526 "has filetype %d", dep->name,
3528 if (fileType == CM_SCACHETYPE_DIRECTORY)
3533 memcpy(op, mask, 11); op += 11;
3534 *op++ = (char) dsp->cookie; /* they say it must be non-zero */
3535 *op++ = nextEntryCookie & 0xff;
3536 *op++ = (nextEntryCookie>>8) & 0xff;
3537 *op++ = (nextEntryCookie>>16) & 0xff;
3538 *op++ = (nextEntryCookie>>24) & 0xff;
3539 memcpy(op, &clientCookie, 4); op += 4;
3541 /* now we emit the attribute. This is sort of tricky,
3542 * since we need to really stat the file to find out
3543 * what type of entry we've got. Right now, we're
3544 * copying out data from a buffer, while holding the
3545 * scp locked, so it isn't really convenient to stat
3546 * something now. We'll put in a place holder now,
3547 * and make a second pass before returning this to get
3548 * the real attributes. So, we just skip the data for
3549 * now, and adjust it later. We allocate a patch
3550 * record to make it easy to find this point later.
3551 * The replay will happen at a time when it is safe to
3552 * unlock the directory.
3554 curPatchp = malloc(sizeof(*curPatchp));
3555 osi_QAdd((osi_queue_t **) &dirListPatchesp, &curPatchp->q);
3556 curPatchp->dptr = op;
3557 curPatchp->fid.cell = scp->fid.cell;
3558 curPatchp->fid.volume = scp->fid.volume;
3559 curPatchp->fid.vnode = ntohl(dep->fid.vnode);
3560 curPatchp->fid.unique = ntohl(dep->fid.unique);
3562 /* do hidden attribute here since name won't be around when applying
3566 if ( smb_hideDotFiles && smb_IsDotFile(actualName) )
3567 curPatchp->flags = SMB_DIRLISTPATCH_DOTFILE;
3569 curPatchp->flags = 0;
3571 op += 9; /* skip attr, time, date and size */
3573 /* zero out name area. The spec says to pad with
3574 * spaces, but Samba doesn't, and neither do we.
3578 /* finally, we get to copy out the name; we know that
3579 * it fits in 8.3 or the pattern wouldn't match, but it
3580 * never hurts to be sure.
3582 strncpy(op, actualName, 13);
3584 /* Uppercase if requested by client */
3585 if ((((smb_t *)inp)->flg2 & 1) == 0)
3590 /* now, adjust the # of entries copied */
3592 } /* if we're including this name */
3595 /* and adjust curOffset to be where the new cookie is */
3596 thyper.HighPart = 0;
3597 thyper.LowPart = CM_DIR_CHUNKSIZE * numDirChunks;
3598 curOffset = LargeIntegerAdd(thyper, curOffset);
3599 } /* while copying data for dir listing */
3601 /* release the mutex */
3602 lock_ReleaseMutex(&scp->mx);
3603 if (bufferp) buf_Release(bufferp);
3605 /* apply and free last set of patches; if not doing a star match, this
3606 * will be empty, but better safe (and freeing everything) than sorry.
3608 smb_ApplyDirListPatches(&dirListPatchesp, userp, &req);
3610 /* special return code for unsuccessful search */
3611 if (code == 0 && dataLength < 21 && returnedNames == 0)
3612 code = CM_ERROR_NOFILES;
3614 osi_Log2(smb_logp, "SMB search dir done, %d names, code %d",
3615 returnedNames, code);
3618 smb_DeleteDirSearch(dsp);
3619 smb_ReleaseDirSearch(dsp);
3620 cm_ReleaseSCache(scp);
3621 cm_ReleaseUser(userp);
3625 /* finalize the output buffer */
3626 smb_SetSMBParm(outp, 0, returnedNames);
3627 temp = (long) (op - origOp);
3628 smb_SetSMBDataLength(outp, temp);
3630 /* the data area is a variable block, which has a 5 (already there)
3631 * followed by the length of the # of data bytes. We now know this to
3632 * be "temp," although that includes the 3 bytes of vbl block header.
3633 * Deduct for them and fill in the length field.
3635 temp -= 3; /* deduct vbl block info */
3636 osi_assert(temp == (43 * returnedNames));
3637 origOp[1] = temp & 0xff;
3638 origOp[2] = (temp>>8) & 0xff;
3639 if (returnedNames == 0) smb_DeleteDirSearch(dsp);
3640 smb_ReleaseDirSearch(dsp);
3641 cm_ReleaseSCache(scp);
3642 cm_ReleaseUser(userp);
3646 /* verify that this is a valid path to a directory. I don't know why they
3647 * don't use the get file attributes call.
3649 long smb_ReceiveCoreCheckPath(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3653 cm_scache_t *rootScp;
3654 cm_scache_t *newScp;
3663 pathp = smb_GetSMBData(inp, NULL);
3664 pathp = smb_ParseASCIIBlock(pathp, NULL);
3665 osi_Log1(smb_logp, "SMB receive check path %s",
3666 osi_LogSaveString(smb_logp, pathp));
3669 return CM_ERROR_BADFD;
3672 rootScp = cm_rootSCachep;
3674 userp = smb_GetUser(vcp, inp);
3676 caseFold = CM_FLAG_CASEFOLD;
3678 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3679 code = cm_NameI(rootScp, pathp,
3680 caseFold | CM_FLAG_FOLLOW | CM_FLAG_CHECKPATH,
3681 userp, tidPathp, &req, &newScp);
3684 cm_ReleaseUser(userp);
3688 /* now lock the vnode with a callback; returns with newScp locked */
3689 lock_ObtainMutex(&newScp->mx);
3690 code = cm_SyncOp(newScp, NULL, userp, &req, PRSFS_LOOKUP,
3691 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
3692 if (code && code != CM_ERROR_NOACCESS) {
3693 lock_ReleaseMutex(&newScp->mx);
3694 cm_ReleaseSCache(newScp);
3695 cm_ReleaseUser(userp);
3699 attrs = smb_Attributes(newScp);
3701 if (!(attrs & 0x10))
3702 code = CM_ERROR_NOTDIR;
3704 lock_ReleaseMutex(&newScp->mx);
3706 cm_ReleaseSCache(newScp);
3707 cm_ReleaseUser(userp);
3711 long smb_ReceiveCoreSetFileAttributes(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3715 cm_scache_t *rootScp;
3716 unsigned short attribute;
3718 cm_scache_t *newScp;
3727 /* decode basic attributes we're passed */
3728 attribute = smb_GetSMBParm(inp, 0);
3729 dosTime = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
3731 pathp = smb_GetSMBData(inp, NULL);
3732 pathp = smb_ParseASCIIBlock(pathp, NULL);
3735 return CM_ERROR_BADSMB;
3738 osi_Log2(smb_logp, "SMB receive setfile attributes time %d, attr 0x%x",
3739 dosTime, attribute);
3741 rootScp = cm_rootSCachep;
3743 userp = smb_GetUser(vcp, inp);
3745 caseFold = CM_FLAG_CASEFOLD;
3747 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3748 code = cm_NameI(rootScp, pathp, caseFold | CM_FLAG_FOLLOW, userp,
3749 tidPathp, &req, &newScp);
3752 cm_ReleaseUser(userp);
3756 /* now lock the vnode with a callback; returns with newScp locked; we
3757 * need the current status to determine what the new status is, in some
3760 lock_ObtainMutex(&newScp->mx);
3761 code = cm_SyncOp(newScp, NULL, userp, &req, 0,
3762 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
3764 lock_ReleaseMutex(&newScp->mx);
3765 cm_ReleaseSCache(newScp);
3766 cm_ReleaseUser(userp);
3770 /* Check for RO volume */
3771 if (newScp->flags & CM_SCACHEFLAG_RO) {
3772 lock_ReleaseMutex(&newScp->mx);
3773 cm_ReleaseSCache(newScp);
3774 cm_ReleaseUser(userp);
3775 return CM_ERROR_READONLY;
3778 /* prepare for setattr call */
3781 attr.mask |= CM_ATTRMASK_CLIENTMODTIME;
3782 smb_UnixTimeFromDosUTime(&attr.clientModTime, dosTime);
3784 if ((newScp->unixModeBits & 0222) && (attribute & 1) != 0) {
3785 /* we're told to make a writable file read-only */
3786 attr.unixModeBits = newScp->unixModeBits & ~0222;
3787 attr.mask |= CM_ATTRMASK_UNIXMODEBITS;
3789 else if ((newScp->unixModeBits & 0222) == 0 && (attribute & 1) == 0) {
3790 /* we're told to make a read-only file writable */
3791 attr.unixModeBits = newScp->unixModeBits | 0222;
3792 attr.mask |= CM_ATTRMASK_UNIXMODEBITS;
3794 lock_ReleaseMutex(&newScp->mx);
3796 /* now call setattr */
3798 code = cm_SetAttr(newScp, &attr, userp, &req);
3802 cm_ReleaseSCache(newScp);
3803 cm_ReleaseUser(userp);
3808 long smb_ReceiveCoreGetFileAttributes(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3812 cm_scache_t *rootScp;
3813 cm_scache_t *newScp, *dscp;
3825 pathp = smb_GetSMBData(inp, NULL);
3826 pathp = smb_ParseASCIIBlock(pathp, NULL);
3829 return CM_ERROR_BADSMB;
3832 if (*pathp == 0) /* null path */
3835 osi_Log1(smb_logp, "SMB receive getfile attributes path %s",
3836 osi_LogSaveString(smb_logp, pathp));
3838 rootScp = cm_rootSCachep;
3840 userp = smb_GetUser(vcp, inp);
3842 /* we shouldn't need this for V3 requests, but we seem to */
3843 caseFold = CM_FLAG_CASEFOLD;
3845 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
3848 * XXX Strange hack XXX
3850 * As of Patch 5 (16 July 97), we are having the following problem:
3851 * In NT Explorer 4.0, whenever we click on a directory, AFS gets
3852 * requests to look up "desktop.ini" in all the subdirectories.
3853 * This can cause zillions of timeouts looking up non-existent cells
3854 * and volumes, especially in the top-level directory.
3856 * We have not found any way to avoid this or work around it except
3857 * to explicitly ignore the requests for mount points that haven't
3858 * yet been evaluated and for directories that haven't yet been
3861 * We should modify this hack to provide a fake desktop.ini file
3862 * http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/custom.asp
3864 spacep = inp->spacep;
3865 smb_StripLastComponent(spacep->data, &lastComp, pathp);
3866 if (lastComp && stricmp(lastComp, "\\desktop.ini") == 0) {
3867 code = cm_NameI(rootScp, spacep->data,
3868 caseFold | CM_FLAG_DIRSEARCH | CM_FLAG_FOLLOW,
3869 userp, tidPathp, &req, &dscp);
3871 if (dscp->fileType == CM_SCACHETYPE_MOUNTPOINT
3872 && !dscp->mountRootFidp)
3873 code = CM_ERROR_NOSUCHFILE;
3874 else if (dscp->fileType == CM_SCACHETYPE_DIRECTORY) {
3875 cm_buf_t *bp = buf_Find(dscp, &hzero);
3879 code = CM_ERROR_NOSUCHFILE;
3881 cm_ReleaseSCache(dscp);
3883 cm_ReleaseUser(userp);
3889 code = cm_NameI(rootScp, pathp, caseFold | CM_FLAG_FOLLOW, userp,
3890 tidPathp, &req, &newScp);
3893 cm_ReleaseUser(userp);
3897 /* now lock the vnode with a callback; returns with newScp locked */
3898 lock_ObtainMutex(&newScp->mx);
3899 code = cm_SyncOp(newScp, NULL, userp, &req, 0,
3900 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
3902 lock_ReleaseMutex(&newScp->mx);
3903 cm_ReleaseSCache(newScp);
3904 cm_ReleaseUser(userp);
3909 /* use smb_Attributes instead. Also the fact that a file is
3910 * in a readonly volume doesn't mean it shojuld be marked as RO
3912 if (newScp->fileType == CM_SCACHETYPE_DIRECTORY
3913 || newScp->fileType == CM_SCACHETYPE_MOUNTPOINT)
3914 attrs = SMB_ATTR_DIRECTORY;
3917 if ((newScp->unixModeBits & 0222) == 0 || (newScp->flags & CM_SCACHEFLAG_RO))
3918 attrs |= SMB_ATTR_READONLY; /* turn on read-only flag */
3920 attrs = smb_Attributes(newScp);
3923 smb_SetSMBParm(outp, 0, attrs);
3925 smb_DosUTimeFromUnixTime(&dosTime, newScp->clientModTime);
3926 smb_SetSMBParm(outp, 1, dosTime & 0xffff);
3927 smb_SetSMBParm(outp, 2, (dosTime>>16) & 0xffff);
3928 smb_SetSMBParm(outp, 3, newScp->length.LowPart & 0xffff);
3929 smb_SetSMBParm(outp, 4, (newScp->length.LowPart >> 16) & 0xffff);
3930 smb_SetSMBParm(outp, 5, 0);
3931 smb_SetSMBParm(outp, 6, 0);
3932 smb_SetSMBParm(outp, 7, 0);
3933 smb_SetSMBParm(outp, 8, 0);
3934 smb_SetSMBParm(outp, 9, 0);
3935 smb_SetSMBDataLength(outp, 0);
3936 lock_ReleaseMutex(&newScp->mx);
3938 cm_ReleaseSCache(newScp);
3939 cm_ReleaseUser(userp);
3944 long smb_ReceiveCoreTreeDisconnect(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3948 osi_Log0(smb_logp, "SMB receive tree disconnect");
3950 /* find the tree and free it */
3951 tidp = smb_FindTID(vcp, ((smb_t *)inp)->tid, 0);
3953 lock_ObtainMutex(&tidp->mx);
3954 tidp->flags |= SMB_TIDFLAG_DELETE;
3955 lock_ReleaseMutex(&tidp->mx);
3956 smb_ReleaseTID(tidp);
3962 long smb_ReceiveCoreOpen(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
3980 pathp = smb_GetSMBData(inp, NULL);
3981 pathp = smb_ParseASCIIBlock(pathp, NULL);
3983 osi_Log1(smb_logp, "SMB receive open file [%s]", osi_LogSaveString(smb_logp, pathp));
3985 #ifdef DEBUG_VERBOSE
3989 hexpath = osi_HexifyString( pathp );
3990 DEBUG_EVENT2("AFS", "CoreOpen H[%s] A[%s]", hexpath, pathp);
3995 share = smb_GetSMBParm(inp, 0);
3996 attribute = smb_GetSMBParm(inp, 1);
3998 spacep = inp->spacep;
3999 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
4000 if (lastNamep && strcmp(lastNamep, SMB_IOCTL_FILENAME) == 0) {
4001 /* special case magic file name for receiving IOCTL requests
4002 * (since IOCTL calls themselves aren't getting through).
4004 fidp = smb_FindFID(vcp, 0, SMB_FLAG_CREATE);
4005 smb_SetupIoctlFid(fidp, spacep);
4006 smb_SetSMBParm(outp, 0, fidp->fid);
4007 smb_SetSMBParm(outp, 1, 0); /* attrs */
4008 smb_SetSMBParm(outp, 2, 0); /* next 2 are DOS time */
4009 smb_SetSMBParm(outp, 3, 0);
4010 smb_SetSMBParm(outp, 4, 0); /* next 2 are length */
4011 smb_SetSMBParm(outp, 5, 0x7fff);
4012 /* pass the open mode back */
4013 smb_SetSMBParm(outp, 6, (share & 0xf));
4014 smb_SetSMBDataLength(outp, 0);
4015 smb_ReleaseFID(fidp);
4019 userp = smb_GetUser(vcp, inp);
4021 caseFold = CM_FLAG_CASEFOLD;
4023 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
4024 code = cm_NameI(cm_rootSCachep, pathp, caseFold | CM_FLAG_FOLLOW, userp,
4025 tidPathp, &req, &scp);
4028 cm_ReleaseUser(userp);
4032 code = cm_CheckOpen(scp, share & 0x7, 0, userp, &req);
4034 cm_ReleaseSCache(scp);
4035 cm_ReleaseUser(userp);
4039 /* don't need callback to check file type, since file types never
4040 * change, and namei and cm_Lookup all stat the object at least once on
4041 * a successful return.
4043 if (scp->fileType != CM_SCACHETYPE_FILE) {
4044 cm_ReleaseSCache(scp);
4045 cm_ReleaseUser(userp);
4046 return CM_ERROR_ISDIR;
4049 fidp = smb_FindFID(vcp, 0, SMB_FLAG_CREATE);
4052 /* save a pointer to the vnode */
4055 if ((share & 0xf) == 0)
4056 fidp->flags |= SMB_FID_OPENREAD;
4057 else if ((share & 0xf) == 1)
4058 fidp->flags |= SMB_FID_OPENWRITE;
4060 fidp->flags |= (SMB_FID_OPENREAD | SMB_FID_OPENWRITE);
4062 lock_ObtainMutex(&scp->mx);
4063 smb_SetSMBParm(outp, 0, fidp->fid);
4064 smb_SetSMBParm(outp, 1, smb_Attributes(scp));
4065 smb_DosUTimeFromUnixTime(&dosTime, scp->clientModTime);
4066 smb_SetSMBParm(outp, 2, dosTime & 0xffff);
4067 smb_SetSMBParm(outp, 3, (dosTime >> 16) & 0xffff);
4068 smb_SetSMBParm(outp, 4, scp->length.LowPart & 0xffff);
4069 smb_SetSMBParm(outp, 5, (scp->length.LowPart >> 16) & 0xffff);
4070 /* pass the open mode back; XXXX add access checks */
4071 smb_SetSMBParm(outp, 6, (share & 0xf));
4072 smb_SetSMBDataLength(outp, 0);
4073 lock_ReleaseMutex(&scp->mx);
4076 cm_Open(scp, 0, userp);
4078 /* send and free packet */
4079 smb_ReleaseFID(fidp);
4080 cm_ReleaseUser(userp);
4081 /* don't release scp, since we've squirreled away the pointer in the fid struct */
4085 typedef struct smb_unlinkRock {
4090 char *maskp; /* pointer to the star pattern */
4095 int smb_UnlinkProc(cm_scache_t *dscp, cm_dirEntry_t *dep, void *vrockp, osi_hyper_t *offp)
4098 smb_unlinkRock_t *rockp;
4106 caseFold = ((rockp->flags & SMB_MASKFLAG_CASEFOLD)? CM_FLAG_CASEFOLD : 0);
4107 if (!(rockp->vcp->flags & SMB_VCFLAG_USEV3))
4108 caseFold |= CM_FLAG_8DOT3;
4110 matchName = dep->name;
4111 match = smb_V3MatchMask(matchName, rockp->maskp, caseFold);
4113 && (rockp->flags & SMB_MASKFLAG_TILDE)
4114 && !cm_Is8Dot3(dep->name)) {
4115 cm_Gen8Dot3Name(dep, shortName, NULL);
4116 matchName = shortName;
4117 /* 8.3 matches are always case insensitive */
4118 match = smb_V3MatchMask(matchName, rockp->maskp, caseFold | CM_FLAG_CASEFOLD);
4121 osi_Log1(smb_logp, "Unlinking %s",
4122 osi_LogSaveString(smb_logp, matchName));
4123 code = cm_Unlink(dscp, dep->name, rockp->userp, rockp->reqp);
4124 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4125 smb_NotifyChange(FILE_ACTION_REMOVED,
4126 FILE_NOTIFY_CHANGE_FILE_NAME,
4127 dscp, dep->name, NULL, TRUE);
4130 /* If we made a case sensitive exact match, we might as well quit now. */
4131 if(!(rockp->flags & SMB_MASKFLAG_CASEFOLD) && !strcmp(matchName, rockp->maskp))
4132 code = CM_ERROR_STOPNOW;
4140 long smb_ReceiveCoreUnlink(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4149 smb_unlinkRock_t rock;
4158 attribute = smb_GetSMBParm(inp, 0);
4160 tp = smb_GetSMBData(inp, NULL);
4161 pathp = smb_ParseASCIIBlock(tp, &tp);
4163 osi_Log1(smb_logp, "SMB receive unlink %s",
4164 osi_LogSaveString(smb_logp, pathp));
4166 spacep = inp->spacep;
4167 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
4169 userp = smb_GetUser(vcp, inp);
4171 caseFold = CM_FLAG_FOLLOW | CM_FLAG_CASEFOLD;
4173 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
4174 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold, userp, tidPathp,
4178 cm_ReleaseUser(userp);
4182 /* otherwise, scp points to the parent directory. */
4189 rock.maskp = smb_FindMask(pathp);
4190 rock.flags = ((strchr(rock.maskp, '~') != NULL) ? SMB_MASKFLAG_TILDE : 0);
4193 thyper.HighPart = 0;
4199 /* Now, if we aren't dealing with a wildcard match, we first try an exact
4200 * match. If that fails, we do a case insensitve match.
4202 if (!(rock.flags & SMB_MASKFLAG_TILDE) &&
4203 !smb_IsStarMask(rock.maskp)) {
4204 code = cm_ApplyDir(dscp, smb_UnlinkProc, &rock, &thyper, userp, &req, NULL);
4207 thyper.HighPart = 0;
4208 rock.flags |= SMB_MASKFLAG_CASEFOLD;
4213 code = cm_ApplyDir(dscp, smb_UnlinkProc, &rock, &thyper, userp, &req, NULL);
4215 if (code == CM_ERROR_STOPNOW)
4218 cm_ReleaseUser(userp);
4220 cm_ReleaseSCache(dscp);
4222 if (code == 0 && !rock.any)
4223 code = CM_ERROR_NOSUCHFILE;
4227 typedef struct smb_renameRock {
4228 cm_scache_t *odscp; /* old dir */
4229 cm_scache_t *ndscp; /* new dir */
4230 cm_user_t *userp; /* user */
4231 cm_req_t *reqp; /* request struct */
4232 smb_vc_t *vcp; /* virtual circuit */
4233 char *maskp; /* pointer to star pattern of old file name */
4234 int flags; /* tilde, casefold, etc */
4235 char *newNamep; /* ptr to the new file's name */
4238 int smb_RenameProc(cm_scache_t *dscp, cm_dirEntry_t *dep, void *vrockp, osi_hyper_t *offp)
4241 smb_renameRock_t *rockp;
4246 rockp = (smb_renameRock_t *) vrockp;
4248 caseFold = ((rockp->flags & SMB_MASKFLAG_CASEFOLD)? CM_FLAG_CASEFOLD : 0);
4249 if (!(rockp->vcp->flags & SMB_VCFLAG_USEV3))
4250 caseFold |= CM_FLAG_8DOT3;
4252 match = smb_V3MatchMask(dep->name, rockp->maskp, caseFold);
4254 && (rockp->flags & SMB_MASKFLAG_TILDE)
4255 && !cm_Is8Dot3(dep->name)) {
4256 cm_Gen8Dot3Name(dep, shortName, NULL);
4257 match = smb_V3MatchMask(shortName, rockp->maskp, caseFold);
4260 code = cm_Rename(rockp->odscp, dep->name,
4261 rockp->ndscp, rockp->newNamep, rockp->userp,
4263 /* if the call worked, stop doing the search now, since we
4264 * really only want to rename one file.
4267 code = CM_ERROR_STOPNOW;
4274 long smb_ReceiveCoreRename(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4280 cm_space_t *spacep = NULL;
4281 smb_renameRock_t rock;
4282 cm_scache_t *oldDscp = NULL;
4283 cm_scache_t *newDscp = NULL;
4284 cm_scache_t *tmpscp= NULL;
4285 cm_scache_t *tmpscp2 = NULL;
4297 tp = smb_GetSMBData(inp, NULL);
4298 oldPathp = smb_ParseASCIIBlock(tp, &tp);
4299 newPathp = smb_ParseASCIIBlock(tp, &tp);
4301 osi_Log2(smb_logp, "smb rename [%s] to [%s]",
4302 osi_LogSaveString(smb_logp, oldPathp),
4303 osi_LogSaveString(smb_logp, newPathp));
4305 spacep = inp->spacep;
4306 smb_StripLastComponent(spacep->data, &oldLastNamep, oldPathp);
4308 userp = smb_GetUser(vcp, inp);
4311 * Changed to use CASEFOLD always. This enables us to rename Foo/baz when
4312 * what actually exists is foo/baz. I don't know why the code used to be
4313 * the way it was. 1/29/96
4315 * caseFold = ((vcp->flags & SMB_VCFLAG_USEV3) ? 0: CM_FLAG_CASEFOLD);
4317 * Changed to use CM_FLAG_FOLLOW. 7/24/96
4319 * caseFold = CM_FLAG_CASEFOLD;
4321 caseFold = CM_FLAG_FOLLOW | CM_FLAG_CASEFOLD;
4323 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
4324 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold,
4325 userp, tidPathp, &req, &oldDscp);
4328 cm_ReleaseUser(userp);
4332 smb_StripLastComponent(spacep->data, &newLastNamep, newPathp);
4333 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold,
4334 userp, tidPathp, &req, &newDscp);
4337 cm_ReleaseSCache(oldDscp);
4338 cm_ReleaseUser(userp);
4342 /* otherwise, oldDscp and newDscp point to the corresponding directories.
4343 * next, get the component names, and lower case them.
4346 /* handle the old name first */
4348 oldLastNamep = oldPathp;
4352 /* and handle the new name, too */
4354 newLastNamep = newPathp;
4358 /* TODO: The old name could be a wildcard. The new name must not be */
4360 /* do the vnode call */
4361 rock.odscp = oldDscp;
4362 rock.ndscp = newDscp;
4366 rock.maskp = oldLastNamep;
4367 rock.flags = ((strchr(oldLastNamep, '~') != NULL) ? SMB_MASKFLAG_TILDE : 0);
4368 rock.newNamep = newLastNamep;
4370 /* Check if the file already exists; if so return error */
4371 code = cm_Lookup(newDscp,newLastNamep,CM_FLAG_CHECKPATH,userp,&req,&tmpscp);
4372 if ((code != CM_ERROR_NOSUCHFILE) && (code != CM_ERROR_NOSUCHPATH) && (code != CM_ERROR_NOSUCHVOLUME) ) {
4373 osi_Log2(afsd_logp, " lookup returns %ld for [%s]", code,
4374 osi_LogSaveString(afsd_logp, newLastNamep));
4376 /* Check if the old and the new names differ only in case. If so return
4377 * success, else return CM_ERROR_EXISTS
4379 if (!code && oldDscp == newDscp && !stricmp(oldLastNamep, newLastNamep)) {
4381 /* This would be a success only if the old file is *as same as* the new file */
4382 code = cm_Lookup(oldDscp, oldLastNamep, CM_FLAG_CHECKPATH, userp, &req, &tmpscp2);
4384 if (tmpscp == tmpscp2)
4387 code = CM_ERROR_EXISTS;
4388 cm_ReleaseSCache(tmpscp2);
4391 code = CM_ERROR_NOSUCHFILE;
4394 /* file exist, do not rename, also fixes move */
4395 osi_Log0(afsd_logp, "Can't rename. Target already exists");
4396 code = CM_ERROR_EXISTS;
4400 cm_ReleaseSCache(tmpscp);
4401 cm_ReleaseSCache(newDscp);
4402 cm_ReleaseSCache(oldDscp);
4403 cm_ReleaseUser(userp);
4407 /* Now search the directory for the pattern, and do the appropriate rename when found */
4408 thyper.LowPart = 0; /* search dir from here */
4409 thyper.HighPart = 0;
4411 code = cm_ApplyDir(oldDscp, smb_RenameProc, &rock, &thyper, userp, &req, NULL);
4413 if (code == CM_ERROR_STOPNOW)
4416 code = CM_ERROR_NOSUCHFILE;
4418 /* Handle Change Notification */
4420 * Being lazy, not distinguishing between files and dirs in this
4421 * filter, since we'd have to do a lookup.
4423 filter = FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME;
4424 if (oldDscp == newDscp) {
4425 if (oldDscp->flags & CM_SCACHEFLAG_ANYWATCH)
4426 smb_NotifyChange(FILE_ACTION_RENAMED_OLD_NAME,
4427 filter, oldDscp, oldLastNamep,
4428 newLastNamep, TRUE);
4430 if (oldDscp->flags & CM_SCACHEFLAG_ANYWATCH)
4431 smb_NotifyChange(FILE_ACTION_RENAMED_OLD_NAME,
4432 filter, oldDscp, oldLastNamep,
4434 if (newDscp->flags & CM_SCACHEFLAG_ANYWATCH)
4435 smb_NotifyChange(FILE_ACTION_RENAMED_NEW_NAME,
4436 filter, newDscp, newLastNamep,
4441 cm_ReleaseSCache(tmpscp);
4442 cm_ReleaseUser(userp);
4443 cm_ReleaseSCache(oldDscp);
4444 cm_ReleaseSCache(newDscp);
4448 typedef struct smb_rmdirRock {
4452 char *maskp; /* pointer to the star pattern */
4457 int smb_RmdirProc(cm_scache_t *dscp, cm_dirEntry_t *dep, void *vrockp, osi_hyper_t *offp)
4460 smb_rmdirRock_t *rockp;
4465 rockp = (smb_rmdirRock_t *) vrockp;
4467 matchName = dep->name;
4468 if (rockp->flags & SMB_MASKFLAG_CASEFOLD)
4469 match = (cm_stricmp(matchName, rockp->maskp) == 0);
4471 match = (strcmp(matchName, rockp->maskp) == 0);
4473 && (rockp->flags & SMB_MASKFLAG_TILDE)
4474 && !cm_Is8Dot3(dep->name)) {
4475 cm_Gen8Dot3Name(dep, shortName, NULL);
4476 matchName = shortName;
4477 match = (cm_stricmp(matchName, rockp->maskp) == 0);
4480 osi_Log1(smb_logp, "Removing directory %s",
4481 osi_LogSaveString(smb_logp, matchName));
4482 code = cm_RemoveDir(dscp, dep->name, rockp->userp, rockp->reqp);
4483 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4484 smb_NotifyChange(FILE_ACTION_REMOVED,
4485 FILE_NOTIFY_CHANGE_DIR_NAME,
4486 dscp, dep->name, NULL, TRUE);
4495 long smb_ReceiveCoreRemoveDir(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4503 smb_rmdirRock_t rock;
4512 tp = smb_GetSMBData(inp, NULL);
4513 pathp = smb_ParseASCIIBlock(tp, &tp);
4515 spacep = inp->spacep;
4516 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
4518 userp = smb_GetUser(vcp, inp);
4520 caseFold = CM_FLAG_CASEFOLD;
4522 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
4523 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold | CM_FLAG_FOLLOW,
4524 userp, tidPathp, &req, &dscp);
4527 cm_ReleaseUser(userp);
4531 /* otherwise, scp points to the parent directory. */
4538 rock.maskp = lastNamep;
4539 rock.flags = ((strchr(rock.maskp, '~') != NULL) ? SMB_MASKFLAG_TILDE : 0);
4542 thyper.HighPart = 0;
4546 /* First do a case sensitive match, and if that fails, do a case insensitive match */
4547 code = cm_ApplyDir(dscp, smb_RmdirProc, &rock, &thyper, userp, &req, NULL);
4548 if (code == 0 && !rock.any) {
4550 thyper.HighPart = 0;
4551 rock.flags |= SMB_MASKFLAG_CASEFOLD;
4552 code = cm_ApplyDir(dscp, smb_RmdirProc, &rock, &thyper, userp, &req, NULL);
4555 cm_ReleaseUser(userp);
4557 cm_ReleaseSCache(dscp);
4559 if (code == 0 && !rock.any)
4560 code = CM_ERROR_NOSUCHFILE;
4564 long smb_ReceiveCoreFlush(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4574 fid = smb_GetSMBParm(inp, 0);
4576 osi_Log1(smb_logp, "SMB flush fid %d", fid);
4578 fid = smb_ChainFID(fid, inp);
4579 fidp = smb_FindFID(vcp, fid, 0);
4580 if (!fidp || (fidp->flags & SMB_FID_IOCTL)) {
4582 smb_ReleaseFID(fidp);
4583 return CM_ERROR_BADFD;
4586 userp = smb_GetUser(vcp, inp);
4588 lock_ObtainMutex(&fidp->mx);
4589 if (fidp->flags & SMB_FID_OPENWRITE)
4590 code = cm_FSync(fidp->scp, userp, &req);
4593 lock_ReleaseMutex(&fidp->mx);
4595 smb_ReleaseFID(fidp);
4597 cm_ReleaseUser(userp);
4602 struct smb_FullNameRock {
4608 int smb_FullNameProc(cm_scache_t *scp, cm_dirEntry_t *dep, void *rockp,
4612 struct smb_FullNameRock *vrockp;
4614 vrockp = (struct smb_FullNameRock *)rockp;
4616 if (!cm_Is8Dot3(dep->name)) {
4617 cm_Gen8Dot3Name(dep, shortName, NULL);
4619 if (cm_stricmp(shortName, vrockp->name) == 0) {
4620 vrockp->fullName = strdup(dep->name);
4621 return CM_ERROR_STOPNOW;
4624 if (cm_stricmp(dep->name, vrockp->name) == 0
4625 && ntohl(dep->fid.vnode) == vrockp->vnode->fid.vnode
4626 && ntohl(dep->fid.unique) == vrockp->vnode->fid.unique) {
4627 vrockp->fullName = strdup(dep->name);
4628 return CM_ERROR_STOPNOW;
4633 void smb_FullName(cm_scache_t *dscp, cm_scache_t *scp, char *pathp,
4634 char **newPathp, cm_user_t *userp, cm_req_t *reqp)
4636 struct smb_FullNameRock rock;
4642 code = cm_ApplyDir(dscp, smb_FullNameProc, &rock, NULL,
4644 if (code == CM_ERROR_STOPNOW)
4645 *newPathp = rock.fullName;
4647 *newPathp = strdup(pathp);
4650 long smb_ReceiveCoreClose(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
4661 fid = smb_GetSMBParm(inp, 0);
4662 dosTime = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
4664 osi_Log1(smb_logp, "SMB close fid %d", fid);
4666 fid = smb_ChainFID(fid, inp);
4667 fidp = smb_FindFID(vcp, fid, 0);
4669 return CM_ERROR_BADFD;
4672 userp = smb_GetUser(vcp, inp);
4674 lock_ObtainMutex(&fidp->mx);
4676 /* Don't jump the gun on an async raw write */
4677 while (fidp->raw_writers) {
4678 lock_ReleaseMutex(&fidp->mx);
4679 thrd_WaitForSingleObject_Event(fidp->raw_write_event, RAWTIMEOUT);
4680 lock_ObtainMutex(&fidp->mx);
4683 fidp->flags |= SMB_FID_DELETE;
4685 /* watch for ioctl closes, and read-only opens */
4686 if (fidp->scp != NULL
4687 && (fidp->flags & (SMB_FID_OPENWRITE | SMB_FID_DELONCLOSE))
4688 == SMB_FID_OPENWRITE) {
4689 if (dosTime != 0 && dosTime != -1) {
4690 fidp->scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
4691 /* This fixes defect 10958 */
4692 CompensateForSmbClientLastWriteTimeBugs(&dosTime);
4693 smb_UnixTimeFromDosUTime(&fidp->scp->clientModTime, dosTime);
4695 code = cm_FSync(fidp->scp, userp, &req);
4700 if (fidp->flags & SMB_FID_DELONCLOSE) {
4701 cm_scache_t *dscp = fidp->NTopen_dscp;
4702 char *pathp = fidp->NTopen_pathp;
4705 smb_FullName(dscp, fidp->scp, pathp, &fullPathp, userp, &req);
4706 if (fidp->scp->fileType == CM_SCACHETYPE_DIRECTORY) {
4707 code = cm_RemoveDir(dscp, fullPathp, userp, &req);
4708 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4709 smb_NotifyChange(FILE_ACTION_REMOVED,
4710 FILE_NOTIFY_CHANGE_DIR_NAME,
4711 dscp, fullPathp, NULL, TRUE);
4715 code = cm_Unlink(dscp, fullPathp, userp, &req);
4716 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
4717 smb_NotifyChange(FILE_ACTION_REMOVED,
4718 FILE_NOTIFY_CHANGE_FILE_NAME,
4719 dscp, fullPathp, NULL, TRUE);
4723 lock_ReleaseMutex(&fidp->mx);
4725 if (fidp->flags & SMB_FID_NTOPEN) {
4726 cm_ReleaseSCache(fidp->NTopen_dscp);
4727 free(fidp->NTopen_pathp);
4729 if (fidp->NTopen_wholepathp)
4730 free(fidp->NTopen_wholepathp);
4732 smb_ReleaseFID(fidp);
4733 cm_ReleaseUser(userp);
4738 * smb_ReadData -- common code for Read, Read And X, and Raw Read
4741 long smb_ReadData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4742 cm_user_t *userp, long *readp)
4744 long smb_ReadData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4745 cm_user_t *userp, long *readp, int dosflag)
4752 osi_hyper_t fileLength;
4754 osi_hyper_t lastByte;
4755 osi_hyper_t bufferOffset;
4756 long bufIndex, nbytes;
4766 lock_ObtainMutex(&fidp->mx);
4768 lock_ObtainMutex(&scp->mx);
4770 if (offset.HighPart == 0) {
4771 chunk = offset.LowPart >> cm_logChunkSize;
4772 if (chunk != fidp->curr_chunk) {
4773 fidp->prev_chunk = fidp->curr_chunk;
4774 fidp->curr_chunk = chunk;
4776 if (fidp->curr_chunk == fidp->prev_chunk + 1)
4780 /* start by looking up the file's end */
4781 code = cm_SyncOp(scp, NULL, userp, &req, 0,
4782 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
4783 if (code) goto done;
4785 /* now we have the entry locked, look up the length */
4786 fileLength = scp->length;
4788 /* adjust count down so that it won't go past EOF */
4789 thyper.LowPart = count;
4790 thyper.HighPart = 0;
4791 thyper = LargeIntegerAdd(offset, thyper); /* where read should end */
4793 if (LargeIntegerGreaterThan(thyper, fileLength)) {
4794 /* we'd read past EOF, so just stop at fileLength bytes.
4795 * Start by computing how many bytes remain in the file.
4797 thyper = LargeIntegerSubtract(fileLength, offset);
4799 /* if we are past EOF, read 0 bytes */
4800 if (LargeIntegerLessThanZero(thyper))
4803 count = thyper.LowPart;
4808 /* now, copy the data one buffer at a time,
4809 * until we've filled the request packet
4812 /* if we've copied all the data requested, we're done */
4813 if (count <= 0) break;
4815 /* otherwise, load up a buffer of data */
4816 thyper.HighPart = offset.HighPart;
4817 thyper.LowPart = offset.LowPart & ~(buf_bufferSize-1);
4818 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
4821 buf_Release(bufferp);
4824 lock_ReleaseMutex(&scp->mx);
4826 lock_ObtainRead(&scp->bufCreateLock);
4827 code = buf_Get(scp, &thyper, &bufferp);
4828 lock_ReleaseRead(&scp->bufCreateLock);
4830 lock_ObtainMutex(&scp->mx);
4831 if (code) goto done;
4832 bufferOffset = thyper;
4834 /* now get the data in the cache */
4836 code = cm_SyncOp(scp, bufferp, userp, &req, 0,
4837 CM_SCACHESYNC_NEEDCALLBACK
4838 | CM_SCACHESYNC_READ);
4839 if (code) goto done;
4841 if (cm_HaveBuffer(scp, bufferp, 0)) break;
4843 /* otherwise, load the buffer and try again */
4844 code = cm_GetBuffer(scp, bufferp, NULL, userp, &req);
4848 buf_Release(bufferp);
4852 } /* if (wrong buffer) ... */
4854 /* now we have the right buffer loaded. Copy out the
4855 * data from here to the user's buffer.
4857 bufIndex = offset.LowPart & (buf_bufferSize - 1);
4859 /* and figure out how many bytes we want from this buffer */
4860 nbytes = buf_bufferSize - bufIndex; /* what remains in buffer */
4861 if (nbytes > count) nbytes = count; /* don't go past EOF */
4863 /* now copy the data */
4866 dosmemput(bufferp->datap + bufIndex, nbytes, (dos_ptr)op);
4869 memcpy(op, bufferp->datap + bufIndex, nbytes);
4871 /* adjust counters, pointers, etc. */
4874 thyper.LowPart = nbytes;
4875 thyper.HighPart = 0;
4876 offset = LargeIntegerAdd(thyper, offset);
4880 lock_ReleaseMutex(&scp->mx);
4881 lock_ReleaseMutex(&fidp->mx);
4883 buf_Release(bufferp);
4885 if (code == 0 && sequential)
4886 cm_ConsiderPrefetch(scp, &lastByte, userp, &req);
4892 * smb_WriteData -- common code for Write and Raw Write
4895 long smb_WriteData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4896 cm_user_t *userp, long *writtenp)
4898 long smb_WriteData(smb_fid_t *fidp, osi_hyper_t *offsetp, long count, char *op,
4899 cm_user_t *userp, long *writtenp, int dosflag)
4906 osi_hyper_t fileLength; /* file's length at start of write */
4907 osi_hyper_t minLength; /* don't read past this */
4908 long nbytes; /* # of bytes to transfer this iteration */
4910 osi_hyper_t thyper; /* hyper tmp variable */
4911 osi_hyper_t bufferOffset;
4912 long bufIndex; /* index in buffer where our data is */
4914 osi_hyper_t writeBackOffset; /* offset of region to write back when
4925 lock_ObtainMutex(&fidp->mx);
4927 lock_ObtainMutex(&scp->mx);
4929 /* start by looking up the file's end */
4930 code = cm_SyncOp(scp, NULL, userp, &req, 0,
4931 CM_SCACHESYNC_NEEDCALLBACK
4932 | CM_SCACHESYNC_SETSTATUS
4933 | CM_SCACHESYNC_GETSTATUS);
4937 /* make sure we have a writable FD */
4938 if (!(fidp->flags & SMB_FID_OPENWRITE)) {
4939 code = CM_ERROR_BADFDOP;
4943 /* now we have the entry locked, look up the length */
4944 fileLength = scp->length;
4945 minLength = fileLength;
4946 if (LargeIntegerGreaterThan(minLength, scp->serverLength))
4947 minLength = scp->serverLength;
4949 /* adjust file length if we extend past EOF */
4950 thyper.LowPart = count;
4951 thyper.HighPart = 0;
4952 thyper = LargeIntegerAdd(offset, thyper); /* where write should end */
4953 if (LargeIntegerGreaterThan(thyper, fileLength)) {
4954 /* we'd write past EOF, so extend the file */
4955 scp->mask |= CM_SCACHEMASK_LENGTH;
4956 scp->length = thyper;
4957 filter |= (FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE);
4959 filter |= FILE_NOTIFY_CHANGE_LAST_WRITE;
4961 /* now, if the new position (thyper) and the old (offset) are in
4962 * different storeback windows, remember to store back the previous
4963 * storeback window when we're done with the write.
4965 if ((thyper.LowPart & (-cm_chunkSize)) !=
4966 (offset.LowPart & (-cm_chunkSize))) {
4967 /* they're different */
4969 writeBackOffset.HighPart = offset.HighPart;
4970 writeBackOffset.LowPart = offset.LowPart & (-cm_chunkSize);
4975 /* now, copy the data one buffer at a time, until we've filled the
4978 /* if we've copied all the data requested, we're done */
4979 if (count <= 0) break;
4981 /* handle over quota or out of space */
4982 if (scp->flags & (CM_SCACHEFLAG_OVERQUOTA | CM_SCACHEFLAG_OUTOFSPACE)) {
4983 *writtenp = written;
4987 /* otherwise, load up a buffer of data */
4988 thyper.HighPart = offset.HighPart;
4989 thyper.LowPart = offset.LowPart & ~(buf_bufferSize-1);
4990 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
4993 lock_ReleaseMutex(&bufferp->mx);
4994 buf_Release(bufferp);
4997 lock_ReleaseMutex(&scp->mx);
4999 lock_ObtainRead(&scp->bufCreateLock);
5000 code = buf_Get(scp, &thyper, &bufferp);
5001 lock_ReleaseRead(&scp->bufCreateLock);
5003 lock_ObtainMutex(&bufferp->mx);
5004 lock_ObtainMutex(&scp->mx);
5005 if (code) goto done;
5007 bufferOffset = thyper;
5009 /* now get the data in the cache */
5011 code = cm_SyncOp(scp, bufferp, userp, &req, 0,
5012 CM_SCACHESYNC_NEEDCALLBACK
5013 | CM_SCACHESYNC_WRITE
5014 | CM_SCACHESYNC_BUFLOCKED);
5018 /* If we're overwriting the entire buffer, or
5019 * if we're writing at or past EOF, mark the
5020 * buffer as current so we don't call
5021 * cm_GetBuffer. This skips the fetch from the
5022 * server in those cases where we're going to
5023 * obliterate all the data in the buffer anyway,
5024 * or in those cases where there is no useful
5025 * data at the server to start with.
5027 * Use minLength instead of scp->length, since
5028 * the latter has already been updated by this
5031 if (LargeIntegerGreaterThanOrEqualTo(
5032 bufferp->offset, minLength)
5033 || LargeIntegerEqualTo(offset, bufferp->offset)
5034 && (count >= buf_bufferSize
5035 || LargeIntegerGreaterThanOrEqualTo(
5036 LargeIntegerAdd(offset,
5037 ConvertLongToLargeInteger(count)),
5039 if (count < buf_bufferSize
5040 && bufferp->dataVersion == -1)
5041 memset(bufferp->datap, 0,
5043 bufferp->dataVersion = scp->dataVersion;
5046 if (cm_HaveBuffer(scp, bufferp, 1)) break;
5048 /* otherwise, load the buffer and try again */
5049 lock_ReleaseMutex(&bufferp->mx);
5050 code = cm_GetBuffer(scp, bufferp, NULL, userp,
5052 lock_ReleaseMutex(&scp->mx);
5053 lock_ObtainMutex(&bufferp->mx);
5054 lock_ObtainMutex(&scp->mx);
5058 lock_ReleaseMutex(&bufferp->mx);
5059 buf_Release(bufferp);
5063 } /* if (wrong buffer) ... */
5065 /* now we have the right buffer loaded. Copy out the
5066 * data from here to the user's buffer.
5068 bufIndex = offset.LowPart & (buf_bufferSize - 1);
5070 /* and figure out how many bytes we want from this buffer */
5071 nbytes = buf_bufferSize - bufIndex; /* what remains in buffer */
5073 nbytes = count; /* don't go past end of request */
5075 /* now copy the data */
5078 dosmemget((dos_ptr)op, nbytes, bufferp->datap + bufIndex);
5081 memcpy(bufferp->datap + bufIndex, op, nbytes);
5082 buf_SetDirty(bufferp);
5084 /* and record the last writer */
5085 if (bufferp->userp != userp) {
5088 cm_ReleaseUser(bufferp->userp);
5089 bufferp->userp = userp;
5092 /* adjust counters, pointers, etc. */
5096 thyper.LowPart = nbytes;
5097 thyper.HighPart = 0;
5098 offset = LargeIntegerAdd(thyper, offset);
5102 lock_ReleaseMutex(&scp->mx);
5103 lock_ReleaseMutex(&fidp->mx);
5105 lock_ReleaseMutex(&bufferp->mx);
5106 buf_Release(bufferp);
5109 if (code == 0 && filter != 0 && (fidp->flags & SMB_FID_NTOPEN)
5110 && (fidp->NTopen_dscp->flags & CM_SCACHEFLAG_ANYWATCH)) {
5111 smb_NotifyChange(FILE_ACTION_MODIFIED, filter,
5112 fidp->NTopen_dscp, fidp->NTopen_pathp,
5116 if (code == 0 && doWriteBack) {
5117 lock_ObtainMutex(&scp->mx);
5118 cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_ASYNCSTORE);
5119 lock_ReleaseMutex(&scp->mx);
5120 cm_QueueBKGRequest(scp, cm_BkgStore, writeBackOffset.LowPart,
5121 writeBackOffset.HighPart, cm_chunkSize, 0, userp);
5127 long smb_ReceiveCoreWrite(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5130 long count, written = 0;
5135 cm_attr_t truncAttr; /* attribute struct used for truncating file */
5137 int inDataBlockCount;
5139 fd = smb_GetSMBParm(inp, 0);
5140 count = smb_GetSMBParm(inp, 1);
5141 offset.HighPart = 0; /* too bad */
5142 offset.LowPart = smb_GetSMBParm(inp, 2) | (smb_GetSMBParm(inp, 3) << 16);
5144 op = smb_GetSMBData(inp, NULL);
5145 op = smb_ParseDataBlock(op, NULL, &inDataBlockCount);
5147 osi_Log3(smb_logp, "smb_ReceiveCoreWrite fd %d, off 0x%x, size 0x%x",
5148 fd, offset.LowPart, count);
5150 fd = smb_ChainFID(fd, inp);
5151 fidp = smb_FindFID(vcp, fd, 0);
5153 return CM_ERROR_BADFD;
5156 if (fidp->flags & SMB_FID_IOCTL)
5157 return smb_IoctlWrite(fidp, vcp, inp, outp);
5159 userp = smb_GetUser(vcp, inp);
5161 /* special case: 0 bytes transferred means truncate to this position */
5167 truncAttr.mask = CM_ATTRMASK_LENGTH;
5168 truncAttr.length.LowPart = offset.LowPart;
5169 truncAttr.length.HighPart = 0;
5170 lock_ObtainMutex(&fidp->mx);
5171 code = cm_SetAttr(fidp->scp, &truncAttr, userp, &req);
5172 lock_ReleaseMutex(&fidp->mx);
5173 smb_SetSMBParm(outp, 0, /* count */ 0);
5174 smb_SetSMBDataLength(outp, 0);
5175 fidp->flags |= SMB_FID_LENGTHSETDONE;
5180 * Work around bug in NT client
5182 * When copying a file, the NT client should first copy the data,
5183 * then copy the last write time. But sometimes the NT client does
5184 * these in the wrong order, so the data copies would inadvertently
5185 * cause the last write time to be overwritten. We try to detect this,
5186 * and don't set client mod time if we think that would go against the
5189 if ((fidp->flags & SMB_FID_MTIMESETDONE) != SMB_FID_MTIMESETDONE) {
5190 fidp->scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
5191 fidp->scp->clientModTime = time(NULL);
5195 code = smb_WriteData(fidp, &offset, count, op, userp, &written);
5197 code = smb_WriteData(fidp, &offset, count, op, userp, &written, FALSE);
5199 if (code == 0 && written < count)
5200 code = CM_ERROR_PARTIALWRITE;
5202 /* set the packet data length to 3 bytes for the data block header,
5203 * plus the size of the data.
5205 smb_SetSMBParm(outp, 0, written);
5206 smb_SetSMBDataLength(outp, 0);
5209 smb_ReleaseFID(fidp);
5210 cm_ReleaseUser(userp);
5215 void smb_CompleteWriteRaw(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp,
5216 NCB *ncbp, raw_write_cont_t *rwcp)
5229 fd = smb_GetSMBParm(inp, 0);
5230 fidp = smb_FindFID(vcp, fd, 0);
5232 osi_Log2(smb_logp, "Completing Raw Write offset %x count %x",
5233 rwcp->offset.LowPart, rwcp->count);
5235 userp = smb_GetUser(vcp, inp);
5239 code = smb_WriteData(fidp, &rwcp->offset, rwcp->count, rawBuf, userp,
5242 rawBuf = (dos_ptr) rwcp->buf;
5243 code = smb_WriteData(fidp, &rwcp->offset, rwcp->count,
5244 (unsigned char *) rawBuf, userp,
5248 if (rwcp->writeMode & 0x1) { /* synchronous */
5251 smb_FormatResponsePacket(vcp, inp, outp);
5252 op = (smb_t *) outp;
5253 op->com = 0x20; /* SMB_COM_WRITE_COMPLETE */
5254 smb_SetSMBParm(outp, 0, written + rwcp->alreadyWritten);
5255 smb_SetSMBDataLength(outp, 0);
5256 smb_SendPacket(vcp, outp);
5257 smb_FreePacket(outp);
5259 else { /* asynchronous */
5260 lock_ObtainMutex(&fidp->mx);
5261 fidp->raw_writers--;
5262 if (fidp->raw_writers == 0)
5263 thrd_SetEvent(fidp->raw_write_event);
5264 lock_ReleaseMutex(&fidp->mx);
5267 /* Give back raw buffer */
5268 lock_ObtainMutex(&smb_RawBufLock);
5270 *((char **)rawBuf) = smb_RawBufs;
5272 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
5274 smb_RawBufs = rawBuf;
5275 lock_ReleaseMutex(&smb_RawBufLock);
5277 smb_ReleaseFID(fidp);
5278 cm_ReleaseUser(userp);
5281 long smb_ReceiveCoreWriteRawDummy(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5286 long smb_ReceiveCoreWriteRaw(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp, raw_write_cont_t *rwcp)
5289 long count, written = 0;
5296 unsigned short writeMode;
5303 fd = smb_GetSMBParm(inp, 0);
5304 totalCount = smb_GetSMBParm(inp, 1);
5305 count = smb_GetSMBParm(inp, 10);
5306 offset.HighPart = 0; /* too bad */
5307 offset.LowPart = smb_GetSMBParm(inp, 3) | (smb_GetSMBParm(inp, 4) << 16);
5308 writeMode = smb_GetSMBParm(inp, 7);
5310 op = (char *) inp->data;
5311 op += smb_GetSMBParm(inp, 11);
5314 "smb_ReceiveCoreWriteRaw fd %d, off 0x%x, size 0x%x, WriteMode 0x%x",
5315 fd, offset.LowPart, count, writeMode);
5317 fd = smb_ChainFID(fd, inp);
5318 fidp = smb_FindFID(vcp, fd, 0);
5320 return CM_ERROR_BADFD;
5323 userp = smb_GetUser(vcp, inp);
5326 * Work around bug in NT client
5328 * When copying a file, the NT client should first copy the data,
5329 * then copy the last write time. But sometimes the NT client does
5330 * these in the wrong order, so the data copies would inadvertently
5331 * cause the last write time to be overwritten. We try to detect this,
5332 * and don't set client mod time if we think that would go against the
5335 if ((fidp->flags & SMB_FID_LOOKSLIKECOPY) != SMB_FID_LOOKSLIKECOPY) {
5336 fidp->scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
5337 fidp->scp->clientModTime = time(NULL);
5341 code = smb_WriteData(fidp, &offset, count, op, userp, &written);
5343 code = smb_WriteData(fidp, &offset, count, op, userp, &written, FALSE);
5345 if (code == 0 && written < count)
5346 code = CM_ERROR_PARTIALWRITE;
5348 /* Get a raw buffer */
5351 lock_ObtainMutex(&smb_RawBufLock);
5353 /* Get a raw buf, from head of list */
5354 rawBuf = smb_RawBufs;
5356 smb_RawBufs = *(char **)smb_RawBufs;
5358 smb_RawBufs = _farpeekl(_dos_ds, smb_RawBufs);
5362 code = CM_ERROR_USESTD;
5364 lock_ReleaseMutex(&smb_RawBufLock);
5367 /* Don't allow a premature Close */
5368 if (code == 0 && (writeMode & 1) == 0) {
5369 lock_ObtainMutex(&fidp->mx);
5370 fidp->raw_writers++;
5371 thrd_ResetEvent(fidp->raw_write_event);
5372 lock_ReleaseMutex(&fidp->mx);
5375 smb_ReleaseFID(fidp);
5376 cm_ReleaseUser(userp);
5379 smb_SetSMBParm(outp, 0, written);
5380 smb_SetSMBDataLength(outp, 0);
5381 ((smb_t *)outp)->com = 0x20; /* SMB_COM_WRITE_COMPLETE */
5388 rwcp->offset.HighPart = 0;
5389 rwcp->offset.LowPart = offset.LowPart + count;
5390 rwcp->count = totalCount - count;
5391 rwcp->writeMode = writeMode;
5392 rwcp->alreadyWritten = written;
5394 /* set the packet data length to 3 bytes for the data block header,
5395 * plus the size of the data.
5397 smb_SetSMBParm(outp, 0, 0xffff);
5398 smb_SetSMBDataLength(outp, 0);
5403 long smb_ReceiveCoreRead(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5406 long count, finalCount;
5413 fd = smb_GetSMBParm(inp, 0);
5414 count = smb_GetSMBParm(inp, 1);
5415 offset.HighPart = 0; /* too bad */
5416 offset.LowPart = smb_GetSMBParm(inp, 2) | (smb_GetSMBParm(inp, 3) << 16);
5418 osi_Log3(smb_logp, "smb_ReceiveCoreRead fd %d, off 0x%x, size 0x%x",
5419 fd, offset.LowPart, count);
5421 fd = smb_ChainFID(fd, inp);
5422 fidp = smb_FindFID(vcp, fd, 0);
5424 return CM_ERROR_BADFD;
5427 if (fidp->flags & SMB_FID_IOCTL) {
5428 return smb_IoctlRead(fidp, vcp, inp, outp);
5431 userp = smb_GetUser(vcp, inp);
5433 /* remember this for final results */
5434 smb_SetSMBParm(outp, 0, count);
5435 smb_SetSMBParm(outp, 1, 0);
5436 smb_SetSMBParm(outp, 2, 0);
5437 smb_SetSMBParm(outp, 3, 0);
5438 smb_SetSMBParm(outp, 4, 0);
5440 /* set the packet data length to 3 bytes for the data block header,
5441 * plus the size of the data.
5443 smb_SetSMBDataLength(outp, count+3);
5445 /* get op ptr after putting in the parms, since otherwise we don't
5446 * know where the data really is.
5448 op = smb_GetSMBData(outp, NULL);
5450 /* now emit the data block header: 1 byte of type and 2 bytes of length */
5451 *op++ = 1; /* data block marker */
5452 *op++ = (unsigned char) (count & 0xff);
5453 *op++ = (unsigned char) ((count >> 8) & 0xff);
5456 code = smb_ReadData(fidp, &offset, count, op, userp, &finalCount);
5458 code = smb_ReadData(fidp, &offset, count, op, userp, &finalCount, FALSE);
5461 /* fix some things up */
5462 smb_SetSMBParm(outp, 0, finalCount);
5463 smb_SetSMBDataLength(outp, finalCount+3);
5465 smb_ReleaseFID(fidp);
5467 cm_ReleaseUser(userp);
5471 long smb_ReceiveCoreMakeDir(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5478 cm_scache_t *dscp; /* dir we're dealing with */
5479 cm_scache_t *scp; /* file we're creating */
5481 int initialModeBits;
5491 /* compute initial mode bits based on read-only flag in attributes */
5492 initialModeBits = 0777;
5494 tp = smb_GetSMBData(inp, NULL);
5495 pathp = smb_ParseASCIIBlock(tp, &tp);
5497 if (strcmp(pathp, "\\") == 0)
5498 return CM_ERROR_EXISTS;
5500 spacep = inp->spacep;
5501 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
5503 userp = smb_GetUser(vcp, inp);
5505 caseFold = CM_FLAG_CASEFOLD;
5507 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
5509 code = cm_NameI(cm_rootSCachep, spacep->data,
5510 caseFold | CM_FLAG_FOLLOW | CM_FLAG_CHECKPATH,
5511 userp, tidPathp, &req, &dscp);
5514 cm_ReleaseUser(userp);
5518 /* otherwise, scp points to the parent directory. Do a lookup, and
5519 * fail if we find it. Otherwise, we do the create.
5525 code = cm_Lookup(dscp, lastNamep, 0, userp, &req, &scp);
5526 if (scp) cm_ReleaseSCache(scp);
5527 if (code != CM_ERROR_NOSUCHFILE) {
5528 if (code == 0) code = CM_ERROR_EXISTS;
5529 cm_ReleaseSCache(dscp);
5530 cm_ReleaseUser(userp);
5534 setAttr.mask = CM_ATTRMASK_CLIENTMODTIME;
5535 setAttr.clientModTime = time(NULL);
5536 code = cm_MakeDir(dscp, lastNamep, 0, &setAttr, userp, &req);
5537 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
5538 smb_NotifyChange(FILE_ACTION_ADDED,
5539 FILE_NOTIFY_CHANGE_DIR_NAME,
5540 dscp, lastNamep, NULL, TRUE);
5542 /* we don't need this any longer */
5543 cm_ReleaseSCache(dscp);
5546 /* something went wrong creating or truncating the file */
5547 cm_ReleaseUser(userp);
5551 /* otherwise we succeeded */
5552 smb_SetSMBDataLength(outp, 0);
5553 cm_ReleaseUser(userp);
5558 BOOL smb_IsLegalFilename(char *filename)
5561 * Find the longest substring of filename that does not contain
5562 * any of the chars in illegalChars. If that substring is less
5563 * than the length of the whole string, then one or more of the
5564 * illegal chars is in filename.
5566 if (strcspn(filename, illegalChars) < strlen(filename))
5572 long smb_ReceiveCoreCreate(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5580 cm_scache_t *dscp; /* dir we're dealing with */
5581 cm_scache_t *scp; /* file we're creating */
5583 int initialModeBits;
5595 excl = (inp->inCom == 0x03)? 0 : 1;
5597 attributes = smb_GetSMBParm(inp, 0);
5598 dosTime = smb_GetSMBParm(inp, 1) | (smb_GetSMBParm(inp, 2) << 16);
5600 /* compute initial mode bits based on read-only flag in attributes */
5601 initialModeBits = 0666;
5602 if (attributes & 1) initialModeBits &= ~0222;
5604 tp = smb_GetSMBData(inp, NULL);
5605 pathp = smb_ParseASCIIBlock(tp, &tp);
5607 spacep = inp->spacep;
5608 smb_StripLastComponent(spacep->data, &lastNamep, pathp);
5610 userp = smb_GetUser(vcp, inp);
5612 caseFold = CM_FLAG_CASEFOLD;
5614 tidPathp = smb_GetTIDPath(vcp, ((smb_t *)inp)->tid);
5615 code = cm_NameI(cm_rootSCachep, spacep->data, caseFold | CM_FLAG_FOLLOW,
5616 userp, tidPathp, &req, &dscp);
5619 cm_ReleaseUser(userp);
5623 /* otherwise, scp points to the parent directory. Do a lookup, and
5624 * truncate the file if we find it, otherwise we create the file.
5626 if (!lastNamep) lastNamep = pathp;
5629 if (!smb_IsLegalFilename(lastNamep))
5630 return CM_ERROR_BADNTFILENAME;
5632 osi_Log1(smb_logp, "SMB receive create [%s]", osi_LogSaveString( smb_logp, pathp ));
5633 #ifdef DEBUG_VERBOSE
5636 hexp = osi_HexifyString( lastNamep );
5637 DEBUG_EVENT2("AFS", "CoreCreate H[%s] A[%s]", hexp, lastNamep );
5642 code = cm_Lookup(dscp, lastNamep, 0, userp, &req, &scp);
5643 if (code && code != CM_ERROR_NOSUCHFILE) {
5644 cm_ReleaseSCache(dscp);
5645 cm_ReleaseUser(userp);
5649 /* if we get here, if code is 0, the file exists and is represented by
5650 * scp. Otherwise, we have to create it.
5654 /* oops, file shouldn't be there */
5655 cm_ReleaseSCache(dscp);
5656 cm_ReleaseSCache(scp);
5657 cm_ReleaseUser(userp);
5658 return CM_ERROR_EXISTS;
5661 setAttr.mask = CM_ATTRMASK_LENGTH;
5662 setAttr.length.LowPart = 0;
5663 setAttr.length.HighPart = 0;
5664 code = cm_SetAttr(scp, &setAttr, userp, &req);
5667 setAttr.mask = CM_ATTRMASK_CLIENTMODTIME;
5668 smb_UnixTimeFromDosUTime(&setAttr.clientModTime, dosTime);
5669 code = cm_Create(dscp, lastNamep, 0, &setAttr, &scp, userp,
5671 if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
5672 smb_NotifyChange(FILE_ACTION_ADDED,
5673 FILE_NOTIFY_CHANGE_FILE_NAME,
5674 dscp, lastNamep, NULL, TRUE);
5675 if (!excl && code == CM_ERROR_EXISTS) {
5676 /* not an exclusive create, and someone else tried
5677 * creating it already, then we open it anyway. We
5678 * don't bother retrying after this, since if this next
5679 * fails, that means that the file was deleted after
5680 * we started this call.
5682 code = cm_Lookup(dscp, lastNamep, caseFold, userp,
5685 setAttr.mask = CM_ATTRMASK_LENGTH;
5686 setAttr.length.LowPart = 0;
5687 setAttr.length.HighPart = 0;
5688 code = cm_SetAttr(scp, &setAttr, userp, &req);
5693 /* we don't need this any longer */
5694 cm_ReleaseSCache(dscp);
5697 /* something went wrong creating or truncating the file */
5698 if (scp) cm_ReleaseSCache(scp);
5699 cm_ReleaseUser(userp);
5703 /* make sure we only open files */
5704 if (scp->fileType != CM_SCACHETYPE_FILE) {
5705 cm_ReleaseSCache(scp);
5706 cm_ReleaseUser(userp);
5707 return CM_ERROR_ISDIR;
5710 /* now all we have to do is open the file itself */
5711 fidp = smb_FindFID(vcp, 0, SMB_FLAG_CREATE);
5714 /* save a pointer to the vnode */
5717 /* always create it open for read/write */
5718 fidp->flags |= (SMB_FID_OPENREAD | SMB_FID_OPENWRITE);
5720 smb_ReleaseFID(fidp);
5722 smb_SetSMBParm(outp, 0, fidp->fid);
5723 smb_SetSMBDataLength(outp, 0);
5725 cm_Open(scp, 0, userp);
5727 cm_ReleaseUser(userp);
5728 /* leave scp held since we put it in fidp->scp */
5732 long smb_ReceiveCoreSeek(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp)
5745 fd = smb_GetSMBParm(inp, 0);
5746 whence = smb_GetSMBParm(inp, 1);
5747 offset = smb_GetSMBParm(inp, 2) | (smb_GetSMBParm(inp, 3) << 16);
5749 /* try to find the file descriptor */
5750 fd = smb_ChainFID(fd, inp);
5751 fidp = smb_FindFID(vcp, fd, 0);
5752 if (!fidp || (fidp->flags & SMB_FID_IOCTL)) {
5753 return CM_ERROR_BADFD;
5756 userp = smb_GetUser(vcp, inp);
5758 lock_ObtainMutex(&fidp->mx);
5760 lock_ObtainMutex(&scp->mx);
5761 code = cm_SyncOp(scp, NULL, userp, &req, 0,
5762 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
5765 /* offset from current offset */
5766 offset += fidp->offset;
5768 else if (whence == 2) {
5769 /* offset from current EOF */
5770 offset += scp->length.LowPart;
5772 fidp->offset = offset;
5773 smb_SetSMBParm(outp, 0, offset & 0xffff);
5774 smb_SetSMBParm(outp, 1, (offset>>16) & 0xffff);
5775 smb_SetSMBDataLength(outp, 0);
5777 lock_ReleaseMutex(&scp->mx);
5778 lock_ReleaseMutex(&fidp->mx);
5779 smb_ReleaseFID(fidp);
5780 cm_ReleaseUser(userp);
5784 /* dispatch all of the requests received in a packet. Due to chaining, this may
5785 * be more than one request.
5787 void smb_DispatchPacket(smb_vc_t *vcp, smb_packet_t *inp, smb_packet_t *outp,
5788 NCB *ncbp, raw_write_cont_t *rwcp)
5792 unsigned long code = 0;
5793 unsigned char *outWctp;
5794 int nparms; /* # of bytes of parameters */
5796 int nbytes; /* bytes of data, excluding count */
5799 unsigned short errCode;
5800 unsigned long NTStatus;
5802 unsigned char errClass;
5803 unsigned int oldGen;
5804 DWORD oldTime, newTime;
5806 /* get easy pointer to the data */
5807 smbp = (smb_t *) inp->data;
5809 if (!(outp->flags & SMB_PACKETFLAG_SUSPENDED)) {
5810 /* setup the basic parms for the initial request in the packet */
5811 inp->inCom = smbp->com;
5812 inp->wctp = &smbp->wct;
5814 inp->ncb_length = ncbp->ncb_length;
5819 if (ncbp->ncb_length < offsetof(struct smb, vdata)) {
5820 /* log it and discard it */
5825 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
5826 sprintf(s, "SMB message too short, len %d", ncbp->ncb_length);
5828 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1007, NULL,
5829 1, ncbp->ncb_length, ptbuf, inp);
5830 DeregisterEventSource(h);
5832 osi_Log1(smb_logp, "SMB message too short, len %d",
5839 /* We are an ongoing op */
5840 thrd_Increment(&ongoingOps);
5842 /* set up response packet for receiving output */
5843 if (!(outp->flags & SMB_PACKETFLAG_SUSPENDED))
5844 smb_FormatResponsePacket(vcp, inp, outp);
5845 outWctp = outp->wctp;
5847 /* Remember session generation number and time */
5848 oldGen = sessionGen;
5849 oldTime = GetCurrentTime();
5851 while(inp->inCom != 0xff) {
5852 dp = &smb_dispatchTable[inp->inCom];
5854 if (outp->flags & SMB_PACKETFLAG_SUSPENDED) {
5855 outp->flags &= ~SMB_PACKETFLAG_SUSPENDED;
5856 code = outp->resumeCode;
5860 /* process each request in the packet; inCom, wctp and inCount
5861 * are already set up.
5863 osi_Log2(smb_logp, "SMB received op 0x%x lsn %d", inp->inCom,
5866 /* now do the dispatch */
5867 /* start by formatting the response record a little, as a default */
5868 if (dp->flags & SMB_DISPATCHFLAG_CHAINED) {
5870 outWctp[1] = 0xff; /* no operation */
5871 outWctp[2] = 0; /* padding */
5876 /* not a chained request, this is a more reasonable default */
5877 outWctp[0] = 0; /* wct of zero */
5878 outWctp[1] = 0; /* and bcc (word) of zero */
5882 /* once set, stays set. Doesn't matter, since we never chain
5883 * "no response" calls.
5885 if (dp->flags & SMB_DISPATCHFLAG_NORESPONSE)
5889 /* we have a recognized operation */
5891 if (inp->inCom == 0x1d)
5893 code = smb_ReceiveCoreWriteRaw (vcp, inp, outp,
5896 osi_LogEvent("AFS Dispatch %s",(myCrt_Dispatch(inp->inCom)),"vcp[%x] lana[%d] lsn[%d]",(int)vcp,vcp->lana,vcp->lsn);
5897 osi_Log4(smb_logp,"Dispatch %s vcp[%x] lana[%d] lsn[%d]",(myCrt_Dispatch(inp->inCom)),vcp,vcp->lana,vcp->lsn);
5898 code = (*(dp->procp)) (vcp, inp, outp);
5899 osi_LogEvent("AFS Dispatch return",NULL,"Code[%d]",(code==0)?0:code-CM_ERROR_BASE);
5900 osi_Log1(smb_logp,"Dispatch return code[%d]",(code==0)?0:code-CM_ERROR_BASE);
5903 if (oldGen != sessionGen) {
5908 newTime = GetCurrentTime();
5909 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
5910 sprintf(s, "Pkt straddled session startup, took %d ms, ncb length %d",
5911 newTime - oldTime, ncbp->ncb_length);
5913 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0,
5914 1005, NULL, 1, ncbp->ncb_length, ptbuf, smbp);
5915 DeregisterEventSource(h);
5917 osi_Log1(smb_logp, "Pkt straddled session startup, "
5918 "ncb length %d", ncbp->ncb_length);
5923 /* bad opcode, fail the request, after displaying it */
5926 #endif /* NOTSERVICE */
5930 sprintf(tbuffer, "Received bad SMB req 0x%x", inp->inCom);
5931 code = (*smb_MBfunc)(NULL, tbuffer, "Cancel: don't show again",
5932 MB_OKCANCEL|MB_SERVICE_NOTIFICATION);
5933 if (code == IDCANCEL) showErrors = 0;
5936 code = CM_ERROR_BADOP;
5939 /* catastrophic failure: log as much as possible */
5940 if (code == CM_ERROR_BADSMB) {
5947 "Invalid SMB, ncb_length %d",
5950 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
5951 sprintf(s, "Invalid SMB message, length %d",
5954 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1002, NULL,
5955 1, ncbp->ncb_length, ptbuf, smbp);
5956 DeregisterEventSource(h);
5959 #endif /* NOTSERVICE */
5961 osi_Log1(smb_logp, "Invalid SMB message, length %d",
5965 code = CM_ERROR_INVAL;
5968 if (outp->flags & SMB_PACKETFLAG_NOSEND) {
5969 thrd_Decrement(&ongoingOps);
5974 /* now, if we failed, turn the current response into an empty
5975 * one, and fill in the response packet's error code.
5978 if (vcp->flags & SMB_VCFLAG_STATUS32) {
5979 smb_MapNTError(code, &NTStatus);
5980 outWctp = outp->wctp;
5981 smbp = (smb_t *) &outp->data;
5982 if (code != CM_ERROR_PARTIALWRITE
5983 && code != CM_ERROR_BUFFERTOOSMALL
5984 && code != CM_ERROR_GSSCONTINUE) {
5985 /* nuke wct and bcc. For a partial
5986 * write or an in-process authentication handshake,
5987 * assume they're OK.
5993 smbp->rcls = (unsigned char) (NTStatus & 0xff);
5994 smbp->reh = (unsigned char) ((NTStatus >> 8) & 0xff);
5995 smbp->errLow = (unsigned char) ((NTStatus >> 16) & 0xff);
5996 smbp->errHigh = (unsigned char) ((NTStatus >> 24) & 0xff);
5997 smbp->flg2 |= 0x4000;
6001 smb_MapCoreError(code, vcp, &errCode, &errClass);
6002 outWctp = outp->wctp;
6003 smbp = (smb_t *) &outp->data;
6004 if (code != CM_ERROR_PARTIALWRITE) {
6005 /* nuke wct and bcc. For a partial
6006 * write, assume they're OK.
6012 smbp->errLow = (unsigned char) (errCode & 0xff);
6013 smbp->errHigh = (unsigned char) ((errCode >> 8) & 0xff);
6014 smbp->rcls = errClass;
6017 } /* error occurred */
6019 /* if we're here, we've finished one request. Look to see if
6020 * this is a chained opcode. If it is, setup things to process
6021 * the chained request, and setup the output buffer to hold the
6022 * chained response. Start by finding the next input record.
6024 if (!(dp->flags & SMB_DISPATCHFLAG_CHAINED))
6025 break; /* not a chained req */
6026 tp = inp->wctp; /* points to start of last request */
6027 /* in a chained request, the first two
6028 * parm fields are required, and are
6029 * AndXCommand/AndXReserved and
6031 if (tp[0] < 2) break;
6032 if (tp[1] == 0xff) break; /* no more chained opcodes */
6034 inp->wctp = inp->data + tp[3] + (tp[4] << 8);
6037 /* and now append the next output request to the end of this
6038 * last request. Begin by finding out where the last response
6039 * ends, since that's where we'll put our new response.
6041 outWctp = outp->wctp; /* ptr to out parameters */
6042 osi_assert (outWctp[0] >= 2); /* need this for all chained requests */
6043 nparms = outWctp[0] << 1;
6044 tp = outWctp + nparms + 1; /* now points to bcc field */
6045 nbytes = tp[0] + (tp[1] << 8); /* # of data bytes */
6046 tp += 2 /* for the count itself */ + nbytes;
6047 /* tp now points to the new output record; go back and patch the
6048 * second parameter (off2) to point to the new record.
6050 temp = (unsigned int)tp - ((unsigned int) outp->data);
6051 outWctp[3] = (unsigned char) (temp & 0xff);
6052 outWctp[4] = (unsigned char) ((temp >> 8) & 0xff);
6053 outWctp[2] = 0; /* padding */
6054 outWctp[1] = inp->inCom; /* next opcode */
6056 /* finally, setup for the next iteration */
6059 } /* while loop over all requests in the packet */
6061 /* done logging out, turn off logging-out flag */
6062 if (!(inp->flags & SMB_PACKETFLAG_PROFILE_UPDATE_OK)) {
6063 vcp->justLoggedOut = NULL;
6066 free(loggedOutName);
6067 loggedOutName = NULL;
6068 smb_ReleaseUID(loggedOutUserp);
6069 loggedOutUserp = NULL;
6073 /* now send the output packet, and return */
6075 smb_SendPacket(vcp, outp);
6076 thrd_Decrement(&ongoingOps);
6078 if (!(vcp->flags & SMB_VCFLAG_ALREADYDEAD)) {
6080 smb_ReleaseVC(active_vcp);
6082 "Replacing active_vcp %x with %x", active_vcp, vcp);
6086 last_msg_time = GetCurrentTime();
6088 else if (active_vcp == vcp) {
6089 smb_ReleaseVC(active_vcp);
6097 /* Wait for Netbios() calls to return, and make the results available to server
6098 * threads. Note that server threads can't wait on the NCBevents array
6099 * themselves, because NCB events are manual-reset, and the servers would race
6100 * each other to reset them.
6102 void smb_ClientWaiter(void *parmp)
6108 code = thrd_WaitForMultipleObjects_Event(numNCBs, NCBevents,
6110 if (code == WAIT_OBJECT_0)
6113 /* error checking */
6114 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numNCBs))
6116 int abandonIdx = code - WAIT_ABANDONED_0;
6117 afsi_log("Error: smb_ClientWaiter event %d abandoned, errno %d\n", abandonIdx, GetLastError());
6120 if (code == WAIT_IO_COMPLETION)
6122 afsi_log("Error: smb_ClientWaiter WAIT_IO_COMPLETION\n");
6126 if (code == WAIT_TIMEOUT)
6128 afsi_log("Error: smb_ClientWaiter WAIT_TIMEOUT, errno %d\n", GetLastError());
6131 if (code == WAIT_FAILED)
6133 afsi_log("Error: smb_ClientWaiter WAIT_FAILED, errno %d\n", GetLastError());
6136 idx = code - WAIT_OBJECT_0;
6138 /* check idx range! */
6139 if (idx < 0 || idx > (sizeof(NCBevents) / sizeof(NCBevents[0])))
6141 /* this is fatal - log as much as possible */
6142 afsi_log("Fatal: NCBevents idx [ %d ] out of range.\n", idx);
6146 thrd_ResetEvent(NCBevents[idx]);
6147 thrd_SetEvent(NCBreturns[0][idx]);
6153 * Try to have one NCBRECV request waiting for every live session. Not more
6154 * than one, because if there is more than one, it's hard to handle Write Raw.
6156 void smb_ServerWaiter(void *parmp)
6159 int idx_session, idx_NCB;
6167 code = thrd_WaitForMultipleObjects_Event(numSessions, SessionEvents,
6169 if (code == WAIT_OBJECT_0)
6172 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numSessions))
6174 int abandonIdx = code - WAIT_ABANDONED_0;
6175 afsi_log("Error: smb_ServerWaiter (SessionEvents) event %d abandoned, errno %d\n", abandonIdx, GetLastError());
6178 if (code == WAIT_IO_COMPLETION)
6180 afsi_log("Error: smb_ServerWaiter (SessionEvents) WAIT_IO_COMPLETION\n");
6184 if (code == WAIT_TIMEOUT)
6186 afsi_log("Error: smb_ServerWaiter (SessionEvents) WAIT_TIMEOUT, errno %d\n", GetLastError());
6189 if (code == WAIT_FAILED)
6191 afsi_log("Error: smb_ServerWaiter (SessionEvents) WAIT_FAILED, errno %d\n", GetLastError());
6194 idx_session = code - WAIT_OBJECT_0;
6196 /* check idx range! */
6197 if (idx_session < 0 || idx_session > (sizeof(SessionEvents) / sizeof(SessionEvents[0])))
6199 /* this is fatal - log as much as possible */
6200 afsi_log("Fatal: session idx [ %d ] out of range.\n", idx_session);
6206 code = thrd_WaitForMultipleObjects_Event(numNCBs, NCBavails,
6208 if (code == WAIT_OBJECT_0)
6211 /* error checking */
6212 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numNCBs))
6214 int abandonIdx = code - WAIT_ABANDONED_0;
6215 afsi_log("Error: smb_ClientWaiter (NCBavails) event %d abandoned, errno %d\n", abandonIdx, GetLastError());
6218 if (code == WAIT_IO_COMPLETION)
6220 afsi_log("Error: smb_ClientWaiter (NCBavails) WAIT_IO_COMPLETION\n");
6224 if (code == WAIT_TIMEOUT)
6226 afsi_log("Error: smb_ClientWaiter (NCBavails) WAIT_TIMEOUT, errno %d\n", GetLastError());
6229 if (code == WAIT_FAILED)
6231 afsi_log("Error: smb_ClientWaiter (NCBavails) WAIT_FAILED, errno %d\n", GetLastError());
6234 idx_NCB = code - WAIT_OBJECT_0;
6236 /* check idx range! */
6237 if (idx_NCB < 0 || idx_NCB > (sizeof(NCBsessions) / sizeof(NCBsessions[0])))
6239 /* this is fatal - log as much as possible */
6240 afsi_log("Fatal: idx_NCB [ %d ] out of range.\n", idx_NCB);
6244 /* Link them together */
6245 NCBsessions[idx_NCB] = idx_session;
6248 ncbp = NCBs[idx_NCB];
6250 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6252 ncbp->ncb_lsn = (unsigned char) LSNs[idx_session];
6253 ncbp->ncb_command = NCBRECV | ASYNCH;
6254 ncbp->ncb_lana_num = lanas[idx_session];
6256 ncbp->ncb_buffer = (unsigned char *) bufs[idx_NCB];
6257 ncbp->ncb_event = NCBevents[idx_NCB];
6258 ncbp->ncb_length = SMB_PACKETSIZE;
6261 ncbp->ncb_buffer = bufs[idx_NCB]->dos_pkt;
6262 ((smb_ncb_t*)ncbp)->orig_pkt = bufs[idx_NCB];
6263 ncbp->ncb_event = NCBreturns[0][idx_NCB];
6264 ncbp->ncb_length = SMB_PACKETSIZE;
6265 Netbios(ncbp, dos_ncb);
6271 * The top level loop for handling SMB request messages. Each server thread
6272 * has its own NCB and buffer for sending replies (outncbp, outbufp), but the
6273 * NCB and buffer for the incoming request are loaned to us.
6275 * Write Raw trickery starts here. When we get a Write Raw, we are supposed
6276 * to immediately send a request for the rest of the data. This must come
6277 * before any other traffic for that session, so we delay setting the session
6278 * event until that data has come in.
6280 void smb_Server(VOID *parmp)
6282 int myIdx = (int) parmp;
6286 smb_packet_t *outbufp;
6288 int idx_NCB, idx_session;
6290 smb_vc_t *vcp = NULL;
6297 outbufp = GetPacket();
6298 outbufp->ncbp = outncbp;
6302 /* check for demo expiration */
6304 unsigned long tod = time((void *) 0);
6305 if (tod > EXPIREDATE) {
6306 (*smb_MBfunc)(NULL, "AFS demo expiration",
6308 MB_OK|MB_ICONSTOP|MB_SETFOREGROUND|MB_SERVICE_NOTIFICATION);
6312 #endif /* !NOEXPIRE */
6314 code = thrd_WaitForMultipleObjects_Event(numNCBs, NCBreturns[myIdx],
6316 if (code == WAIT_OBJECT_0) {
6320 /* error checking */
6321 if (code >= WAIT_ABANDONED_0 && code < (WAIT_ABANDONED_0 + numNCBs))
6323 int abandonIdx = code - WAIT_ABANDONED_0;
6324 afsi_log("Error: smb_Server ( NCBreturns[%d] ) event %d abandoned, errno %d\n", myIdx, abandonIdx, GetLastError());
6327 if (code == WAIT_IO_COMPLETION)
6329 afsi_log("Error: smb_Server ( NCBreturns[%d] ) WAIT_IO_COMPLETION\n", myIdx);
6333 if (code == WAIT_TIMEOUT)
6335 afsi_log("Error: smb_Server ( NCBreturns[%d] ) WAIT_TIMEOUT, errno %d\n", myIdx, GetLastError());
6338 if (code == WAIT_FAILED)
6340 afsi_log("Error: smb_Server ( NCBreturns[%d] ) WAIT_FAILED, errno %d\n", myIdx, GetLastError());
6343 idx_NCB = code - WAIT_OBJECT_0;
6345 /* check idx range! */
6346 if (idx_NCB < 0 || idx_NCB > (sizeof(NCBs) / sizeof(NCBs[0])))
6348 /* this is fatal - log as much as possible */
6349 afsi_log("Fatal: idx_NCB [ %d ] out of range.\n", idx_NCB);
6353 ncbp = NCBs[idx_NCB];
6355 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6357 idx_session = NCBsessions[idx_NCB];
6358 rc = ncbp->ncb_retcode;
6360 if (rc != NRC_PENDING && rc != NRC_GOODRET)
6361 osi_Log1(smb_logp, "NCBRECV failure code %d", rc);
6364 case NRC_GOODRET: break;
6367 /* Can this happen? Or is it just my
6374 /* Client closed session */
6375 if (reportSessionStartups)
6377 afsi_log("session [ %d ] closed", idx_session);
6379 dead_sessions[idx_session] = TRUE;
6382 vcp = smb_FindVC(ncbp->ncb_lsn, 0, lanas[idx_session]);
6383 /* Should also release vcp. [done] 2004-05-11 jaltman
6385 * sanity check that all TID's are gone.
6387 * TODO: check if we could use LSNs[idx_session] instead,
6388 * also cleanup after dead vcp
6393 "dead_vcp already set, %x",
6395 if (!dead_vcp && !(vcp->flags & SMB_VCFLAG_ALREADYDEAD)) {
6397 "setting dead_vcp %x, user struct %x",
6401 vcp->flags |= SMB_VCFLAG_ALREADYDEAD;
6403 if (vcp->justLoggedOut) {
6405 loggedOutTime = vcp->logoffTime;
6407 strdup(vcp->justLoggedOut->unp->name);
6408 loggedOutUserp = vcp->justLoggedOut;
6409 lock_ObtainWrite(&smb_rctLock);
6410 loggedOutUserp->refCount++;
6411 lock_ReleaseWrite(&smb_rctLock);
6417 /* Treat as transient error */
6424 osi_Log1(smb_logp, "dispatch smb recv failed, message incomplete, ncb_length %d",
6426 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
6427 sprintf(s, "SMB message incomplete, length %d",
6430 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0,
6432 ncbp->ncb_length, ptbuf,
6434 DeregisterEventSource(h);
6437 "dispatch smb recv failed, message incomplete, ncb_length %d",
6440 "SMB message incomplete, "
6441 "length %d", ncbp->ncb_length);
6445 * We used to discard the packet.
6446 * Instead, try handling it normally.
6454 /* A weird error code. Log it, sleep, and
6456 if (vcp && vcp->errorCount++ > 3) {
6457 afsi_log("session [ %d ] closed, vcp->errorCount = %d", idx_session, vcp->errorCount);
6458 dead_sessions[idx_session] = TRUE;
6462 thrd_SetEvent(SessionEvents[idx_session]);
6467 /* Success, so now dispatch on all the data in the packet */
6469 smb_concurrentCalls++;
6470 if (smb_concurrentCalls > smb_maxObsConcurrentCalls)
6471 smb_maxObsConcurrentCalls = smb_concurrentCalls;
6475 vcp = smb_FindVC(ncbp->ncb_lsn, 0, ncbp->ncb_lana_num);
6477 * If at this point vcp is NULL (implies that packet was invalid)
6478 * then we are in big trouble. This means either :
6479 * a) we have the wrong NCB.
6480 * b) Netbios screwed up the call.
6481 * Obviously this implies that
6482 * ( LSNs[idx_session] != ncbp->ncb_lsn ||
6483 * lanas[idx_session] != ncbp->ncb_lana_num )
6484 * Either way, we can't do anything with this packet.
6485 * Log, sleep and resume.
6494 "LSNs[idx_session]=[%d],"
6495 "lanas[idx_session]=[%d],"
6496 "ncbp->ncb_lsn=[%d],"
6497 "ncbp->ncb_lana_num=[%d]",
6501 ncbp->ncb_lana_num);
6505 h = RegisterEventSource(NULL,AFS_DAEMON_EVENT_NAME);
6507 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1001, NULL,1,sizeof(*ncbp),ptbuf,(void*)ncbp);
6508 DeregisterEventSource(h);
6511 /* Also log in the trace log. */
6512 osi_Log4(smb_logp, "Server: BAD VCP!"
6513 "LSNs[idx_session]=[%d],"
6514 "lanas[idx_session]=[%d],"
6515 "ncbp->ncb_lsn=[%d],"
6516 "ncbp->ncb_lana_num=[%d]",
6520 ncbp->ncb_lana_num);
6522 /* thrd_Sleep(1000); Don't bother sleeping */
6523 thrd_SetEvent(SessionEvents[idx_session]);
6524 smb_concurrentCalls--;
6529 vcp->errorCount = 0;
6530 bufp = (struct smb_packet *) ncbp->ncb_buffer;
6532 bufp = ((smb_ncb_t *) ncbp)->orig_pkt;
6533 /* copy whole packet to virtual memory */
6534 /*fprintf(stderr, "smb_Server: copying dos packet at 0x%x, "
6536 bufp->dos_pkt / 16, bufp);*/
6538 dosmemget(bufp->dos_pkt, ncbp->ncb_length, bufp->data);
6540 smbp = (smb_t *)bufp->data;
6543 #if !defined(DJGPP) && !defined(AFS_WIN32_ENV)
6547 if (smbp->com == 0x1d) {
6548 /* Special handling for Write Raw */
6549 raw_write_cont_t rwc;
6550 EVENT_HANDLE rwevent;
6551 char eventName[MAX_PATH];
6553 smb_DispatchPacket(vcp, bufp, outbufp, ncbp, &rwc);
6554 if (rwc.code == 0) {
6555 rwevent = thrd_CreateEvent(NULL, FALSE, FALSE, TEXT("smb_Server() rwevent"));
6556 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6557 afsi_log("Event Object Already Exists: %s", eventName);
6558 ncbp->ncb_command = NCBRECV | ASYNCH;
6559 ncbp->ncb_lsn = (unsigned char) vcp->lsn;
6560 ncbp->ncb_lana_num = vcp->lana;
6561 ncbp->ncb_buffer = rwc.buf;
6562 ncbp->ncb_length = 65535;
6563 ncbp->ncb_event = rwevent;
6567 Netbios(ncbp, dos_ncb);
6569 rcode = thrd_WaitForSingleObject_Event(rwevent, RAWTIMEOUT);
6570 thrd_CloseHandle(rwevent);
6572 thrd_SetEvent(SessionEvents[idx_session]);
6574 smb_CompleteWriteRaw(vcp, bufp, outbufp, ncbp, &rwc);
6575 } else if (smbp->com == 0xa0) {
6577 * Serialize the handling for NT Transact
6580 smb_DispatchPacket(vcp, bufp, outbufp, ncbp, NULL);
6581 thrd_SetEvent(SessionEvents[idx_session]);
6583 thrd_SetEvent(SessionEvents[idx_session]);
6584 /* TODO: what else needs to be serialized? */
6585 smb_DispatchPacket(vcp, bufp, outbufp, ncbp, NULL);
6587 #if !defined(DJGPP) && !defined(AFS_WIN95_ENV)
6589 __except( smb_ServerExceptionFilter() ) {
6593 smb_concurrentCalls--;
6596 thrd_SetEvent(NCBavails[idx_NCB]);
6603 * Exception filter for the server threads. If an exception occurs in the
6604 * dispatch routines, which is where exceptions are most common, then do a
6605 * force trace and give control to upstream exception handlers. Useful for
6608 #if !defined(DJGPP) && !defined(AFS_WIN95_ENV)
6609 DWORD smb_ServerExceptionFilter(void) {
6610 /* While this is not the best time to do a trace, if it succeeds, then
6611 * we have a trace (assuming tracing was enabled). Otherwise, this should
6612 * throw a second exception.
6617 ptbuf[0] = "Unhandled exception forcing trace";
6619 h = RegisterEventSource(NULL,AFS_DAEMON_EVENT_NAME);
6621 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 1001, NULL,1,0,ptbuf,NULL);
6622 DeregisterEventSource(h);
6625 afsd_ForceTrace(TRUE);
6626 return EXCEPTION_CONTINUE_SEARCH;
6631 * Create a new NCB and associated events, packet buffer, and "space" buffer.
6632 * If the number of server threads is M, and the number of live sessions is
6633 * N, then the number of NCB's in use at any time either waiting for, or
6634 * holding, received messages is M + N, so that is how many NCB's get created.
6636 void InitNCBslot(int idx)
6638 struct smb_packet *bufp;
6639 EVENT_HANDLE retHandle;
6641 char eventName[MAX_PATH];
6643 osi_assert( idx < (sizeof(NCBs) / sizeof(NCBs[0])) );
6645 NCBs[idx] = GetNCB();
6646 sprintf(eventName,"NCBavails[%d]", idx);
6647 NCBavails[idx] = thrd_CreateEvent(NULL, FALSE, TRUE, eventName);
6648 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6649 afsi_log("Event Object Already Exists: %s", eventName);
6651 sprintf(eventName,"NCBevents[%d]", idx);
6652 NCBevents[idx] = thrd_CreateEvent(NULL, TRUE, FALSE, eventName);
6653 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6654 afsi_log("Event Object Already Exists: %s", eventName);
6656 sprintf(eventName,"NCBReturns[0<=i<smb_NumServerThreads][%d]", idx);
6657 retHandle = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
6658 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6659 afsi_log("Event Object Already Exists: %s", eventName);
6660 for (i=0; i<smb_NumServerThreads; i++)
6661 NCBreturns[i][idx] = retHandle;
6663 bufp->spacep = cm_GetSpace();
6667 /* listen for new connections */
6668 void smb_Listener(void *parmp)
6676 char rname[NCBNAMSZ+1];
6677 char cname[MAX_COMPUTERNAME_LENGTH+1];
6678 int cnamelen = MAX_COMPUTERNAME_LENGTH+1;
6683 int lana = (int) parmp;
6687 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6690 /* retrieve computer name */
6691 GetComputerName(cname, &cnamelen);
6695 memset(ncbp, 0, sizeof(NCB));
6699 /* check for demo expiration */
6701 unsigned long tod = time((void *) 0);
6702 if (tod > EXPIREDATE) {
6703 (*smb_MBfunc)(NULL, "AFS demo expiration",
6705 MB_OK|MB_ICONSTOP|MB_SETFOREGROUND|MB_SERVICE_NOTIFICATION);
6713 #endif /* !NOEXPIRE */
6715 ncbp->ncb_command = NCBLISTEN;
6716 ncbp->ncb_rto = 0; /* No receive timeout */
6717 ncbp->ncb_sto = 0; /* No send timeout */
6719 /* pad out with spaces instead of null termination */
6720 len = strlen(smb_localNamep);
6721 strncpy(ncbp->ncb_name, smb_localNamep, NCBNAMSZ);
6722 for(i=len; i<NCBNAMSZ; i++) ncbp->ncb_name[i] = ' ';
6724 strcpy(ncbp->ncb_callname, "*");
6725 for(i=1; i<NCBNAMSZ; i++) ncbp->ncb_callname[i] = ' ';
6727 ncbp->ncb_lana_num = lana;
6730 code = Netbios(ncbp);
6732 code = Netbios(ncbp, dos_ncb);
6741 /* terminate silently if shutdown flag is set */
6742 if (smbShutdownFlag == 1) {
6751 "NCBLISTEN lana=%d failed with code %d",
6752 ncbp->ncb_lana_num, code);
6754 "Client exiting due to network failure. Please restart client.\n");
6758 "Client exiting due to network failure. Please restart client.\n"
6759 "NCBLISTEN lana=%d failed with code %d",
6760 ncbp->ncb_lana_num, code);
6762 code = (*smb_MBfunc)(NULL, tbuffer, "AFS Client Service: Fatal Error",
6763 MB_OK|MB_SERVICE_NOTIFICATION);
6764 osi_assert(tbuffer);
6767 fprintf(stderr, "NCBLISTEN lana=%d failed with code %d\n",
6768 ncbp->ncb_lana_num, code);
6769 fprintf(stderr, "\nClient exiting due to network failure "
6770 "(possibly due to power-saving mode)\n");
6771 fprintf(stderr, "Please restart client.\n");
6772 afs_exit(AFS_EXITCODE_NETWORK_FAILURE);
6776 /* check for remote conns */
6777 /* first get remote name and insert null terminator */
6778 memcpy(rname, ncbp->ncb_callname, NCBNAMSZ);
6779 for (i=NCBNAMSZ; i>0; i--) {
6780 if (rname[i-1] != ' ' && rname[i-1] != 0) {
6786 /* compare with local name */
6788 if (strncmp(rname, cname, NCBNAMSZ) != 0)
6789 flags |= SMB_VCFLAG_REMOTECONN;
6791 osi_Log1(smb_logp, "New session lsn %d", ncbp->ncb_lsn);
6793 lock_ObtainMutex(&smb_ListenerLock);
6795 /* New generation */
6798 /* Log session startup */
6800 fprintf(stderr, "New session(ncb_lsn,ncb_lana_num) %d,%d starting from host "
6802 ncbp->ncb_lsn,ncbp->ncb_lana_num, rname);
6804 afsi_log("New session(ncb_lsn,ncb_lana_num) (%d,%d) starting from host %s, %d ongoing ops",
6805 ncbp->ncb_lsn,ncbp->ncb_lana_num, rname, ongoingOps);
6807 if (reportSessionStartups) {
6813 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
6814 sprintf(s, "SMB session startup, %d ongoing ops", ongoingOps);
6816 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1004, NULL,
6818 DeregisterEventSource(h);
6820 afsi_log("NCBLISTEN completed, call from %s",rname);
6821 osi_Log1(smb_logp, "SMB session startup, %d ongoing ops",
6824 fprintf(stderr, "%s: New session %d starting from host %s\n",
6825 asctime(localtime(&now)), ncbp->ncb_lsn, rname);
6830 /* now ncbp->ncb_lsn is the connection ID */
6831 vcp = smb_FindVC(ncbp->ncb_lsn, SMB_FLAG_CREATE, ncbp->ncb_lana_num);
6832 vcp->flags |= flags;
6833 strcpy(vcp->rname, rname);
6835 /* Allocate slot in session arrays */
6836 /* Re-use dead session if possible, otherwise add one more */
6837 /* But don't look at session[0], it is reserved */
6838 for (i = 1; i < numSessions; i++) {
6839 if (dead_sessions[i]) {
6840 afsi_log("connecting to dead session [ %d ]", i);
6841 dead_sessions[i] = FALSE;
6846 /* assert that we do not exceed the maximum number of sessions or NCBs.
6847 * we should probably want to wait for a session to be freed in case
6851 osi_assert(i < Sessionmax - 1);
6852 osi_assert(numNCBs < NCBmax - 1); /* if we pass this test we can allocate one more */
6854 LSNs[i] = ncbp->ncb_lsn;
6855 lanas[i] = ncbp->ncb_lana_num;
6857 if (i == numSessions) {
6858 /* Add new NCB for new session */
6859 char eventName[MAX_PATH];
6861 osi_Log1(smb_logp, "smb_Listener creating new session %d", i);
6863 InitNCBslot(numNCBs);
6865 thrd_SetEvent(NCBavails[0]);
6866 thrd_SetEvent(NCBevents[0]);
6867 for (j = 0; j < smb_NumServerThreads; j++)
6868 thrd_SetEvent(NCBreturns[j][0]);
6869 /* Also add new session event */
6870 sprintf(eventName, "SessionEvents[%d]", i);
6871 SessionEvents[i] = thrd_CreateEvent(NULL, FALSE, TRUE, eventName);
6872 if ( GetLastError() == ERROR_ALREADY_EXISTS )
6873 afsi_log("Event Object Already Exists: %s", eventName);
6875 afsi_log("increasing numNCBs [ %d ] numSessions [ %d ]", numNCBs, numSessions);
6876 thrd_SetEvent(SessionEvents[0]);
6878 thrd_SetEvent(SessionEvents[i]);
6881 lock_ReleaseMutex(&smb_ListenerLock);
6883 } /* dispatch while loop */
6886 /* initialize Netbios */
6887 void smb_NetbiosInit()
6893 int i, lana, code, l;
6895 int delname_tried=0;
6898 OSVERSIONINFO Version;
6900 /* AFAIK, this is the default for the ms loopback adapter.*/
6901 unsigned char kWLA_MAC[6] = { 0x02, 0x00, 0x4c, 0x4f, 0x4f, 0x50 };
6902 /*******************************************************************/
6904 /* Get the version of Windows */
6905 memset(&Version, 0x00, sizeof(Version));
6906 Version.dwOSVersionInfoSize = sizeof(Version);
6907 GetVersionEx(&Version);
6909 /* setup the NCB system */
6912 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
6916 if (smb_LANadapter == -1) {
6917 ncbp->ncb_command = NCBENUM;
6918 ncbp->ncb_buffer = (PUCHAR)&lana_list;
6919 ncbp->ncb_length = sizeof(lana_list);
6920 code = Netbios(ncbp);
6922 sprintf(s, "Netbios NCBENUM error code %d", code);
6924 osi_panic(s, __FILE__, __LINE__);
6928 lana_list.length = 1;
6929 lana_list.lana[0] = smb_LANadapter;
6932 for (i = 0; i < lana_list.length; i++) {
6933 /* reset the adaptor: in Win32, this is required for every process, and
6934 * acts as an init call, not as a real hardware reset.
6936 ncbp->ncb_command = NCBRESET;
6937 ncbp->ncb_callname[0] = 100;
6938 ncbp->ncb_callname[2] = 100;
6939 ncbp->ncb_lana_num = lana_list.lana[i];
6940 code = Netbios(ncbp);
6942 code = ncbp->ncb_retcode;
6944 sprintf(s, "Netbios NCBRESET lana %d error code %d", lana_list.lana[i], code);
6946 lana_list.lana[i] = 255; /* invalid lana */
6948 sprintf(s, "Netbios NCBRESET lana %d succeeded", lana_list.lana[i]);
6953 /* for DJGPP, there is no NCBENUM and NCBRESET is a real reset. so
6954 we will just fake the LANA list */
6955 if (smb_LANadapter == -1) {
6956 for (i = 0; i < 8; i++)
6957 lana_list.lana[i] = i;
6958 lana_list.length = 8;
6961 lana_list.length = 1;
6962 lana_list.lana[0] = smb_LANadapter;
6966 /* and declare our name so we can receive connections */
6967 memset(ncbp, 0, sizeof(*ncbp));
6968 len=lstrlen(smb_localNamep);
6969 memset(smb_sharename,' ',NCBNAMSZ);
6970 memcpy(smb_sharename,smb_localNamep,len);
6971 sprintf(s, "lana_list.length %d", lana_list.length);
6974 /* Keep the name so we can unregister it later */
6975 for (l = 0; l < lana_list.length; l++) {
6976 lana = lana_list.lana[l];
6978 ncbp->ncb_command = NCBADDNAME;
6979 ncbp->ncb_lana_num = lana;
6980 memcpy(ncbp->ncb_name,smb_sharename,NCBNAMSZ);
6982 code = Netbios(ncbp);
6984 code = Netbios(ncbp, dos_ncb);
6987 afsi_log("Netbios NCBADDNAME lana=%d code=%d retcode=%d complete=%d",
6988 lana, code, ncbp->ncb_retcode,ncbp->ncb_cmd_cplt);
6990 char name[NCBNAMSZ+1];
6992 memcpy(name,ncbp->ncb_name,NCBNAMSZ);
6993 afsi_log("Netbios NCBADDNAME added new name >%s<",name);
6996 if (code == 0) code = ncbp->ncb_retcode;
6998 afsi_log("Netbios NCBADDNAME succeeded on lana %d\n", lana);
7000 /* we only use one LANA with djgpp */
7001 lana_list.lana[0] = lana;
7002 lana_list.length = 1;
7006 sprintf(s, "Netbios NCBADDNAME lana %d error code %d", lana, code);
7008 if (code == NRC_BRIDGE) { /* invalid LANA num */
7009 lana_list.lana[l] = 255;
7012 else if (code == NRC_DUPNAME) {
7013 afsi_log("Name already exists; try to delete it");
7014 memset(ncbp, 0, sizeof(*ncbp));
7015 ncbp->ncb_command = NCBDELNAME;
7016 memcpy(ncbp->ncb_name,smb_sharename,NCBNAMSZ);
7017 ncbp->ncb_lana_num = lana;
7019 code = Netbios(ncbp);
7021 code = Netbios(ncbp, dos_ncb);
7023 if (code == 0) code = ncbp->ncb_retcode;
7025 sprintf(s, "Netbios NCBDELNAME lana %d error code %d\n", lana, code);
7028 if (code != 0 || delname_tried) {
7029 lana_list.lana[l] = 255;
7031 else if (code == 0) {
7032 if (!delname_tried) {
7040 sprintf(s, "Netbios NCBADDNAME lana %d error code %d", lana, code);
7042 lana_list.lana[l] = 255; /* invalid lana */
7043 osi_panic(s, __FILE__, __LINE__);
7047 lana_found = 1; /* at least one worked */
7054 osi_assert(lana_list.length >= 0);
7056 sprintf(s, "No valid LANA numbers found!");
7057 osi_panic(s, __FILE__, __LINE__);
7060 /* we're done with the NCB now */
7064 void smb_Init(osi_log_t *logp, char *snamep, int useV3, int LANadapt,
7081 EVENT_HANDLE retHandle;
7082 char eventName[MAX_PATH];
7085 smb_MBfunc = aMBfunc;
7089 /* check for demo expiration */
7091 unsigned long tod = time((void *) 0);
7092 if (tod > EXPIREDATE) {
7094 (*smb_MBfunc)(NULL, "AFS demo expiration", "afsd",
7095 MB_OK|MB_ICONSTOP|MB_SETFOREGROUND|MB_SERVICE_NOTIFICATION);
7098 fprintf(stderr, "AFS demo expiration\n");
7103 #endif /* !NOEXPIRE */
7106 smb_LANadapter = LANadapt;
7108 /* Initialize smb_localZero */
7109 myTime.tm_isdst = -1; /* compute whether on DST or not */
7110 myTime.tm_year = 70;
7116 smb_localZero = mktime(&myTime);
7118 /* Initialize kludge-GMT */
7119 smb_CalculateNowTZ();
7121 /* initialize the remote debugging log */
7124 /* remember the name */
7125 len = strlen(snamep);
7126 smb_localNamep = malloc(len+1);
7127 strcpy(smb_localNamep, snamep);
7128 afsi_log("smb_localNamep is >%s<", smb_localNamep);
7130 /* and the global lock */
7131 lock_InitializeRWLock(&smb_globalLock, "smb global lock");
7132 lock_InitializeRWLock(&smb_rctLock, "smb refct and tree struct lock");
7134 /* Raw I/O data structures */
7135 lock_InitializeMutex(&smb_RawBufLock, "smb raw buffer lock");
7137 lock_InitializeMutex(&smb_ListenerLock, "smb listener lock");
7139 /* 4 Raw I/O buffers */
7141 smb_RawBufs = calloc(65536,1);
7142 *((char **)smb_RawBufs) = NULL;
7143 for (i=0; i<3; i++) {
7144 char *rawBuf = calloc(65536,1);
7145 *((char **)rawBuf) = smb_RawBufs;
7146 smb_RawBufs = rawBuf;
7149 npar = 65536 >> 4; /* number of paragraphs */
7150 seg = __dpmi_allocate_dos_memory(npar, &smb_RawBufSel[0]);
7152 afsi_log("Cannot allocate %d paragraphs of DOS memory",
7154 osi_panic("",__FILE__,__LINE__);
7157 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X",
7160 smb_RawBufs = (seg * 16) + 0; /* DOS physical address */
7162 _farpokel(_dos_ds, smb_RawBufs, NULL);
7163 for (i=0; i<SMB_RAW_BUFS-1; i++) {
7164 npar = 65536 >> 4; /* number of paragraphs */
7165 seg = __dpmi_allocate_dos_memory(npar, &smb_RawBufSel[i+1]);
7167 afsi_log("Cannot allocate %d paragraphs of DOS memory",
7169 osi_panic("",__FILE__,__LINE__);
7172 afsi_log("Allocated %d paragraphs of DOS mem at 0x%X",
7175 rawBuf = (seg * 16) + 0; /* DOS physical address */
7176 /*_farpokel(_dos_ds, smb_RawBufs, smb_RawBufs);*/
7177 _farpokel(_dos_ds, rawBuf, smb_RawBufs);
7178 smb_RawBufs = rawBuf;
7182 /* global free lists */
7183 smb_ncbFreeListp = NULL;
7184 smb_packetFreeListp = NULL;
7188 /* Initialize listener and server structures */
7190 memset(dead_sessions, 0, sizeof(dead_sessions));
7191 sprintf(eventName, "SessionEvents[0]");
7192 SessionEvents[0] = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
7193 if ( GetLastError() == ERROR_ALREADY_EXISTS )
7194 afsi_log("Event Object Already Exists: %s", eventName);
7196 smb_NumServerThreads = nThreads;
7197 sprintf(eventName, "NCBavails[0]");
7198 NCBavails[0] = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
7199 if ( GetLastError() == ERROR_ALREADY_EXISTS )
7200 afsi_log("Event Object Already Exists: %s", eventName);
7201 sprintf(eventName, "NCBevents[0]");
7202 NCBevents[0] = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
7203 if ( GetLastError() == ERROR_ALREADY_EXISTS )
7204 afsi_log("Event Object Already Exists: %s", eventName);
7205 NCBreturns = malloc(nThreads * sizeof(EVENT_HANDLE *));
7206 sprintf(eventName, "NCBreturns[0<=i<smb_NumServerThreads][0]");
7207 retHandle = thrd_CreateEvent(NULL, FALSE, FALSE, eventName);
7208 if ( GetLastError() == ERROR_ALREADY_EXISTS )
7209 afsi_log("Event Object Already Exists: %s", eventName);
7210 for (i = 0; i < smb_NumServerThreads; i++) {
7211 NCBreturns[i] = malloc(NCBmax * sizeof(EVENT_HANDLE));
7212 NCBreturns[i][0] = retHandle;
7214 for (i = 1; i <= nThreads; i++)
7216 numNCBs = nThreads + 1;
7218 /* Initialize dispatch table */
7219 memset(&smb_dispatchTable, 0, sizeof(smb_dispatchTable));
7220 smb_dispatchTable[0x00].procp = smb_ReceiveCoreMakeDir;
7221 smb_dispatchTable[0x01].procp = smb_ReceiveCoreRemoveDir;
7222 smb_dispatchTable[0x02].procp = smb_ReceiveCoreOpen;
7223 smb_dispatchTable[0x03].procp = smb_ReceiveCoreCreate;
7224 smb_dispatchTable[0x04].procp = smb_ReceiveCoreClose;
7225 smb_dispatchTable[0x05].procp = smb_ReceiveCoreFlush;
7226 smb_dispatchTable[0x06].procp = smb_ReceiveCoreUnlink;
7227 smb_dispatchTable[0x07].procp = smb_ReceiveCoreRename;
7228 smb_dispatchTable[0x08].procp = smb_ReceiveCoreGetFileAttributes;
7229 smb_dispatchTable[0x09].procp = smb_ReceiveCoreSetFileAttributes;
7230 smb_dispatchTable[0x0a].procp = smb_ReceiveCoreRead;
7231 smb_dispatchTable[0x0b].procp = smb_ReceiveCoreWrite;
7232 smb_dispatchTable[0x0c].procp = smb_ReceiveCoreLockRecord;
7233 smb_dispatchTable[0x0d].procp = smb_ReceiveCoreUnlockRecord;
7234 smb_dispatchTable[0x0e].procp = smb_SendCoreBadOp; /* create temporary */
7235 smb_dispatchTable[0x0f].procp = smb_ReceiveCoreCreate;
7236 smb_dispatchTable[0x10].procp = smb_ReceiveCoreCheckPath;
7237 smb_dispatchTable[0x11].procp = smb_SendCoreBadOp; /* process exit */
7238 smb_dispatchTable[0x12].procp = smb_ReceiveCoreSeek;
7239 smb_dispatchTable[0x1a].procp = smb_ReceiveCoreReadRaw;
7240 /* Set NORESPONSE because smb_ReceiveCoreReadRaw() does the responses itself */
7241 smb_dispatchTable[0x1a].flags |= SMB_DISPATCHFLAG_NORESPONSE;
7242 smb_dispatchTable[0x1d].procp = smb_ReceiveCoreWriteRawDummy;
7243 smb_dispatchTable[0x22].procp = smb_ReceiveV3SetAttributes;
7244 smb_dispatchTable[0x23].procp = smb_ReceiveV3GetAttributes;
7245 smb_dispatchTable[0x24].procp = smb_ReceiveV3LockingX;
7246 smb_dispatchTable[0x24].flags |= SMB_DISPATCHFLAG_CHAINED;
7247 smb_dispatchTable[0x29].procp = smb_SendCoreBadOp; /* copy file */
7248 smb_dispatchTable[0x2b].procp = smb_ReceiveCoreEcho;
7249 /* Set NORESPONSE because smb_ReceiveCoreEcho() does the responses itself */
7250 smb_dispatchTable[0x2b].flags |= SMB_DISPATCHFLAG_NORESPONSE;
7251 smb_dispatchTable[0x2d].procp = smb_ReceiveV3OpenX;
7252 smb_dispatchTable[0x2d].flags |= SMB_DISPATCHFLAG_CHAINED;
7253 smb_dispatchTable[0x2e].procp = smb_ReceiveV3ReadX;
7254 smb_dispatchTable[0x2e].flags |= SMB_DISPATCHFLAG_CHAINED;
7255 smb_dispatchTable[0x32].procp = smb_ReceiveV3Tran2A; /* both are same */
7256 smb_dispatchTable[0x32].flags |= SMB_DISPATCHFLAG_NORESPONSE;
7257 smb_dispatchTable[0x33].procp = smb_ReceiveV3Tran2A;
7258 smb_dispatchTable[0x33].flags |= SMB_DISPATCHFLAG_NORESPONSE;
7259 smb_dispatchTable[0x34].procp = smb_ReceiveV3FindClose;
7260 smb_dispatchTable[0x35].procp = smb_ReceiveV3FindNotifyClose;
7261 smb_dispatchTable[0x70].procp = smb_ReceiveCoreTreeConnect;
7262 smb_dispatchTable[0x71].procp = smb_ReceiveCoreTreeDisconnect;
7263 smb_dispatchTable[0x72].procp = smb_ReceiveNegotiate;
7264 smb_dispatchTable[0x73].procp = smb_ReceiveV3SessionSetupX;
7265 smb_dispatchTable[0x73].flags |= SMB_DISPATCHFLAG_CHAINED;
7266 smb_dispatchTable[0x74].procp = smb_ReceiveV3UserLogoffX;
7267 smb_dispatchTable[0x74].flags |= SMB_DISPATCHFLAG_CHAINED;
7268 smb_dispatchTable[0x75].procp = smb_ReceiveV3TreeConnectX;
7269 smb_dispatchTable[0x75].flags |= SMB_DISPATCHFLAG_CHAINED;
7270 smb_dispatchTable[0x80].procp = smb_ReceiveCoreGetDiskAttributes;
7271 smb_dispatchTable[0x81].procp = smb_ReceiveCoreSearchDir;
7272 smb_dispatchTable[0xA0].procp = smb_ReceiveNTTransact;
7273 smb_dispatchTable[0xA2].procp = smb_ReceiveNTCreateX;
7274 smb_dispatchTable[0xA2].flags |= SMB_DISPATCHFLAG_CHAINED;
7275 smb_dispatchTable[0xA4].procp = smb_ReceiveNTCancel;
7276 smb_dispatchTable[0xA4].flags |= SMB_DISPATCHFLAG_NORESPONSE;
7277 smb_dispatchTable[0xc0].procp = smb_SendCoreBadOp;
7278 smb_dispatchTable[0xc1].procp = smb_SendCoreBadOp;
7279 smb_dispatchTable[0xc2].procp = smb_SendCoreBadOp;
7280 smb_dispatchTable[0xc3].procp = smb_SendCoreBadOp;
7281 for(i=0xd0; i<= 0xd7; i++) {
7282 smb_dispatchTable[i].procp = smb_SendCoreBadOp;
7285 /* setup tran 2 dispatch table */
7286 smb_tran2DispatchTable[0].procp = smb_ReceiveTran2Open;
7287 smb_tran2DispatchTable[1].procp = smb_ReceiveTran2SearchDir; /* FindFirst */
7288 smb_tran2DispatchTable[2].procp = smb_ReceiveTran2SearchDir; /* FindNext */
7289 smb_tran2DispatchTable[3].procp = smb_ReceiveTran2QFSInfo;
7290 smb_tran2DispatchTable[4].procp = smb_ReceiveTran2SetFSInfo;
7291 smb_tran2DispatchTable[5].procp = smb_ReceiveTran2QPathInfo;
7292 smb_tran2DispatchTable[6].procp = smb_ReceiveTran2SetPathInfo;
7293 smb_tran2DispatchTable[7].procp = smb_ReceiveTran2QFileInfo;
7294 smb_tran2DispatchTable[8].procp = smb_ReceiveTran2SetFileInfo;
7295 smb_tran2DispatchTable[9].procp = smb_ReceiveTran2FSCTL;
7296 smb_tran2DispatchTable[10].procp = smb_ReceiveTran2IOCTL;
7297 smb_tran2DispatchTable[11].procp = smb_ReceiveTran2FindNotifyFirst;
7298 smb_tran2DispatchTable[12].procp = smb_ReceiveTran2FindNotifyNext;
7299 smb_tran2DispatchTable[13].procp = smb_ReceiveTran2MKDir;
7303 /* if we are doing SMB authentication we have register outselves as a logon process */
7304 if (smb_authType != SMB_AUTH_NONE) {
7306 LSA_STRING afsProcessName;
7307 LSA_OPERATIONAL_MODE dummy; /*junk*/
7310 afsProcessName.Buffer = "OpenAFSClientDaemon";
7311 afsProcessName.Length = strlen(afsProcessName.Buffer);
7312 afsProcessName.MaximumLength = afsProcessName.Length + 1;
7314 nts = LsaRegisterLogonProcess(&afsProcessName, &smb_lsaHandle, &dummy);
7316 if (nts == STATUS_SUCCESS) {
7317 LSA_STRING packageName;
7318 /* we are registered. Find out the security package id */
7319 packageName.Buffer = MSV1_0_PACKAGE_NAME;
7320 packageName.Length = strlen(packageName.Buffer);
7321 packageName.MaximumLength = packageName.Length + 1;
7322 nts = LsaLookupAuthenticationPackage(smb_lsaHandle, &packageName , &smb_lsaSecPackage);
7323 if (nts == STATUS_SUCCESS) {
7324 /* Now get ourselves a domain name. */
7325 /* For now we are using the local computer name as the domain name.
7326 * It is actually the domain for local logins, and we are acting as
7327 * a local SMB server.
7329 bufsize = sizeof(smb_ServerDomainName) - 1;
7330 GetComputerName(smb_ServerDomainName, &bufsize);
7331 smb_ServerDomainNameLength = bufsize + 1; /* bufsize doesn't include terminator */
7332 afsi_log("Setting SMB server domain name to [%s]", smb_ServerDomainName);
7334 smb_lsaLogonOrigin.Buffer = "OpenAFS";
7335 smb_lsaLogonOrigin.Length = strlen(smb_lsaLogonOrigin.Buffer);
7336 smb_lsaLogonOrigin.MaximumLength = smb_lsaLogonOrigin.Length + 1;
7338 afsi_log("Can't determine security package name for NTLM!! NTSTATUS=[%l]",nts);
7341 afsi_log("Can't register logon process!! NTSTATUS=[%l]",nts);
7344 if (nts != STATUS_SUCCESS) {
7345 /* something went wrong. We report the error and revert back to no authentication
7346 because we can't perform any auth requests without a successful lsa handle
7347 or sec package id. */
7348 afsi_log("Reverting to NO SMB AUTH");
7349 smb_authType = SMB_AUTH_NONE;
7350 } else if ( smb_authType == SMB_AUTH_EXTENDED) {
7351 /* Test to see if there is anything to negotiate. If SPNEGO is not going to be used
7352 * then the only option is NTLMSSP anyway; so just fallback.
7357 smb_NegotiateExtendedSecurity(&secBlob, &secBlobLength);
7358 if (secBlobLength == 0) {
7359 smb_authType = SMB_AUTH_NTLM;
7360 afsi_log("Reverting to SMB AUTH NTLM");
7366 /* Start listeners, waiters, servers, and daemons */
7368 for (i = 0; i < lana_list.length; i++) {
7369 if (lana_list.lana[i] == 255) continue;
7370 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_Listener,
7371 (void*)lana_list.lana[i], 0, &lpid, "smb_Listener");
7372 osi_assert(phandle != NULL);
7373 thrd_CloseHandle(phandle);
7377 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_ClientWaiter,
7378 NULL, 0, &lpid, "smb_ClientWaiter");
7379 osi_assert(phandle != NULL);
7380 thrd_CloseHandle(phandle);
7383 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_ServerWaiter,
7384 NULL, 0, &lpid, "smb_ServerWaiter");
7385 osi_assert(phandle != NULL);
7386 thrd_CloseHandle(phandle);
7388 for (i=0; i<nThreads; i++) {
7389 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_Server,
7390 (void *) i, 0, &lpid, "smb_Server");
7391 osi_assert(phandle != NULL);
7392 thrd_CloseHandle(phandle);
7395 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_Daemon,
7396 NULL, 0, &lpid, "smb_Daemon");
7397 osi_assert(phandle != NULL);
7398 thrd_CloseHandle(phandle);
7400 phandle = thrd_Create(NULL, 65536, (ThreadFunc) smb_WaitingLocksDaemon,
7401 NULL, 0, &lpid, "smb_WaitingLocksDaemon");
7402 osi_assert(phandle != NULL);
7403 thrd_CloseHandle(phandle);
7412 void smb_Shutdown(void)
7421 /*fprintf(stderr, "Entering smb_Shutdown\n");*/
7423 /* setup the NCB system */
7426 dos_ncb = ((smb_ncb_t *)ncbp)->dos_ncb;
7429 /* Block new sessions by setting shutdown flag */
7430 smbShutdownFlag = 1;
7432 /* Hang up all sessions */
7433 memset((char *)ncbp, 0, sizeof(NCB));
7434 for (i = 1; i < numSessions; i++)
7436 if (dead_sessions[i])
7439 /*fprintf(stderr, "NCBHANGUP session %d LSN %d\n", i, LSNs[i]);*/
7440 ncbp->ncb_command = NCBHANGUP;
7441 ncbp->ncb_lana_num = lanas[i]; /*smb_LANadapter;*/
7442 ncbp->ncb_lsn = LSNs[i];
7444 code = Netbios(ncbp);
7446 code = Netbios(ncbp, dos_ncb);
7448 /*fprintf(stderr, "returned from NCBHANGUP session %d LSN %d\n", i, LSNs[i]);*/
7449 if (code == 0) code = ncbp->ncb_retcode;
7451 osi_Log1(smb_logp, "Netbios NCBHANGUP error code %d", code);
7452 fprintf(stderr, "Session %d Netbios NCBHANGUP error code %d", i, code);
7456 /* Delete Netbios name */
7457 memset((char *)ncbp, 0, sizeof(NCB));
7458 for (i = 0; i < lana_list.length; i++) {
7459 if (lana_list.lana[i] == 255) continue;
7460 ncbp->ncb_command = NCBDELNAME;
7461 ncbp->ncb_lana_num = lana_list.lana[i];
7462 memcpy(ncbp->ncb_name,smb_sharename,NCBNAMSZ);
7464 code = Netbios(ncbp);
7466 code = Netbios(ncbp, dos_ncb);
7468 if (code == 0) code = ncbp->ncb_retcode;
7470 fprintf(stderr, "Netbios NCBDELNAME lana %d error code %d",
7471 ncbp->ncb_lana_num, code);
7477 /* Get the UNC \\<servername>\<sharename> prefix. */
7478 char *smb_GetSharename()
7482 /* Make sure we have been properly initialized. */
7483 if (smb_localNamep == NULL)
7486 /* Allocate space for \\<servername>\<sharename>, plus the
7489 name = malloc(strlen(smb_localNamep) + strlen("ALL") + 4);
7490 sprintf(name, "\\\\%s\\%s", smb_localNamep, "ALL");
7496 void smb_LogPacket(smb_packet_t *packet)
7499 unsigned length, paramlen, datalen, i, j;
7501 char hex[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
7505 osi_Log0(smb_logp, "*** SMB packet dump ***");
7507 vp = (BYTE *) packet->data;
7509 datalen = *((WORD*)(vp + (paramlen = ((unsigned)*(vp+20)) << 1)));
7510 length = paramlen + 2 + datalen;
7513 for(i=0;i < length; i+=16)
7515 memset( buf, ' ', 80 );
7520 buf[strlen(buf)] = ' ';
7522 cp = (BYTE*) buf + 7;
7524 for(j=0;j < 16 && (i+j)<length; j++)
7526 *(cp++) = hex[vp[i+j] >> 4];
7527 *(cp++) = hex[vp[i+j] & 0xf];
7537 for(j=0;j < 16 && (i+j)<length;j++)
7539 *(cp++) = ( 32 <= vp[i+j] && 128 > vp[i+j] )? vp[i+j]:'.';
7550 osi_Log0( smb_logp, buf );
7553 osi_Log0(smb_logp, "*** End SMB packet dump ***");
7557 #endif /* NOTSERVICE */
7559 int smb_DumpVCP(FILE *outputFile, char *cookie)
7566 lock_ObtainRead(&smb_rctLock);
7568 sprintf(output, "begin dumping vcpsp\n");
7569 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7571 for(vcp = smb_allVCsp; vcp; vcp=vcp->nextp)
7575 sprintf(output, "%s vcp=0x%08X, refCount=%d, flags=%d, vcID=%d, lsn=%d, uidCounter=%d, tidCounter=%d, fidCounter=%d\n",
7576 cookie, vcp, vcp->refCount, vcp->flags, vcp->vcID, vcp->lsn, vcp->uidCounter, vcp->tidCounter, vcp->fidCounter);
7577 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7579 sprintf(output, "begin dumping fidsp\n");
7580 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7582 for (fidp = vcp->fidsp; fidp; fidp = (smb_fid_t *) osi_QNext(&fidp->q))
7584 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",
7585 cookie, fidp, fidp->refCount, fidp->fid, fidp->vcp, fidp->scp, fidp->ioctlp,
7586 fidp->NTopen_pathp ? fidp->NTopen_pathp : "NULL",
7587 fidp->NTopen_wholepathp ? fidp->NTopen_wholepathp : "NULL");
7588 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7591 sprintf(output, "done dumping fidsp\n");
7592 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7595 sprintf(output, "done dumping vcpsp\n");
7596 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
7598 lock_ReleaseRead(&smb_rctLock);