o
    jy                     @   sX  d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZmZ d dl	m
Z
 d dlmZ d dlT d dlmZ d dlmZ d dlmZ d dlT d d	lmZ d dlT d dlT d dlT d dlT d dlT d dlT d dlT d dlT d d
lm Z  d dl!m"Z" de#fddZ$G dd de j%Z&eG dd dZ'eG dd dZ(eG dd dZ)G dd dZ*dS )    N)	dataclassfield)Path)logger)*)
SMBCommand)NTStatus)
SMBMessage)SMB2Message)FileAttributes)FileInfoClasslinux_filetimec                 C   s   t | d d S )Nl    !l
 i )int)r    r   /root/aizidognhua/tmp/workspace/projects/ec89d86c-575f-41c9-af57-ac45cbdbf775/venv/lib/python3.10/site-packages/aiosmb/server/serverconnection.pyconvert_to_ft   s   r   c                   @   s   e Zd ZdZdZdZdZdS )SMBConnectionStatusNEGOTIATINGSESSIONSETUPRUNNINGCLOSEDN)__name__
__module____qualname__r   r   r   r   r   r   r   r   r       s
    r   c                   @   s4   e Zd ZU dZeed< dZeed< dZe	j
ed< dS )	FileEntryNfile_idpathhandle)r   r   r   r   r   __annotations__r   r   r   ioFileIOr   r   r   r   r   &   s   
 r   c                   @   sL   e Zd ZU eedZeeef ed< dZ	e
ed< dZeed< dZeed< dS )	TreeEntrydefault_factoryfile_entriesNhostnamer   tree_id)r   r   r   r   dictr$   r   r   r   r%   strr   r   r&   r   r   r   r   r!   ,   s
   
 r!   c                   @   sH   e Zd ZU eedZee ed< dZe	ed< dZ
eed< dZeed< dS )	DirEnumStater"   entriesr   indexr   patternN
info_class)r   r   r   r   listr*   r(   r   r+   r   r,   r-   r   r   r   r   r   r)   3   s
   
 r)   c                   @   s   e Zd Ze fddZdd Zdd Zdd Zd	d
 Z	dd Z
d%ddZdd Zdd ZdefddZdefddZdefddZdefddZdefddZdefdd Zejfd!ed"efd#d$ZdS )&SMBServerConnectionc                 C   s  || _ | j || _|| _| j j| _|| _d | _d | _| j j	| _
d| _d| _tj| _i | _i | _i | _i | _d| _| j j| _| j j| _| j j| _| j j| _d| _d| _d| _d| _d| _d| _d| _t j!| _"d| _#t$j%| _&| j
du rz|  j&t$j'O  _&d| _(d | _)d| _i | _*d S )NF
   r   T   )+settingscreate_new_gssapigssapiconnection_idpreferred_dialectssupported_dialects
connectionincoming_taskselected_dialectRequireSigningsigning_requiredencryption_requiredlast_treeidr   r   statusOutstandingResponsesEventOutstandingRequestsOutstandingResponsespending_tableSequenceWindowMaxTransactSizeMaxReadSizeMaxWriteSize
ServerGuidSupportsFileLeasingSupportsMultiCreditSupportsDirectoryLeasingSupportsMultiChannelSupportsPersistentHandlesSupportsEncryptionClientCapabilitiesNegotiateCapabilities	LARGE_MTUServerCapabilitiesClientSecurityModeNegotiateSecurityModeSMB2_NEGOTIATE_SIGNING_ENABLEDServerSecurityModeSMB2_NEGOTIATE_SIGNING_REQUIRED	SessionId
SessionKey%_SMBServerConnection__treeid_to_entry)selfr2   r8   r5   shutdown_evtr   r   r   __init__=   sH   







zSMBServerConnection.__init__c                    s   t |  | _| jS N)asynciocreate_task#_SMBServerConnection__handle_smb_inr9   r[   r   r   r   runs   s   zSMBServerConnection.runc              
      s   z%|  dI d H  | jd ur| j  | jd ur$| j I d H  W d S W d S  tyG } zt  |  d| I d H  W Y d }~d S d }~ww )Nz[INF] Stopping connection[ERR] %s)printr9   cancelr8   close	Exception	traceback	print_exc)r[   er   r   r   stopw   s   


"zSMBServerConnection.stopc                    s6   | j jd ur| j d| j d| I d H  d S d S )Nz[SMBSERVERCONN][z] )r2   log_callbackr5   )r[   msgr   r   r   re      s   $zSMBServerConnection.printc                 C   s   |  j d7  _ | j S Nr1   )r>   rb   r   r   r   get_new_tree_id   s   z#SMBServerConnection.get_new_tree_idc                    s
  zzzI| j  2 z?3 dH W }|du r n4|d dk r&td|d  |d dkr0td|d dkr:td|d dkrzt|}| d	| I dH  W n tya } ztd
