Logo Море(!) аналитической информации!
IT-консалтинг Software Engineering Программирование СУБД Безопасность Internet Сети Операционные системы Hardware
Архив форумов ЦИТФорума
Море(!) вопросов - Море(!) ответов
 
 FAQFAQ   ПоискПоиск   ПользователиПользователи   ГруппыГруппы   РегистрацияРегистрация 
 ПрофильПрофиль   Войти и проверить личные сообщенияВойти и проверить личные сообщения   ВходВход 
Как правильно задавать вопросы

Расшаривание ресурсов, TShareInfo502

 
Перейти:  
Этот форум закрыт, вы не можете писать новые сообщения и редактировать старые.   Эта тема закрыта, вы не можете писать ответы и редактировать сообщения.    Список форумов Архив форумов ЦИТФорума -> Программирование
Предыдущая тема :: Следующая тема  
Автор Сообщение
Ildar



Зарегистрирован: 06.07.2006
Сообщения: 3
Откуда: Чистополь

СообщениеДобавлено: Чт Июл 06 2006 16:04    Заголовок сообщения: Расшаривание ресурсов, TShareInfo502 Ответить с цитатой

Люди, возникает ошибка при LookupAccountNameW(nil, Username, MypSid, cbSid, @RefDomain[0], cchDomain, peUse). Она возвращает значение False. Ошибка 1332 - Именам пользователей не сопоставлены коды защиты данных.
При отладке видно, что все поля заполняются нормально
Username:= StringToOleStr(MyUserName); заполняется нормально, но MessageBox(0, @Username, PChar('Error!'), MB_OK); показывает абракадабру.

sd объявлен в другом модуле и тамже происходит заполнение структуры TShareInfo502. Всё это сделано с целью расшаривания папки только для определённого опользователя.

В чём моя ошибка или какие-то другие структуры надо применять?

Весь модуль:

unit untSecDesc;
interface
uses
Windows, Messages, SysUtils, StrUtils, LM;

// functions
function GetSD(MyDirectoryToShare: String; MyUserName: String): Integer;

implementation

type
_ACE_HEADER = record
AceType: BYTE;
AceFlags: BYTE;
AceSize: WORD;
end;
ACE_HEADER = ^_ACE_HEADER;
PACE_HEADER = ^ACE_HEADER;


type
_ACCESS_ALLOWED_ACE = record
Header: ACE_HEADER;
Mask: ACCESS_MASK;
SidStart: DWORD;
end;
ACCESS_ALLOWED_ACE = ^_ACCESS_ALLOWED_ACE;

const
RTN_OK: Integer = 0;
RTN_USAGE: Integer = 1;
RTN_ERROR: Integer = 13;

SID_SIZE: Integer = 96;
ACL_REVISION: Integer = 1;
//#pragma comment(lib,"NetApi32.lib")
// Note: UNICODE entry point and argv. This way, we don't need to bother
// with converting commandline args to Unicode //

//int __cdecl wmain( int argc, wchar_t *argv[] )

