Various cosmetic changes.
[wine] / dlls / dplayx / name_server.c
1 /* DPLAYX.DLL name server implementation
2  *
3  * Copyright 2000-2001 - 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   BOOL bNsIsLocal;
48   LPVOID lpLocalAddrHdr;  /* FIXME: Not yet used */
49   LPVOID lpRemoteAddrHdr; /* FIXME: Not yet used */
50 }; 
51 typedef struct NSCache NSCache, *lpNSCache;
52
53 /* Function prototypes */
54 DPQ_DECL_DELETECB( cbDeleteNSNodeFromHeap, lpNSCacheData );
55
56 /* Name Server functions 
57  * --------------------- 
58  */
59 void NS_SetLocalComputerAsNameServer( LPCDPSESSIONDESC2 lpsd, LPVOID lpNSInfo )
60 {
61 #if 0
62   /* FIXME: Remove this method? */
63   DPLAYX_SetLocalSession( lpsd );
64 #endif
65   lpNSCache lpCache = (lpNSCache)lpNSInfo;
66
67   lpCache->bNsIsLocal = TRUE;
68 }
69
70 void NS_SetRemoteComputerAsNameServer( LPCDPSESSIONDESC2 lpsd, LPVOID lpNSInfo )
71 {
72   lpNSCache lpCache = (lpNSCache)lpNSInfo;
73
74   lpCache->bNsIsLocal = FALSE;
75 }
76
77 DPQ_DECL_COMPARECB( cbUglyPig, GUID )
78 {
79   return IsEqualGUID( elem1, elem2 );
80 }
81
82 /* Store the given NS remote address for future reference */
83 /* FIXME: LPDPMSG_ENUMSESSIONSREPLY should be const */
84 void NS_AddRemoteComputerAsNameServer( LPCVOID                   lpcNSAddrHdr,
85                                        DWORD                     dwHdrSize,
86                                        LPDPMSG_ENUMSESSIONSREPLY lpMsg,
87                                        LPVOID                    lpNSInfo )
88 {
89   DWORD len;
90   lpNSCache     lpCache = (lpNSCache)lpNSInfo;
91   lpNSCacheData lpCacheNode;
92
93   TRACE( "%p, %p, %p\n", lpcNSAddrHdr, lpMsg, lpNSInfo );
94
95   /* See if we can find this session. If we can, remove it as it's a dup */
96   DPQ_REMOVE_ENTRY_CB( lpCache->first, next, data->guidInstance, cbUglyPig,
97                        lpMsg->sd.guidInstance, lpCacheNode );
98
99   if( lpCacheNode != NULL )
100   {
101     TRACE( "Duplicate session entry for %s removed - updated version kept\n",
102            debugstr_guid( &lpCacheNode->data->guidInstance ) );
103     cbDeleteNSNodeFromHeap( lpCacheNode );
104   }
105
106   /* Add this to the list */
107   lpCacheNode = (lpNSCacheData)HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 
108                                           sizeof( *lpCacheNode ) );
109
110   if( lpCacheNode == NULL )
111   {
112     ERR( "no memory for NS node\n" );
113     return;
114   }
115
116   lpCacheNode->lpNSAddrHdr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
117                                         dwHdrSize );
118   CopyMemory( lpCacheNode->lpNSAddrHdr, lpcNSAddrHdr, dwHdrSize );
119               
120
121   lpCacheNode->data = (LPDPSESSIONDESC2)HeapAlloc( GetProcessHeap(),
122                                                    HEAP_ZERO_MEMORY, 
123                                                    sizeof( *(lpCacheNode->data) ) );
124
125   if( lpCacheNode->data == NULL )
126   {
127     ERR( "no memory for SESSIONDESC2\n" );
128     return;
129   }
130
131   CopyMemory( lpCacheNode->data, &lpMsg->sd, sizeof( *lpCacheNode->data ) );
132   len = WideCharToMultiByte( CP_ACP, 0, (LPWSTR)(lpMsg+1), -1, NULL, 0, NULL, NULL );
133   if ((lpCacheNode->data->u1.lpszSessionNameA = HeapAlloc( GetProcessHeap(), 0, len )))
134   {
135       WideCharToMultiByte( CP_ACP, 0, (LPWSTR)(lpMsg+1), -1,
136                            lpCacheNode->data->u1.lpszSessionNameA, len, NULL, NULL );
137   }
138
139   lpCacheNode->dwTime = timeGetTime();
140
141   DPQ_INSERT(lpCache->first, lpCacheNode, next );
142
143   lpCache->present = lpCacheNode;
144
145   /* Use this message as an oportunity to weed out any old sessions so 
146    * that we don't enum them again 
147    */
148   NS_PruneSessionCache( lpNSInfo );
149 }
150
151 LPVOID NS_GetNSAddr( LPVOID lpNSInfo )
152 {
153   lpNSCache lpCache = (lpNSCache)lpNSInfo;
154
155   FIXME( ":quick stub\n" );
156
157   /* Ok. Cheat and don't search for the correct stuff just take the first.
158    * FIXME: In the future how are we to know what is _THE_ enum we used?
159    *        This is going to have to go into dplay somehow. Perhaps it
160    *        comes back with app server id for the join command! Oh...that
161    *        must be it. That would make this method obsolete once that's
162    *        in place.
163    */
164 #if 1
165   return lpCache->first.lpQHFirst->lpNSAddrHdr;
166 #else
167   /* FIXME: Should convert over to this */
168   return lpCache->bNsIsLocal ? lpCache->lpLocalAddrHdr
169                              : lpCache->lpRemoteAddrHdr;
170 #endif
171 }
172
173 /* Get the magic number associated with the Name Server */
174 DWORD NS_GetNsMagic( LPVOID lpNSInfo )
175 {
176   LPDWORD lpHdrInfo = (LPDWORD)NS_GetNSAddr( lpNSInfo );
177
178   return lpHdrInfo[1];
179 }
180
181 /* Get the magic number associated with the non NS end */
182 DWORD NS_GetOtherMagic( LPVOID lpNSInfo )
183 {
184   lpNSCache lpCache = (lpNSCache)lpNSInfo;
185
186   return ((LPDWORD)lpCache->lpLocalAddrHdr)[1];
187 }
188
189 void NS_SetLocalAddr( LPVOID lpNSInfo, LPCVOID lpHdr, DWORD dwHdrSize )
190 {
191   lpNSCache lpCache = (lpNSCache)lpNSInfo;
192
193   lpCache->lpLocalAddrHdr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, dwHdrSize );
194
195   CopyMemory( lpCache->lpLocalAddrHdr, lpHdr, dwHdrSize );
196 }
197
198 /* This function is responsible for sending a request for all other known
199    nameservers to send us what sessions they have registered locally
200  */
201 HRESULT NS_SendSessionRequestBroadcast( LPCGUID lpcGuid,
202                                         DWORD dwFlags,
203                                         LPSPINITDATA lpSpData )
204                                      
205 {
206   DPSP_ENUMSESSIONSDATA data;
207   LPDPMSG_ENUMSESSIONSREQUEST lpMsg;
208
209   TRACE( "enumerating for guid %s\n", debugstr_guid( lpcGuid ) );
210
211   /* Get the SP to deal with sending the EnumSessions request */
212   FIXME( ": not all data fields are correct\n" );
213
214   data.dwMessageSize = lpSpData->dwSPHeaderSize + sizeof( *lpMsg ); /*FIXME!*/
215   data.lpMessage = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 
216                               data.dwMessageSize );
217   data.lpISP = lpSpData->lpISP;
218   data.bReturnStatus = (dwFlags & DPENUMSESSIONS_RETURNSTATUS) ? TRUE : FALSE;
219
220
221   lpMsg = (LPDPMSG_ENUMSESSIONSREQUEST)(((BYTE*)data.lpMessage)+lpSpData->dwSPHeaderSize); 
222
223   /* Setup EnumSession reqest message */
224   lpMsg->envelope.dwMagic    = DPMSGMAGIC_DPLAYMSG;
225   lpMsg->envelope.wCommandId = DPMSGCMD_ENUMSESSIONSREQUEST;
226   lpMsg->envelope.wVersion   = DPMSGVER_DP6;
227
228   lpMsg->dwPasswordSize = 0; /* FIXME: If enumerating passwords..? */
229   lpMsg->dwFlags        = dwFlags;
230
231   CopyMemory( &lpMsg->guidApplication, lpcGuid, sizeof( *lpcGuid ) );
232
233   return (lpSpData->lpCB->EnumSessions)( &data ); 
234 }
235
236 /* Delete a name server node which has been allocated on the heap */
237 DPQ_DECL_DELETECB( cbDeleteNSNodeFromHeap, lpNSCacheData )
238 {
239   /* NOTE: This proc doesn't deal with the walking pointer */
240
241   /* FIXME: Memory leak on data (contained ptrs) */
242   HeapFree( GetProcessHeap(), 0, elem->data );
243   HeapFree( GetProcessHeap(), 0, elem->lpNSAddrHdr );
244   HeapFree( GetProcessHeap(), 0, elem );
245 }
246
247 /* Render all data in a session cache invalid */
248 void NS_InvalidateSessionCache( LPVOID lpNSInfo )
249 {
250   lpNSCache lpCache = (lpNSCache)lpNSInfo;
251
252   if( lpCache == NULL )
253   {
254     ERR( ": invalidate non existant cache\n" );
255     return;
256   }
257
258   DPQ_DELETEQ( lpCache->first, next, lpNSCacheData, cbDeleteNSNodeFromHeap );
259
260   /* NULL out the walking pointer */
261   lpCache->present = NULL;
262
263   lpCache->bNsIsLocal = FALSE;
264
265 }
266
267 /* Create and initialize a session cache */
268 BOOL NS_InitializeSessionCache( LPVOID* lplpNSInfo )
269 {
270   lpNSCache lpCache = (lpNSCache)HeapAlloc( GetProcessHeap(),
271                                             HEAP_ZERO_MEMORY,
272                                             sizeof( *lpCache ) );
273
274   *lplpNSInfo = lpCache;
275
276   if( lpCache == NULL )
277   {
278     return FALSE;
279   }
280
281   DPQ_INIT(lpCache->first);
282   lpCache->present = NULL;
283
284   lpCache->bNsIsLocal = FALSE;
285
286   return TRUE;
287 }
288
289 /* Delete a session cache */
290 void NS_DeleteSessionCache( LPVOID lpNSInfo )
291 {
292   NS_InvalidateSessionCache( (lpNSCache)lpNSInfo );
293 }
294
295 /* Reinitialize the present pointer for this cache */
296 void NS_ResetSessionEnumeration( LPVOID lpNSInfo )
297 {
298   ((lpNSCache)lpNSInfo)->present = ((lpNSCache)lpNSInfo)->first.lpQHFirst;
299 }
300
301 LPDPSESSIONDESC2 NS_WalkSessions( LPVOID lpNSInfo )
302 {
303   LPDPSESSIONDESC2 lpSessionDesc;
304   lpNSCache lpCache = (lpNSCache)lpNSInfo;
305
306   /* FIXME: The pointers could disappear when walking if a prune happens */
307
308   /* Test for end of the list */ 
309   if( lpCache->present == NULL )
310   {
311     return NULL;
312   }
313
314   lpSessionDesc = lpCache->present->data;
315
316   /* Advance tracking pointer */
317   lpCache->present = lpCache->present->next.lpQNext;
318
319   return lpSessionDesc;
320 }
321
322 /* This method should check to see if there are any sessions which are
323  * older than the criteria. If so, just delete that information.
324  */
325 /* FIXME: This needs to be called by some periodic timer */
326 void NS_PruneSessionCache( LPVOID lpNSInfo )
327 {
328   lpNSCache     lpCache = lpNSInfo;
329
330   const DWORD dwPresentTime = timeGetTime();
331   const DWORD dwPrunePeriod = DPMSG_WAIT_60_SECS; /* is 60 secs enough? */
332
333   /* This silly little algorithm is based on the fact we keep entries in 
334    * the queue in a time based order. It also assumes that it is not possible
335    * to wrap around over yourself (which is not unreasonable).
336    * The if statements verify if the first entry in the queue is less 
337    * than dwPrunePeriod old depending on the "clock" roll over.
338    */
339   for( ;; )
340   {
341     lpNSCacheData lpFirstData;
342
343     if( DPQ_IS_EMPTY(lpCache->first) )
344     {
345       /* Nothing to prune */
346       break;
347     }
348
349     /* Deal with time in a wrap around safe manner - unsigned arithmatic.
350      * Check the difference in time */
351     if( (dwPresentTime - (DPQ_FIRST(lpCache->first)->dwTime)) < dwPrunePeriod )
352     {
353       /* First entry has not expired yet; don't prune */
354       break;
355     }
356
357     lpFirstData = DPQ_FIRST(lpCache->first);
358     DPQ_REMOVE( lpCache->first, DPQ_FIRST(lpCache->first), next );
359     cbDeleteNSNodeFromHeap( lpFirstData );
360   }
361
362 }
363
364 /* NAME SERVER Message stuff */
365 void NS_ReplyToEnumSessionsRequest( LPCVOID lpcMsg, 
366                                     LPVOID* lplpReplyData,
367                                     LPDWORD lpdwReplySize,
368                                     IDirectPlay2Impl* lpDP )
369 {
370   LPDPMSG_ENUMSESSIONSREPLY rmsg;
371   DWORD dwVariableSize;
372   DWORD dwVariableLen;
373   /* LPCDPMSG_ENUMSESSIONSREQUEST msg = (LPDPMSG_ENUMSESSIONSREQUEST)lpcMsg; */
374   BOOL bAnsi = TRUE; /* FIXME: This needs to be in the DPLAY interface */
375
376   FIXME( ": few fixed + need to check request for response\n" );
377
378   if (bAnsi)
379   {
380       dwVariableLen = MultiByteToWideChar( CP_ACP, 0,
381                                            lpDP->dp2->lpSessionDesc->u1.lpszSessionNameA,
382                                            -1, NULL, 0 );
383   }
384   else
385   {
386       dwVariableLen = strlenW( lpDP->dp2->lpSessionDesc->u1.lpszSessionName ) + 1;
387   }
388
389   dwVariableSize = dwVariableLen * sizeof( WCHAR );
390
391   *lpdwReplySize = lpDP->dp2->spData.dwSPHeaderSize +
392                      sizeof( *rmsg ) + dwVariableSize;
393   *lplpReplyData = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
394                               *lpdwReplySize );
395
396   rmsg = (LPDPMSG_ENUMSESSIONSREPLY)( (BYTE*)*lplpReplyData + 
397                                              lpDP->dp2->spData.dwSPHeaderSize);
398
399   rmsg->envelope.dwMagic    = DPMSGMAGIC_DPLAYMSG; 
400   rmsg->envelope.wCommandId = DPMSGCMD_ENUMSESSIONSREPLY;
401   rmsg->envelope.wVersion   = DPMSGVER_DP6;
402
403   CopyMemory( &rmsg->sd, lpDP->dp2->lpSessionDesc, 
404               sizeof( lpDP->dp2->lpSessionDesc->dwSize ) ); 
405   rmsg->dwUnknown = 0x0000005c;
406   if( bAnsi )
407   {
408       MultiByteToWideChar( CP_ACP, 0, lpDP->dp2->lpSessionDesc->u1.lpszSessionNameA, -1,
409                            (LPWSTR)(rmsg+1), dwVariableLen );
410   }
411   else
412   {
413       strcpyW( (LPWSTR)(rmsg+1), lpDP->dp2->lpSessionDesc->u1.lpszSessionName );
414   }
415 }