d}~ww | jtjkrq| 	|I dH  n~| jtj
kr| |I dH  no| jtjkr|jjtjkr| |I dH  nY|jjtjkr| |I dH  nI|jjtjkr| |I dH  n9|jjtjkr| |I dH  n)|jjtjkr| |I dH  n|jjtjkr| |I dH  n	td|jj  q
|d dkr&t|}| d	| I dH  | jtjkr|jjtjkr| 	|I dH  n	td|jj  q
t dd|jj!  |jj!| j"v rJ| j"|jj! # I dH  | j"|jj!= q
6 W n% t$j%ya   Y W | # I dH  dS    t&'  Y W | # I dH  dS W | # I dH  dS | # I dH  w )z
		Waits from SMB message bytes from the transport in_queue, and fills the connection table.
		This function started automatically when calling connect.
		Pls don't touch it.
		Nr      zUnknown SMB packet type %s   z2SMB2_COMPRESSED_DATA_HEADER is not implemented yetz7SMB2_COMPRESSED_TRANSFORM_HEADER is not implemented yet   z[PACKET] %sz;Failed to parse SMB data. Probably not implemented feature.z SMB2 command not implemented! %s   z.SMBv1 message recieved! This is unexpected! %sr1   z*__handle_smb_in got new message with Id %s)(r8   readrh   r
   
from_bytesre   r?   r   r   	negotiater   session_setupr   headerCommandSMB2CommandTREE_CONNECTtree_connectCREATEcreateIOCTLioctlECHOechoQUERY_DIRECTORYquery_directoryCLOSErg   r	   r   SMB_COM_NEGOTIATEr   log	MessageIdrC   rl   r_   CancelledErrorri   rj   )r[   msg_datarn   rk   r   r   r   __handle_smb_in   s|   

;" z#SMBServerConnection.__handle_smb_inNc              
      sf  z| j tjkrLt|trd}|  jd7  _nd|j_|jjdu r%d|j_| j|j_	| j}|  jd7  _t
 | j|< | j| I dH  ||dfW S |jjtjur_| j|j_	|  jd7  _| j|j_|jjsld|j_| j tjkr||jjdu r|d|j_|jj	}t
 | j|< | j| I dH  ||dfW S  ty } zt  dd|fW  Y d}~S d}~ww )zp
		Sends an SMB message to teh remote endpoint.
		msg: SMB2Message or SMBMessage
		Returns: MessageId integer
		r   r1   N   )r?   r   r   
isinstancer	   rD   ry   CreditCharge	CreditReqr   r_   Eventr@   r8   writeto_bytesrz   r{   CANCELrX   r   rh   ri   rj   )r[   rn   compression_cb
message_idrk   r   r   r   sendSMB   s@   



zSMBServerConnection.sendSMBc              
      s\  zt |trd|jjv st |trt }t |_| j|j_tj	|j_
d|j_| j|j_| j|j_| j|j_| j|j_| j|j_tj |j_tj |j_| j |j_d|j_g |j_t |_tj|j_t j!|j_"d|j_#| $|I d H  tj	| _%t&j'| jv | _(t&j)| jv | _*t&j+| jv | _,t-j.| _/W d S  t0y } zt12  W Y d }~d S d }~ww )Nz	SMB 2.???r   r1   )3r   r	   commandDialectsr
   NEGOTIATE_REPLYrV   SecurityModeNegotiateDialectsSMB202DialectRevisionNegotiateContextCountrH   rR   CapabilitiesrE   rF   rG   datetimeutcnow
SystemTimeServerStartTimer4   get_mechtypes_listSecurityBufferNegotiateContextOffsetNegotiateContextListSMB2Header_SYNCry   r{   	NEGOTIATErz   SMB2HeaderFlagSMB2_FLAGS_SERVER_TO_REDIRFlagsr   r   r:   rP   MULTI_CHANNELrL   LEASINGrI   rQ   rJ   r   r   r?   rh   ri   rj   )r[   reqreplyrk   r   r   r   rw     sB    








zSMBServerConnection.negotiatec              
      s  d }z0d}| j dkr|  j d7  _ |dkr2t }t |_d|j_z| dI d H  | j|jjI d H \|j_}}| d|jj||f I d H  |d urQ||du r|jjd u rt }t |_tj	|j_| j
 I d H \|j_}|d ury|t |_tj|j_tj|j_| j |j_ d|j_d|j_tj|j_| |I d H  tj| _W W dS W n ty } zt|dd	krt |d }~ww |d