function GetSD(MyDirectoryToShare: String; MyUserName: String): Integer;
var
DirectoryToShare: LPWSTR;
// Sharename: LPWSTR;
Username: LPWSTR;
Server: LPWSTR;
MypSid: PSID; // !!!!!!!!!!!!!
cbSid: DWORD;
RefDomain: array [0..DNLEN] of WideChar;
cchDomain: DWORD;
peUse: SID_NAME_USE;
sd: SECURITY_DESCRIPTOR;
MypDacl: PACL; // !!!!!!!!!!!!!
dwAclSize: DWORD;
si502: SHARE_INFO_502;
nas: NET_API_STATUS;
bSuccess: BOOL; // assume this function fails
begin
MypSid:= nil;
cchDomain:= DNLEN+ 1;
FillChar(RefDomain, SizeOf(RefDomain), #0);

MypDacl:= nil;
bSuccess:= False;
//
// since the commandline was Unicode, just provide pointers to
// the relevant items
//
DirectoryToShare:= PWideChar(MyDirectoryToShare);
// Username:= PWideChar(MyUserName);
Username:= StringToOleStr(MyUserName);
MessageBox(0, @Username, PChar('Error!'), MB_OK);
//
// initial allocation attempt for Sid
//
cbSid:= SID_SIZE;
MypSid:= HeapAlloc(GetProcessHeap(), 0, cbSid);
// -----------------------------------------------------------------------------
if MypSid = nil then
begin
MessageBox(0, PChar('HeapAlloc error!'), PChar('Error!'), MB_OK);
Exit;
end;
// -----------------------------------------------------------------------------
//
// get the Sid associated with the supplied user/group name
// force Unicode API since we always pass Unicode string
//
// -----------------------------------------------------------------------------
if not LookupAccountNameW(nil, // default lookup logic
Username, // user/group of interest from commandline
MypSid, // Sid buffer
cbSid, // size of Sid
@RefDomain[0], // Domain account found on (unused)
cchDomain, // size of domain in chars
peUse)
then
begin //
// if the buffer wasn't large enough, try again
//
// ------------------------------------------------------------------
if (GetLastError() = ERROR_INSUFFICIENT_BUFFER) then
begin
MypSid:= HeapReAlloc(GetProcessHeap(), 0, MypSid, cbSid);
if(MypSid = nil) then
begin
MessageBox(0, PChar('HeapAlloc error!'), PChar('Error!'), MB_OK);
Exit;
end;
cchDomain:= DNLEN+ 1;
if not LookupAccountNameW(nil, // default lookup logic
Username, // user/group of interest from commandline
MypSid, // Sid buffer
cbSid, // size of Sid
@RefDomain[0], // Domain account found on (unused)
cchDomain, // size of domain in chars
peUse)
then
begin
MessageBox(0, PChar('1LookupAccountName error! Ошибка: '+ IntToStr(GetLastError()) + ' - '+ SysErrorMessage(GetLastError())), PChar('Error!'), MB_OK);
Exit;
end;
end
else MessageBox(0, PChar('2LookupAccountName error! Ошибка: '+ IntToStr(GetLastError()) + ' - '+ SysErrorMessage(GetLastError())), PChar('Error!'), MB_OK);
// ------------------------------------------------------------------
//
// compute size of new acl
//
dwAclSize:= SizeOf(ACL) +1 * (SizeOf(ACCESS_ALLOWED_ACE) - SizeOf(DWORD)) + GetLengthSid(MypSid);
//
// allocate storage for Acl
//
MypDacl:= HeapAlloc(GetProcessHeap(), 0, dwAclSize);
if MypDacl = nil then Exit;
if not InitializeAcl(MypDacl^, dwAclSize, ACL_REVISION) then Exit;
//
// grant GENERIC_ALL (Full Control) access
//
if not AddAccessAllowedAce(MypDacl^, ACL_REVISION, GENERIC_ALL, MypSid) then Exit;
if not InitializeSecurityDescriptor(@sd, SECURITY_DESCRIPTOR_REVISION) then Exit;
if not SetSecurityDescriptorDacl(@sd, TRUE, MypDacl, FALSE) then
begin
MessageBox(0, PChar('SetSecurityDescriptorDacl error! '+ SysErrorMessage(GetLastError())), PChar('Error!'), MB_OK);
Exit;
end;
//
// setup share info structure
//
{ si502.shi502_netname:= LPTSTR(Sharename);
si502.shi502_type:= STYPE_DISKTREE;
si502.shi502_remark:= nil;
si502.shi502_permissions:= 0;
si502.shi502_max_uses:= SHI_USES_UNLIMITED;
si502.shi502_current_uses:= 0;
si502.shi502_path:= LPTSTR(DirectoryToShare);
si502.shi502_passwd:= nil;
si502.shi502_reserved:= 0;
si502.shi502_security_descriptor:= @sd;
nas:= NetShareAdd(LPTSTR(Server), // share is on local machine
502, // info-level
@si502, // info-buffer
nil // don't bother with parm
);
if nas <> NO_ERROR then
begin
MessageBox(0, PChar('NetShareAdd error! '+ SysErrorMessage(GetLastError())), PChar('Error!'), MB_OK);
Exit;
end;}
end;
bSuccess:= True;
// indicate success
// cleanup:
// // free allocated resources //
if MypDacl <> nil then HeapFree(GetProcessHeap(), 0, MypDacl);
if MypSid <> nil then HeapFree(GetProcessHeap(), 0, MypSid);
if not bSuccess then Result:= RTN_ERROR else Result:= RTN_OK;
end;

end.
Вернуться к началу
Посмотреть профиль Отправить личное сообщение
Показать сообщения:   
Этот форум закрыт, вы не можете писать новые сообщения и редактировать старые.   Эта тема закрыта, вы не можете писать ответы и редактировать сообщения.    Список форумов Архив форумов ЦИТФорума -> Программирование Часовой пояс: GMT + 3
Страница 1 из 1

 
Перейти:  
Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах


Powered by phpBB © 2001, 2002 phpBB Group
Русская поддержка phpBB

 

IT-консалтинг Software Engineering Программирование СУБД Безопасность Internet Сети Операционные системы Hardware

Информация для рекламодателей PR-акции, размещение рекламы — adv@citforum.ru,
тел. +7 495 6608306, ICQ 232284597
Пресс-релизы — pr@citforum.ru
Послать комментарий
Информация для авторов
This Web server launched on February 24, 1997
Copyright © 1997-2000 CIT, © 2001-2006 CIT Forum
Внимание! Любой из материалов, опубликованных на этом сервере, не может быть воспроизведен в какой бы то ни было форме и какими бы то ни было средствами без письменного разрешения владельцев авторских прав. Подробнее...