Updated.
[wine] / dlls / dplayx / name_server.c
1 /* DPLAYX.DLL name server implementation
2  *
3  * Copyright 2000 - Peter Hunnisett
4  *
5  * <presently under construction - contact hunnise@nortelnetworks.com>
6  *
7  */
8  
9 /* NOTE: Methods with the NS_ prefix are name server methods */
10
11 #include <string.h>
12 #include "winbase.h"
13 #include "winnls.h"
14 #include "wine/unicode.h"
15 #include "debugtools.h"
16 #include "mmsystem.h"
17
18 #include "dplayx_global.h"
19 #include "name_server.h"
20 #include "dplaysp.h"
21 #include "dplayx_messages.h"
22 #include "dplayx_queue.h"
23
24 /* FIXME: Need to create a crit section, store and use it */
25
26 DEFAULT_DEBUG_CHANNEL(dplay);
27
28 /* NS specific structures */
29 struct NSCacheData
30 {
31   DPQ_ENTRY(NSCacheData) next;
32
33   DWORD dwTime; /* Time at which data was last known valid */
34   LPDPSESSIONDESC2 data;
35
36   LPVOID lpNSAddrHdr;
37
38 };
39 typedef struct NSCacheData NSCacheData, *lpNSCacheData;
40
41 struct NSCache
42 {
43   lpNSCacheData present; /* keep track of what is to be looked at when walking */
44
45   DPQ_HEAD(NSCacheData) first;
46 }; 
47 typedef struct NSCache NSCache, *lpNSCache;
48
49 /* Function prototypes */
50 DPQ_DECL_DELETECB( cbDeleteNSNodeFromHeap, lpNSCacheData );
51
52 /* Name Server functions 
53  * --------------------- 
54  */
55 void NS_SetLocalComputerAsNameServer( LPCDPSESSIONDESC2 lpsd )
56 {
57 #if 0
58   /* FIXME: Remove this method? */
59   DPLAYX_SetLocalSession( lpsd );
60 #endif
61 }
62
63 DPQ_DECL_COMPARECB( cbUglyPig, GUID )
64 {
65   return IsEqualGUID( elem1, elem2 );
66 }
67
68 /* Store the given NS remote address for future reference */
69 void NS_SetRemoteComputerAsNameServer( LPVOID                    lpNSAddrHdr,
70                                        DWORD                     dwHdrSize,
71                                        LPDPMSG_ENUMSESSIONSREPLY lpMsg,
72                                        LPVOID                    lpNSInfo )
73 {
74   DWORD len;
75   lpNSCache     lpCache = (lpNSCache)lpNSInfo;
76   lpNSCacheData lpCacheNode;
77
78   TRACE( "%p, %p, %p\n", lpNSAddrHdr, lpMsg, lpNSInfo );
79
80   /* FIXME: Should check to see if the reply is for an existing session. If
81    *        so we remove the old and add the new so oldest is at front.
82    */
83
84   /* See if we can find this session. If we can, remove it as it's a dup */
85   DPQ_REMOVE_ENTRY_CB( lpCache->first, next, data->guidInstance, cbUglyPig,
86                      lpMsg->sd.guidInstance, lpCacheNode );
87
88   if( lpCacheNode != NULL )
89   {
90     TRACE( "Duplicate session entry for %s removed - updated version kept\n",
91            debugstr_guid( &lpCacheNode->data->guidInstance ) );
92     cbDeleteNSNodeFromHeap( lpCacheNode );
93   }
94
95   /* Add this to the list */
96   lpCacheNode = (lpNSCacheData)HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 
97                                           sizeof( *lpCacheNode ) );
98
99   if( lpCacheNode == NULL )
100   {
101     ERR( "no memory for NS node\n" );
102     return;
103   }
104
105   lpCacheNode->lpNSAddrHdr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
106                                         dwHdrSize );
107   CopyMemory( lpCacheNode->lpNSAddrHdr, lpNSAddrHdr, dwHdrSize );
108               
109
110   lpCacheNode->data = (LPDPSESSIONDESC2)HeapAlloc( GetProcessHeap(),
111                                                    HEAP_ZERO_MEMORY, 
112                                                    sizeof( *lpCacheNode->data ) );
113
114   if( lpCacheNode->data == NULL )
115   {
116     ERR( "no memory for SESSIONDESC2\n" );
117     return;
118   }
119
120   CopyMemory( lpCacheNode->data, &lpMsg->sd, sizeof( *lpCacheNode->data ) );
121   len = WideCharToMultiByte( CP_ACP, 0, (LPWSTR)(lpMsg+1), -1, NULL, 0, NULL, NULL );
122   if ((lpCacheNode->data->u1.lpszSessionNameA = HeapAlloc( GetProcessHeap(), 0, len )))
123       WideCharToMultiByte( CP_ACP, 0, (LPWSTR)(lpMsg+1), -1,
124                            lpCacheNode->data->u1.lpszSessionNameA, len, NULL, NULL );
125
126   lpCacheNode->dwTime = timeGetTime();
127
128   DPQ_INSERT(lpCache->first, lpCacheNode, next );
129
130   lpCache->present = lpCacheNode;
131
132   /* Use this message as an oportunity to weed out any old sessions so 
133    * that we don't enum them again 
134    */
135   NS_PruneSessionCache( lpNSInfo );
136 }
137
138 LPVOID NS_GetNSAddr( LPVOID lpNSInfo )
139 {
140   lpNSCache lpCache = (lpNSCache)lpNSInfo;
141
142   FIXME( ":quick stub\n" );
143
144   /* Ok. Cheat and don't search for the correct stuff just take the first.
145    * FIXME: In the future how are we to know what is _THE_ enum we used?
146    *        This is going to have to go into dplay somehow. Perhaps it
147    *        comes back with app server id for the join command! Oh...that
148    *        must be it. That would make this method obsolete once that's
149    *        in place.
150    */
151
152   return lpCache->first.lpQHFirst->lpNSAddrHdr;
153 }
154
155 /* This function is responsible for sending a request for all other known
156    nameservers to send us what sessions they have registered locally
157  */
158 HRESULT NS_SendSessionRequestBroadcast( LPCGUID lpcGuid,
159                                         DWORD dwFlags,
160                                         LPSPINITDATA lpSpData )
161                                      
162 {
163   DPSP_ENUMSESSIONSDATA data;
164   LPDPMSG_ENUMSESSIONSREQUEST lpMsg;
165
166   TRACE( "enumerating for guid %s\n", debugstr_guid( lpcGuid ) );
167
168   /* Get the SP to deal with sending the EnumSessions request */
169   FIXME( ": not all data fields are correct\n" );
170
171   data.dwMessageSize = lpSpData->dwSPHeaderSize + sizeof( *lpMsg ); /*FIXME!*/
172   data.lpMessage = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 
173                               data.dwMessageSize );
174   data.lpISP = lpSpData->lpISP;
175   data.bReturnStatus = (dwFlags & DPENUMSESSIONS_RETURNSTATUS) ? TRUE : FALSE;
176
177
178   lpMsg = (LPDPMSG_ENUMSESSIONSREQUEST)(((BYTE*)data.lpMessage)+lpSpData->dwSPHeaderSize); 
179
180   /* Setup EnumSession reqest message */
181   lpMsg->envelope.dwMagic    = DPMSGMAGIC_DPLAYMSG;
182   lpMsg->envelope.wCommandId = DPMSGCMD_ENUMSESSIONSREQUEST;
183   lpMsg->envelope.wVersion   = DPMSGVER_DP6;
184
185   lpMsg->dwPasswordSize = 0; /* FIXME: If enumerating passwords..? */
186   lpMsg->dwFlags        = dwFlags;
187
188   CopyMemory( &lpMsg->guidApplication, lpcGuid, sizeof( *lpcGuid ) );
189
190   return (lpSpData->lpCB->EnumSessions)( &data ); 
191 }
192
193 /* Delete a name server node which has been allocated on the heap */
194 DPQ_DECL_DELETECB( cbDeleteNSNodeFromHeap, lpNSCacheData )
195 {
196   /* NOTE: This proc doesn't deal with the walking pointer */
197
198   /* FIXME: Memory leak on data (contained ptrs) */
199   HeapFree( GetProcessHeap(), 0, elem->data );
200   HeapFree( GetProcessHeap(), 0, elem->lpNSAddrHdr );
201   HeapFree( GetProcessHeap(), 0, elem );
202 }
203
204 /* Render all data in a session cache invalid */
205 void NS_InvalidateSessionCache( LPVOID lpNSInfo )
206 {
207   lpNSCache lpCache = (lpNSCache)lpNSInfo;
208
209   if( lpCache == NULL )
210   {
211     ERR( ": invalidate non existant cache\n" );
212     return;
213   }
214
215   DPQ_DELETEQ( lpCache->first, next, lpNSCacheData, cbDeleteNSNodeFromHeap );
216
217   /* NULL out the walking pointer */
218   lpCache->present = NULL;
219 }
220
221 /* Create and initialize a session cache */
222 BOOL NS_InitializeSessionCache( LPVOID* lplpNSInfo )
223 {
224   lpNSCache lpCache = (lpNSCache)HeapAlloc( GetProcessHeap(),
225                                             HEAP_ZERO_MEMORY,
226                                             sizeof( *lpCache ) );
227
228   *lplpNSInfo = lpCache;
229
230   if( lpCache == NULL )
231   {
232     return FALSE;
233   }
234
235   DPQ_INIT(lpCache->first);
236   lpCache->present = NULL;
237
238   return TRUE;
239 }
240
241 /* Delete a session cache */
242 void NS_DeleteSessionCache( LPVOID lpNSInfo )
243 {
244   NS_InvalidateSessionCache( (lpNSCache)lpNSInfo );
245 }
246
247 /* Reinitialize the present pointer for this cache */
248 void NS_ResetSessionEnumeration( LPVOID lpNSInfo )
249 {
250   ((lpNSCache)lpNSInfo)->present = ((lpNSCache)lpNSInfo)->first.lpQHFirst;
251 }
252
253 LPDPSESSIONDESC2 NS_WalkSessions( LPVOID lpNSInfo )
254 {
255   LPDPSESSIONDESC2 lpSessionDesc;
256   lpNSCache lpCache = (lpNSCache)lpNSInfo;
257
258   /* FIXME: The pointers could disappear when walking if a prune happens */
259
260   /* Test for end of the list */ 
261   if( lpCache->present == NULL )
262   {
263     return NULL;
264   }
265
266   lpSessionDesc = lpCache->present->data;
267
268   /* Advance tracking pointer */
269   lpCache->present = lpCache->present->next.lpQNext;
270
271   return lpSessionDesc;
272 }
273
274 /* This method should check to see if there are any sessions which are
275  * older than the criteria. If so, just delete that information.
276  */
277 /* FIXME: This needs to be called by some periodic timer */
278 void NS_PruneSessionCache( LPVOID lpNSInfo )
279 {
280   lpNSCache     lpCache = lpNSInfo;
281
282   const DWORD dwPresentTime = timeGetTime();
283   const DWORD dwPrunePeriod = 60000; /* is 60 secs enough? */ 
284   const DWORD dwPruneTime   = dwPresentTime - dwPrunePeriod;
285
286   /* This silly little algorithm is based on the fact we keep entries in 
287    * the queue in a time based order. It also assumes that it is not possible
288    * to wrap around over yourself (which is not unreasonable).
289    * The if statements verify if the first entry in the queue is less 
290    * than dwPrunePeriod old depending on the "clock" roll over.
291    */
292   for( ;; )
293   {
294     lpNSCacheData lpFirstData;
295
296     if( DPQ_IS_EMPTY(lpCache->first) )
297     {
298       /* Nothing to prune */
299       break;
300     }
301
302     if( dwPruneTime > dwPresentTime ) /* 0 <= dwPresentTime <= dwPrunePeriod */
303     {
304       if( ( DPQ_FIRST(lpCache->first)->dwTime <= dwPresentTime ) ||
305           ( DPQ_FIRST(lpCache->first)->dwTime > dwPruneTime )
306         )
307       {
308         /* Less than dwPrunePeriod old - keep */
309         break; 
310       }
311     }
312     else /* dwPrunePeriod <= dwPresentTime <= max dword */
313     {
314       if( ( DPQ_FIRST(lpCache->first)->dwTime <= dwPresentTime ) &&
315           ( DPQ_FIRST(lpCache->first)->dwTime > dwPruneTime ) 
316         )
317       {
318         /* Less than dwPrunePeriod old - keep */
319         break;
320       }
321     }
322
323     lpFirstData = DPQ_FIRST(lpCache->first);
324     DPQ_REMOVE( lpCache->first, DPQ_FIRST(lpCache->first), next );
325     cbDeleteNSNodeFromHeap( lpFirstData );
326   }
327
328 }
329
330 /* NAME SERVER Message stuff */
331 void NS_ReplyToEnumSessionsRequest( LPVOID lpMsg, 
332                                     LPDPSP_REPLYDATA lpReplyData,
333                                     IDirectPlay2Impl* lpDP )
334 {
335   LPDPMSG_ENUMSESSIONSREPLY rmsg;
336   DWORD dwVariableSize;
337   DWORD dwVariableLen;
338   /* LPDPMSG_ENUMSESSIONSREQUEST msg = (LPDPMSG_ENUMSESSIONSREQUEST)lpMsg; */
339   BOOL bAnsi = TRUE; /* FIXME: This needs to be in the DPLAY interface */
340
341   FIXME( ": few fixed + need to check request for response\n" );
342
343   if (bAnsi)
344       dwVariableLen = MultiByteToWideChar( CP_ACP, 0,
345                                            lpDP->dp2->lpSessionDesc->u1.lpszSessionNameA,
346                                            -1, NULL, 0 );
347   else
348       dwVariableLen = strlenW( lpDP->dp2->lpSessionDesc->u1.lpszSessionName ) + 1;
349
350   dwVariableSize = dwVariableLen * sizeof( WCHAR );
351
352   lpReplyData->dwMessageSize = lpDP->dp2->spData.dwSPHeaderSize +
353                                  sizeof( *rmsg ) + dwVariableSize;
354   lpReplyData->lpMessage     = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
355                                           lpReplyData->dwMessageSize );
356
357   rmsg = (LPDPMSG_ENUMSESSIONSREPLY)( (BYTE*)lpReplyData->lpMessage + 
358                                              lpDP->dp2->spData.dwSPHeaderSize);
359
360   rmsg->envelope.dwMagic    = DPMSGMAGIC_DPLAYMSG; 
361   rmsg->envelope.wCommandId = DPMSGCMD_ENUMSESSIONSREPLY;
362   rmsg->envelope.wVersion   = DPMSGVER_DP6;
363
364   CopyMemory( &rmsg->sd, lpDP->dp2->lpSessionDesc, 
365               sizeof( lpDP->dp2->lpSessionDesc->dwSize ) ); 
366   rmsg->dwUnknown = 0x0000005c;
367   if( bAnsi )
368       MultiByteToWideChar( CP_ACP, 0, lpDP->dp2->lpSessionDesc->u1.lpszSessionNameA, -1,
369                            (LPWSTR)(rmsg+1), dwVariableLen );
370   else
371       strcpyW( (LPWSTR)(rmsg+1), lpDP->dp2->lpSessionDesc->u1.lpszSessionName );
372 }