u rt |_tj|j_tj|j_| j |j_ d|j_d|j_tj |j_| |I d H  |du r/t |_tj|j_tj|j_| j |j_ d|j_d|j_tj|j_|j jtj!O  _d|j_| |I d H  tj| _W dS W d S  ty } zB| d| I d H  t |_tj|j_tj|j_|j jtj!O  _| j |j_ d|j_d|j_tj"|j_| |I d H  W Y d }~dS d }~ww )N   r   r1   z![INF] Calling authenticate_serverz&[INF] Authenticate results: %s, %s, %sF)FNPreauthTr   )TNrd   )#rX   r
   SESSION_SETUP_REPLYr   SessionFlagsre   r4   authenticate_serverBufferSMB2_SESSION_FLAG_IS_GUESTauthenticate_server_finishedr   ry   r{   SESSION_SETUPrz   r   r   r   r   r   r   SUCCESSStatusr   r   r   r?   rh   r(   findSMBKerberosPreauthFailedMORE_PROCESSING_REQUIREDSMB2_FLAGS_SIGNEDACCESS_DENIED)r[   rn   errmaxiterr   to_continuerk   r   r   r   rx   *  s   

 













L



z!SMBServerConnection.session_setuprn   c              
      s  zt t|j}t }t |_tj|j_	t
j|j_| j|j_d|j_|jj|j_tj|j_t |_z|jd^}}}}}td|  t| W n tyU   |j}Y nw | drctj|j_ntj|j_tj|j_tj |j_!t"j#|j_$d }| j%j&' D ]\}}	|( |( krt|	} nq|d u rtj)|j_| *|tj|jtj)I d H  W d S | + }
|
|j_,t-d ||
d| j.|
< | /|I d H  W d S  ty } zt01  W Y d }~d S d }~ww )Nr1   \zTREE_CONNECT: %szIPC$)r%   r   r&   )2typingcastTREE_CONNECT_REQr   r
   r   ry   r{   r|   rz   r   r   r   rX   r   r   r   r   r   TREE_CONNECT_REPLYr   splitre   rh   upperendswith	ShareTypePIPEDISK
ShareFlagsSMB2_SHAREFLAG_MANUAL_CACHINGTreeCapabilitiesSMB2_SHARE_CAP_NONEr   FileAccessMaskGENERIC_ALLMaximalAccessr2   sharesitemslowerBAD_NETWORK_NAMEsendSMB2rp   TreeIdr!   rZ   r   ri   rj   )r[   rn   r   r   _
share_namerestmappedkvr&   rk   r   r   r   r}     sV   









z SMBServerConnection.tree_connectc              
      s&  zzt t|j}|jtjkryt }t |_t	j
|j_tj|j_| j|j_d|j_|jj|j_tj|j_|jj|j_t |_|j|j_|j|j_|j|j_|j|j_d|j_d|j_|j|j_|j|j_d|j_| |t	j
|jtjI d H  W d S W d S  t y } zt!"  W Y d }~d S d }~ww )Nr1   r       )#r   r   	IOCTL_REQr   CtlCodeFSCTL_DFS_GET_REFERRALSr
   r   ry   r{   r   rz   r   r   r   rX   r   r   r   FS_DRIVER_REQUIREDr   r   	messageIdIOCTL_REPLYFileIdInputOffset
InputCountOutputOffsetOutputCount	Reserved2r   r   rh   ri   rj   r[   rn   r   r   rk   r   r   r   r     s:   









"zSMBServerConnection.ioctlc              
      sB  zt t|j}d }|jd u r| j|jj j}t	d|j
  | r(| s/td|j
 t }t |_tj|j_tj|j_| j|j_d|j_|jj|j_tj|j_t |_tj|j_tj |j_t!j"|j_!t#|$ j%|j_&t#|$ j'|j_(t#|$ j)|j_*t#|$ j)|j_+d|j_,d|j_-t.j/|j_.d|j_0d|j_1d|j_2n|jj| jvrtd|jj | j|jj }|d u rtd|jj |j}|j}|t3|4| }| std| |5 std| |5 rd}	t6|d	}t7|||	d
}
|
|j8|jj0< |$ }t }t |_tj|j_tj|j_| j|j_d|j_|jj|j_tj|j_t |_tj|j_tj |j_t!j"|j_!t#|j%|j_&t#|j'|j_(t#|j)|j_*t#|j)|j_+|j9|j_,|j9|j_-t.j:|j_.|
j;|j_0d|j_1d|j_2| <|tj|jtjI d H  W d S  ty } zt=>  W Y d }~d S d }~ww )NzOPENING SHARE %szShare %s does not existr1   r   Tree ID %s not foundz#Tree entry for Tree ID %s not foundzFile %s does not existzFile %s is not a filerb)r   r   r   )?r   r   
CREATE_REQr   NamerZ   ry   r   r   re   nameexistsis_dirrh   r
   r   r{   r~   rz   r   r   r   rX   r   r   r   r   r   CREATE_REPLYOplockLevelSMB2_OPLOCK_LEVEL_NONECreateOptionsFILE_WRITE_THROUGHCreateActionFILE_CREATEDr   statst_ctimeCreationTimest_atimeLastAccessTimest_mtimeLastWriteTime
ChangeTimeAllocationSize	EndofFiler   FILE_ATTRIBUTE_DIRECTORYr   CreateContextsOffsetCreateContextsLengthr   relative_tois_fileopenr   r$   st_sizeFILE_ATTRIBUTE_NORMALr   r   ri   rj   )r[   rn   r   r   sharer   te	file_name
local_pathr   fefstatrk   r   r   r   r     s   






















"zSMBServerConnection.createc           &   
      s  zgt t|j}|jj| jvrtd|jj | j|jj }|j}|}|j	r+|j	nd}|dv r3d}t
| ds;i | _|jj|jf}tj|jv sS|| jvsStj|jv rg }| D ]0}	|	j}
zddlm} dd l}||||
ssW qYW n ty   |dvrY qYY nw ||
 qYt|d||jd| j|< | j| }g }|j|jd  D ]}
||
 }	|	 }tt|j}tt|j }tt|j!}tt|j!}|	" rdn|j#}|	" rdn|j#}|	" rt$j%nt$j&}|
'd	}d
}|dj(dddd7 }|dj(dddd7 }||j(dddd7 }||j(dddd7 }||j(dddd7 }||j(dddd7 }||j(dddd7 }||j(dddd7 }||j)j(dddd7 }|jt*j+krl|t,|j(dddd7 }|dj(dddd7 }|| }n|jt*j-kr|t,|j(dddd7 }|| }n|jt*j.kr|t,|j(dddd7 }|dj(dddd7 }|dj(dddd7 }|dj(dddd7 }|d7 }|dj(dddd7 }|| }n|jt*j/krt0|dd}||j(dddd7 }|t,|j(dddd7 }|dj(dddd7 }|| }nU|jt*j1krN|t,|j(dddd7 }|dj(dddd7 }|dj(dddd7 }|dj(dddd7 }|d7 }|dj(dddd7 }t0|dd}||j(dddd7 }|| }nqt,|d dkrd|ddt,|d   7 }|| q|j2rq|j2nd}d
}d}t3|D ]m\}}t,|}|d d@ }|| } t,|}!|!| |kr nOd}"|d t,|k rt,||d  }#|!| |  |# |krd}"||7 }|d7 }|"rt4|}|j(dddd||!|!d < t5|}| r|d|  7 }q{	 q{| j|7  _t6 }$t7 |$_t8j9|$j_:t;j<|$j_| j=|$j_=|jj|$j_d|$j_>|jj?r|jj?nd|$j_?t,|dks2|dkrL|jt,|jkrLt@jA|$j_BtC |$_| D|t8j9|$jt@jAI d H  W d S t@jE|$j_BtF |$_||$j_G| D|t8j9|$jt@jEI d H  W d S  ty }% ztHI  W Y d }%~%d S d }%~%ww )Nr   r   )z\ r   .z. _dir_enum_stater   )glob2re)r   N)r*   r+   r,   r-   z	utf-16-ler      littleF)signed   Tr1   s                              st_ino    i     i)Jr   r   QUERY_DIRECTORY_REQr   ry   r   rZ   rh   r   FileNamehasattrr  r   QueryDirectoryFlagSMB2_RESTART_SCANSr   SMB2_REOPENiterdirr   aiosmb.commons.utils.glob2rer  rematchappendr)   FileInformationClassr*   r+   r   r   r   r  r  r  r   r  r   r
  r  encoder   valuer   FileFullDirectoryInformationlenFileDirectoryInformationFileBothDirectoryInformationFileIdFullDirectoryInformationgetattrFileIdBothDirectoryInformationOutputBufferLength	enumerate	bytearraybytesr
   r   r{   r   rz   r   r   rX   r   r   r   NO_MORE_FILESr   ERROR_REPLYr   r   QUERY_DIRECTORY_REPLYDatari   rj   )&r[   rn   r   r  r  	base_pathr,   	state_keyr*   childr   r  r+  statestcreation_timelast_access_timelast_write_timechange_timeallocation_sizeend_of_fileattrsfilename_bytesfixedentryr   max_lenbufferemittedicur_len
padded_lenpad_len	start_poscan_chain_nextnext_lenr   rk   r   r   r   r   3  s  
"









*
"
"z#SMBServerConnection.query_directoryc              
      s  zt t|j}t }t |_tj|j_	t
j|j_| j|j_|jj|j_d|j_|jj|j_tj|j_t |_tj|j_d|j_d }|jj| jv r^| j|jj }|j|jv r^|j|j}|rt|jrtz|j  W n	 tys   Y nw tj|jv r|d ur|j ! }t"t#|j$|j_%t"t#|j&|j_'t"t#|j(|j_)t"t#|j(|j_*|j + rdn|j,|j_-|j + rdn|j,|j_.|j + rt/j0nt/j1j2|j_/tj|j_| 3|I d H  W d S  ty } zt45  W Y d }~d S d }~ww )Nr1   r   )6r   r   	CLOSE_REQr   r
   r   ry   r{   r   rz   r   r   r   rX   r   r   r   r   r   r   CLOSE_REPLY	CloseFlagNONEReservedrZ   r   r$   popr   rg   rh    SMB2_CLOSE_FLAG_POSTQUERY_ATTRIBr   r   r   r   r  r  r  r  r  r  r  r   r  r  r	  r   r
  r  r0  r   ri   rj   )r[   rn   r   r   r  r  rD  rk   r   r   r   rg     sR   







zSMBServerConnection.closec              
      s   zIt t|j}t }t |_tj|j_	t
j|j_| j|j_|jjr'|jjnd|j_|jjr3|jjnd|j_tj|j_t |_| |I d H  W d S  tya } zt  W Y d }~d S d }~ww ro   )r   r   ECHO_REQr   r
   r   ry   r{   r   rz   r   r   r   rX   r   r   r   r   r   
ECHO_REPLYr   rh   ri   rj   r   r   r   r   r     s"   



zSMBServerConnection.echoorgiginatorr   c                    s   t d|jj  t }t |_|jj|j_||j_tj|j_| j	|j_	|jj
|j_
|jjr3|jjnd|j_||j_||_| |I d H  d S )Nz,[DEBUG] sending SMB2 message with MessageId r1   )re   ry   r   r
   r   rz   r   r   r   rX   r   r   r   r   r   )r[   rb  r   r   r?   replymsgr   r   r   r     s   

zSMBServerConnection.sendSMB2r^   )r   r   r   r_   r   r]   rc   rl   re   rp   ra   r   rw   rx   r
   r}   r   r   r   rg   r   r   r   r{   r   r   r   r   r   r/   <   s$    6
I1&a1Y &*r/   )+enumr   r_   r   ri   r   dataclassesr   r   pathlibr   aiosmbr   aiosmb.commons.exceptions!aiosmb.protocol.smb.command_codesr   aiosmb.wintypes.ntstatusr   aiosmb.protocol.smb.messager	   aiosmb.protocol.smb.commandsaiosmb.protocol.smb2.messager
   *aiosmb.protocol.smb2.commands.tree_connectaiosmb.protocol.smb2.commandsaiosmb.protocol.smb2.headers"aiosmb.protocol.smb2.command_codesaiosmb.protocol.common.aiosmb.wintypes.dtyp.constrcuted_security.guid*aiosmb.protocol.smb2.commands.sessionsetup$aiosmb.protocol.smb2.commands.create#aiosmb.wintypes.fscc.FileAttributesr   -aiosmb.wintypes.fscc.structures.fileinfoclassr   r   r   Enumr   r   r!   r)   r/   r   r   r   r   <module>   sD    