shell32/tests: Remove spaces before '\n's in traces.
[wine] / dlls / secur32 / schannel.c
1 /* Copyright (C) 2005 Juan Lang
2  * Copyright 2008 Henri Verbeet
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  *
18  * This file implements the schannel provider, or, the SSL/TLS implementations.
19  * FIXME: It should be rather obvious that this file is empty of any
20  * implementation.
21  */
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <stdarg.h>
26 #include <errno.h>
27 #include <limits.h>
28 #ifdef SONAME_LIBGNUTLS
29 #include <gnutls/gnutls.h>
30 #endif
31
32 #include "windef.h"
33 #include "winbase.h"
34 #include "winnls.h"
35 #include "sspi.h"
36 #include "schannel.h"
37 #include "secur32_priv.h"
38 #include "wine/debug.h"
39 #include "wine/library.h"
40
41 WINE_DEFAULT_DEBUG_CHANNEL(secur32);
42
43 #ifdef SONAME_LIBGNUTLS
44
45 static void *libgnutls_handle;
46 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
47 MAKE_FUNCPTR(gnutls_alert_get);
48 MAKE_FUNCPTR(gnutls_alert_get_name);
49 MAKE_FUNCPTR(gnutls_certificate_allocate_credentials);
50 MAKE_FUNCPTR(gnutls_certificate_free_credentials);
51 MAKE_FUNCPTR(gnutls_certificate_get_peers);
52 MAKE_FUNCPTR(gnutls_cipher_get);
53 MAKE_FUNCPTR(gnutls_cipher_get_key_size);
54 MAKE_FUNCPTR(gnutls_credentials_set);
55 MAKE_FUNCPTR(gnutls_deinit);
56 MAKE_FUNCPTR(gnutls_global_deinit);
57 MAKE_FUNCPTR(gnutls_global_init);
58 MAKE_FUNCPTR(gnutls_global_set_log_function);
59 MAKE_FUNCPTR(gnutls_global_set_log_level);
60 MAKE_FUNCPTR(gnutls_handshake);
61 MAKE_FUNCPTR(gnutls_init);
62 MAKE_FUNCPTR(gnutls_kx_get);
63 MAKE_FUNCPTR(gnutls_mac_get);
64 MAKE_FUNCPTR(gnutls_mac_get_key_size);
65 MAKE_FUNCPTR(gnutls_perror);
66 MAKE_FUNCPTR(gnutls_protocol_get_version);
67 MAKE_FUNCPTR(gnutls_set_default_priority);
68 MAKE_FUNCPTR(gnutls_record_recv);
69 MAKE_FUNCPTR(gnutls_record_send);
70 MAKE_FUNCPTR(gnutls_transport_set_errno);
71 MAKE_FUNCPTR(gnutls_transport_set_ptr);
72 MAKE_FUNCPTR(gnutls_transport_set_pull_function);
73 MAKE_FUNCPTR(gnutls_transport_set_push_function);
74 #undef MAKE_FUNCPTR
75
76 #define SCHAN_INVALID_HANDLE ~0UL
77
78 enum schan_handle_type
79 {
80     SCHAN_HANDLE_CRED,
81     SCHAN_HANDLE_CTX,
82     SCHAN_HANDLE_FREE
83 };
84
85 struct schan_handle
86 {
87     void *object;
88     enum schan_handle_type type;
89 };
90
91 struct schan_credentials
92 {
93     ULONG credential_use;
94     gnutls_certificate_credentials credentials;
95 };
96
97 struct schan_context
98 {
99     gnutls_session_t session;
100     ULONG req_ctx_attr;
101 };
102
103 struct schan_transport;
104
105 struct schan_buffers
106 {
107     SIZE_T offset;
108     const SecBufferDesc *desc;
109     int current_buffer_idx;
110     BOOL allow_buffer_resize;
111     int (*get_next_buffer)(const struct schan_transport *, struct schan_buffers *);
112 };
113
114 struct schan_transport
115 {
116     struct schan_context *ctx;
117     struct schan_buffers in;
118     struct schan_buffers out;
119 };
120
121 static struct schan_handle *schan_handle_table;
122 static struct schan_handle *schan_free_handles;
123 static SIZE_T schan_handle_table_size;
124 static SIZE_T schan_handle_count;
125
126 static ULONG_PTR schan_alloc_handle(void *object, enum schan_handle_type type)
127 {
128     struct schan_handle *handle;
129
130     if (schan_free_handles)
131     {
132         DWORD index = schan_free_handles - schan_handle_table;
133         /* Use a free handle */
134         handle = schan_free_handles;
135         if (handle->type != SCHAN_HANDLE_FREE)
136         {
137             ERR("Handle %d(%p) is in the free list, but has type %#x.\n", index, handle, handle->type);
138             return SCHAN_INVALID_HANDLE;
139         }
140         schan_free_handles = handle->object;
141         handle->object = object;
142         handle->type = type;
143
144         return index;
145     }
146     if (!(schan_handle_count < schan_handle_table_size))
147     {
148         /* Grow the table */
149         SIZE_T new_size = schan_handle_table_size + (schan_handle_table_size >> 1);
150         struct schan_handle *new_table = HeapReAlloc(GetProcessHeap(), 0, schan_handle_table, new_size * sizeof(*schan_handle_table));
151         if (!new_table)
152         {
153             ERR("Failed to grow the handle table\n");
154             return SCHAN_INVALID_HANDLE;
155         }
156         schan_handle_table = new_table;
157         schan_handle_table_size = new_size;
158     }
159
160     handle = &schan_handle_table[schan_handle_count++];
161     handle->object = object;
162     handle->type = type;
163
164     return handle - schan_handle_table;
165 }
166
167 static void *schan_free_handle(ULONG_PTR handle_idx, enum schan_handle_type type)
168 {
169     struct schan_handle *handle;
170     void *object;
171
172     if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
173     if (handle_idx >= schan_handle_count) return NULL;
174     handle = &schan_handle_table[handle_idx];
175     if (handle->type != type)
176     {
177         ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
178         return NULL;
179     }
180
181     object = handle->object;
182     handle->object = schan_free_handles;
183     handle->type = SCHAN_HANDLE_FREE;
184     schan_free_handles = handle;
185
186     return object;
187 }
188
189 static void *schan_get_object(ULONG_PTR handle_idx, enum schan_handle_type type)
190 {
191     struct schan_handle *handle;
192
193     if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
194     if (handle_idx >= schan_handle_count) return NULL;
195     handle = &schan_handle_table[handle_idx];
196     if (handle->type != type)
197     {
198         ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
199         return NULL;
200     }
201
202     return handle->object;
203 }
204
205 static SECURITY_STATUS schan_QueryCredentialsAttributes(
206  PCredHandle phCredential, ULONG ulAttribute, VOID *pBuffer)
207 {
208     SECURITY_STATUS ret;
209
210     switch (ulAttribute)
211     {
212     case SECPKG_ATTR_SUPPORTED_ALGS:
213         if (pBuffer)
214         {
215             /* FIXME: get from CryptoAPI */
216             FIXME("SECPKG_ATTR_SUPPORTED_ALGS: stub\n");
217             ret = SEC_E_UNSUPPORTED_FUNCTION;
218         }
219         else
220             ret = SEC_E_INTERNAL_ERROR;
221         break;
222     case SECPKG_ATTR_CIPHER_STRENGTHS:
223         if (pBuffer)
224         {
225             SecPkgCred_CipherStrengths *r = pBuffer;
226
227             /* FIXME: get from CryptoAPI */
228             FIXME("SECPKG_ATTR_CIPHER_STRENGTHS: semi-stub\n");
229             r->dwMinimumCipherStrength = 40;
230             r->dwMaximumCipherStrength = 168;
231             ret = SEC_E_OK;
232         }
233         else
234             ret = SEC_E_INTERNAL_ERROR;
235         break;
236     case SECPKG_ATTR_SUPPORTED_PROTOCOLS:
237         if (pBuffer)
238         {
239             /* FIXME: get from OpenSSL? */
240             FIXME("SECPKG_ATTR_SUPPORTED_PROTOCOLS: stub\n");
241             ret = SEC_E_UNSUPPORTED_FUNCTION;
242         }
243         else
244             ret = SEC_E_INTERNAL_ERROR;
245         break;
246     default:
247         ret = SEC_E_UNSUPPORTED_FUNCTION;
248     }
249     return ret;
250 }
251
252 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesA(
253  PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
254 {
255     SECURITY_STATUS ret;
256
257     TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
258
259     switch (ulAttribute)
260     {
261     case SECPKG_CRED_ATTR_NAMES:
262         FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
263         ret = SEC_E_UNSUPPORTED_FUNCTION;
264         break;
265     default:
266         ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
267          pBuffer);
268     }
269     return ret;
270 }
271
272 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesW(
273  PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
274 {
275     SECURITY_STATUS ret;
276
277     TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
278
279     switch (ulAttribute)
280     {
281     case SECPKG_CRED_ATTR_NAMES:
282         FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
283         ret = SEC_E_UNSUPPORTED_FUNCTION;
284         break;
285     default:
286         ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
287          pBuffer);
288     }
289     return ret;
290 }
291
292 static SECURITY_STATUS schan_CheckCreds(const SCHANNEL_CRED *schanCred)
293 {
294     SECURITY_STATUS st;
295     DWORD i;
296
297     TRACE("dwVersion = %d\n", schanCred->dwVersion);
298     TRACE("cCreds = %d\n", schanCred->cCreds);
299     TRACE("hRootStore = %p\n", schanCred->hRootStore);
300     TRACE("cMappers = %d\n", schanCred->cMappers);
301     TRACE("cSupportedAlgs = %d:\n", schanCred->cSupportedAlgs);
302     for (i = 0; i < schanCred->cSupportedAlgs; i++)
303         TRACE("%08x\n", schanCred->palgSupportedAlgs[i]);
304     TRACE("grbitEnabledProtocols = %08x\n", schanCred->grbitEnabledProtocols);
305     TRACE("dwMinimumCipherStrength = %d\n", schanCred->dwMinimumCipherStrength);
306     TRACE("dwMaximumCipherStrength = %d\n", schanCred->dwMaximumCipherStrength);
307     TRACE("dwSessionLifespan = %d\n", schanCred->dwSessionLifespan);
308     TRACE("dwFlags = %08x\n", schanCred->dwFlags);
309     TRACE("dwCredFormat = %d\n", schanCred->dwCredFormat);
310
311     switch (schanCred->dwVersion)
312     {
313     case SCH_CRED_V3:
314     case SCHANNEL_CRED_VERSION:
315         break;
316     default:
317         return SEC_E_INTERNAL_ERROR;
318     }
319
320     if (schanCred->cCreds == 0)
321         st = SEC_E_NO_CREDENTIALS;
322     else if (schanCred->cCreds > 1)
323         st = SEC_E_UNKNOWN_CREDENTIALS;
324     else
325     {
326         DWORD keySpec;
327         HCRYPTPROV csp;
328         BOOL ret, freeCSP;
329
330         ret = CryptAcquireCertificatePrivateKey(schanCred->paCred[0],
331          0, /* FIXME: what flags to use? */ NULL,
332          &csp, &keySpec, &freeCSP);
333         if (ret)
334         {
335             st = SEC_E_OK;
336             if (freeCSP)
337                 CryptReleaseContext(csp, 0);
338         }
339         else
340             st = SEC_E_UNKNOWN_CREDENTIALS;
341     }
342     return st;
343 }
344
345 static SECURITY_STATUS schan_AcquireClientCredentials(const SCHANNEL_CRED *schanCred,
346  PCredHandle phCredential, PTimeStamp ptsExpiry)
347 {
348     struct schan_credentials *creds;
349     SECURITY_STATUS st = SEC_E_OK;
350
351     TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
352
353     if (schanCred)
354     {
355         st = schan_CheckCreds(schanCred);
356         if (st == SEC_E_NO_CREDENTIALS)
357             st = SEC_E_OK;
358     }
359
360     /* For now, the only thing I'm interested in is the direction of the
361      * connection, so just store it.
362      */
363     if (st == SEC_E_OK)
364     {
365         ULONG_PTR handle;
366         int ret;
367
368         creds = HeapAlloc(GetProcessHeap(), 0, sizeof(*creds));
369         if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
370
371         handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
372         if (handle == SCHAN_INVALID_HANDLE) goto fail;
373
374         creds->credential_use = SECPKG_CRED_OUTBOUND;
375         ret = pgnutls_certificate_allocate_credentials(&creds->credentials);
376         if (ret != GNUTLS_E_SUCCESS)
377         {
378             pgnutls_perror(ret);
379             schan_free_handle(handle, SCHAN_HANDLE_CRED);
380             goto fail;
381         }
382
383         phCredential->dwLower = handle;
384         phCredential->dwUpper = 0;
385
386         /* Outbound credentials have no expiry */
387         if (ptsExpiry)
388         {
389             ptsExpiry->LowPart = 0;
390             ptsExpiry->HighPart = 0;
391         }
392     }
393     return st;
394
395 fail:
396     HeapFree(GetProcessHeap(), 0, creds);
397     return SEC_E_INTERNAL_ERROR;
398 }
399
400 static SECURITY_STATUS schan_AcquireServerCredentials(const SCHANNEL_CRED *schanCred,
401  PCredHandle phCredential, PTimeStamp ptsExpiry)
402 {
403     SECURITY_STATUS st;
404
405     TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
406
407     if (!schanCred) return SEC_E_NO_CREDENTIALS;
408
409     st = schan_CheckCreds(schanCred);
410     if (st == SEC_E_OK)
411     {
412         ULONG_PTR handle;
413         struct schan_credentials *creds;
414
415         creds = HeapAlloc(GetProcessHeap(), 0, sizeof(*creds));
416         if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
417         creds->credential_use = SECPKG_CRED_INBOUND;
418
419         handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
420         if (handle == SCHAN_INVALID_HANDLE)
421         {
422             HeapFree(GetProcessHeap(), 0, creds);
423             return SEC_E_INTERNAL_ERROR;
424         }
425
426         phCredential->dwLower = handle;
427         phCredential->dwUpper = 0;
428
429         /* FIXME: get expiry from cert */
430     }
431     return st;
432 }
433
434 static SECURITY_STATUS schan_AcquireCredentialsHandle(ULONG fCredentialUse,
435  const SCHANNEL_CRED *schanCred, PCredHandle phCredential, PTimeStamp ptsExpiry)
436 {
437     SECURITY_STATUS ret;
438
439     if (fCredentialUse == SECPKG_CRED_OUTBOUND)
440         ret = schan_AcquireClientCredentials(schanCred, phCredential,
441          ptsExpiry);
442     else
443         ret = schan_AcquireServerCredentials(schanCred, phCredential,
444          ptsExpiry);
445     return ret;
446 }
447
448 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleA(
449  SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
450  PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
451  PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
452 {
453     TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
454      debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
455      pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
456     return schan_AcquireCredentialsHandle(fCredentialUse,
457      pAuthData, phCredential, ptsExpiry);
458 }
459
460 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleW(
461  SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
462  PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
463  PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
464 {
465     TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
466      debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
467      pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
468     return schan_AcquireCredentialsHandle(fCredentialUse,
469      pAuthData, phCredential, ptsExpiry);
470 }
471
472 static SECURITY_STATUS SEC_ENTRY schan_FreeCredentialsHandle(
473  PCredHandle phCredential)
474 {
475     struct schan_credentials *creds;
476
477     TRACE("phCredential %p\n", phCredential);
478
479     if (!phCredential) return SEC_E_INVALID_HANDLE;
480
481     creds = schan_free_handle(phCredential->dwLower, SCHAN_HANDLE_CRED);
482     if (!creds) return SEC_E_INVALID_HANDLE;
483
484     if (creds->credential_use == SECPKG_CRED_OUTBOUND)
485         pgnutls_certificate_free_credentials(creds->credentials);
486     HeapFree(GetProcessHeap(), 0, creds);
487
488     return SEC_E_OK;
489 }
490
491 static void init_schan_buffers(struct schan_buffers *s, const PSecBufferDesc desc,
492         int (*get_next_buffer)(const struct schan_transport *, struct schan_buffers *))
493 {
494     s->offset = 0;
495     s->desc = desc;
496     s->current_buffer_idx = -1;
497     s->allow_buffer_resize = FALSE;
498     s->get_next_buffer = get_next_buffer;
499 }
500
501 static int schan_find_sec_buffer_idx(const SecBufferDesc *desc, unsigned int start_idx, ULONG buffer_type)
502 {
503     unsigned int i;
504     PSecBuffer buffer;
505
506     for (i = start_idx; i < desc->cBuffers; ++i)
507     {
508         buffer = &desc->pBuffers[i];
509         if (buffer->BufferType == buffer_type) return i;
510     }
511
512     return -1;
513 }
514
515 static void schan_resize_current_buffer(const struct schan_buffers *s, SIZE_T min_size)
516 {
517     SecBuffer *b = &s->desc->pBuffers[s->current_buffer_idx];
518     SIZE_T new_size = b->cbBuffer ? b->cbBuffer * 2 : 128;
519     void *new_data;
520
521     if (b->cbBuffer >= min_size || !s->allow_buffer_resize || min_size > UINT_MAX / 2) return;
522
523     while (new_size < min_size) new_size *= 2;
524
525     if (b->pvBuffer)
526         new_data = HeapReAlloc(GetProcessHeap(), 0, b->pvBuffer, new_size);
527     else
528         new_data = HeapAlloc(GetProcessHeap(), 0, new_size);
529
530     if (!new_data)
531     {
532         TRACE("Failed to resize %p from %d to %ld\n", b->pvBuffer, b->cbBuffer, new_size);
533         return;
534     }
535
536     b->cbBuffer = new_size;
537     b->pvBuffer = new_data;
538 }
539
540 static char *schan_get_buffer(const struct schan_transport *t, struct schan_buffers *s, size_t *count)
541 {
542     SIZE_T max_count;
543     PSecBuffer buffer;
544
545     if (!s->desc)
546     {
547         TRACE("No desc\n");
548         return NULL;
549     }
550
551     if (s->current_buffer_idx == -1)
552     {
553         /* Initial buffer */
554         int buffer_idx = s->get_next_buffer(t, s);
555         if (buffer_idx == -1)
556         {
557             TRACE("No next buffer\n");
558             return NULL;
559         }
560         s->current_buffer_idx = buffer_idx;
561     }
562
563     buffer = &s->desc->pBuffers[s->current_buffer_idx];
564     TRACE("Using buffer %d: cbBuffer %d, BufferType %#x, pvBuffer %p\n", s->current_buffer_idx, buffer->cbBuffer, buffer->BufferType, buffer->pvBuffer);
565
566     schan_resize_current_buffer(s, s->offset + *count);
567     max_count = buffer->cbBuffer - s->offset;
568     if (!max_count)
569     {
570         int buffer_idx;
571
572         s->allow_buffer_resize = FALSE;
573         buffer_idx = s->get_next_buffer(t, s);
574         if (buffer_idx == -1)
575         {
576             TRACE("No next buffer\n");
577             return NULL;
578         }
579         s->current_buffer_idx = buffer_idx;
580         s->offset = 0;
581         return schan_get_buffer(t, s, count);
582     }
583
584     if (*count > max_count) *count = max_count;
585     return (char *)buffer->pvBuffer + s->offset;
586 }
587
588 static ssize_t schan_pull(gnutls_transport_ptr_t transport, void *buff, size_t buff_len)
589 {
590     struct schan_transport *t = transport;
591     char *b;
592
593     TRACE("Pull %zu bytes\n", buff_len);
594
595     b = schan_get_buffer(t, &t->in, &buff_len);
596     if (!b)
597     {
598         pgnutls_transport_set_errno(t->ctx->session, EAGAIN);
599         return -1;
600     }
601
602     memcpy(buff, b, buff_len);
603     t->in.offset += buff_len;
604
605     TRACE("Read %zu bytes\n", buff_len);
606
607     return buff_len;
608 }
609
610 static ssize_t schan_push(gnutls_transport_ptr_t transport, const void *buff, size_t buff_len)
611 {
612     struct schan_transport *t = transport;
613     char *b;
614
615     TRACE("Push %zu bytes\n", buff_len);
616
617     b = schan_get_buffer(t, &t->out, &buff_len);
618     if (!b)
619     {
620         pgnutls_transport_set_errno(t->ctx->session, EAGAIN);
621         return -1;
622     }
623
624     memcpy(b, buff, buff_len);
625     t->out.offset += buff_len;
626
627     TRACE("Wrote %zu bytes\n", buff_len);
628
629     return buff_len;
630 }
631
632 static int schan_init_sec_ctx_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
633 {
634     if (s->current_buffer_idx == -1)
635     {
636         int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
637         if (t->ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
638         {
639             if (idx == -1)
640             {
641                 idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_EMPTY);
642                 if (idx != -1) s->desc->pBuffers[idx].BufferType = SECBUFFER_TOKEN;
643             }
644             if (idx != -1 && !s->desc->pBuffers[idx].pvBuffer)
645             {
646                 s->desc->pBuffers[idx].cbBuffer = 0;
647                 s->allow_buffer_resize = TRUE;
648             }
649         }
650         return idx;
651     }
652
653     return -1;
654 }
655
656 static void dump_buffer_desc(SecBufferDesc *desc)
657 {
658     unsigned int i;
659
660     if (!desc) return;
661     TRACE("Buffer desc %p:\n", desc);
662     for (i = 0; i < desc->cBuffers; ++i)
663     {
664         SecBuffer *b = &desc->pBuffers[i];
665         TRACE("\tbuffer %u: cbBuffer %d, BufferType %#x pvBuffer %p\n", i, b->cbBuffer, b->BufferType, b->pvBuffer);
666     }
667 }
668
669 /***********************************************************************
670  *              InitializeSecurityContextW
671  */
672 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextW(
673  PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName,
674  ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
675  PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
676  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
677 {
678     struct schan_context *ctx;
679     struct schan_buffers *out_buffers;
680     struct schan_credentials *cred;
681     struct schan_transport transport;
682     int err;
683
684     TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
685      debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
686      Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
687
688     dump_buffer_desc(pInput);
689     dump_buffer_desc(pOutput);
690
691     if (!phContext)
692     {
693         ULONG_PTR handle;
694
695         if (!phCredential) return SEC_E_INVALID_HANDLE;
696
697         cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
698         if (!cred) return SEC_E_INVALID_HANDLE;
699
700         if (!(cred->credential_use & SECPKG_CRED_OUTBOUND))
701         {
702             WARN("Invalid credential use %#x\n", cred->credential_use);
703             return SEC_E_INVALID_HANDLE;
704         }
705
706         ctx = HeapAlloc(GetProcessHeap(), 0, sizeof(*ctx));
707         if (!ctx) return SEC_E_INSUFFICIENT_MEMORY;
708
709         handle = schan_alloc_handle(ctx, SCHAN_HANDLE_CTX);
710         if (handle == SCHAN_INVALID_HANDLE)
711         {
712             HeapFree(GetProcessHeap(), 0, ctx);
713             return SEC_E_INTERNAL_ERROR;
714         }
715
716         err = pgnutls_init(&ctx->session, GNUTLS_CLIENT);
717         if (err != GNUTLS_E_SUCCESS)
718         {
719             pgnutls_perror(err);
720             schan_free_handle(handle, SCHAN_HANDLE_CTX);
721             HeapFree(GetProcessHeap(), 0, ctx);
722             return SEC_E_INTERNAL_ERROR;
723         }
724
725         /* FIXME: We should be using the information from the credentials here. */
726         FIXME("Using hardcoded \"NORMAL\" priority\n");
727         err = pgnutls_set_default_priority(ctx->session);
728         if (err != GNUTLS_E_SUCCESS)
729         {
730             pgnutls_perror(err);
731             pgnutls_deinit(ctx->session);
732             schan_free_handle(handle, SCHAN_HANDLE_CTX);
733             HeapFree(GetProcessHeap(), 0, ctx);
734         }
735
736         err = pgnutls_credentials_set(ctx->session, GNUTLS_CRD_CERTIFICATE, cred->credentials);
737         if (err != GNUTLS_E_SUCCESS)
738         {
739             pgnutls_perror(err);
740             pgnutls_deinit(ctx->session);
741             schan_free_handle(handle, SCHAN_HANDLE_CTX);
742             HeapFree(GetProcessHeap(), 0, ctx);
743         }
744
745         pgnutls_transport_set_pull_function(ctx->session, schan_pull);
746         pgnutls_transport_set_push_function(ctx->session, schan_push);
747
748         phNewContext->dwLower = handle;
749         phNewContext->dwUpper = 0;
750     }
751     else
752     {
753         ctx = schan_get_object(phContext->dwLower, SCHAN_HANDLE_CTX);
754     }
755
756     ctx->req_ctx_attr = fContextReq;
757
758     transport.ctx = ctx;
759     init_schan_buffers(&transport.in, pInput, schan_init_sec_ctx_get_next_buffer);
760     init_schan_buffers(&transport.out, pOutput, schan_init_sec_ctx_get_next_buffer);
761     pgnutls_transport_set_ptr(ctx->session, &transport);
762
763     /* Perform the TLS handshake */
764     err = pgnutls_handshake(ctx->session);
765
766     out_buffers = &transport.out;
767     if (out_buffers->current_buffer_idx != -1)
768     {
769         SecBuffer *buffer = &out_buffers->desc->pBuffers[out_buffers->current_buffer_idx];
770         buffer->cbBuffer = out_buffers->offset;
771     }
772
773     *pfContextAttr = 0;
774     if (ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
775         *pfContextAttr |= ISC_RET_ALLOCATED_MEMORY;
776
777     switch(err)
778     {
779         case GNUTLS_E_SUCCESS:
780             TRACE("Handshake completed\n");
781             return SEC_E_OK;
782
783         case GNUTLS_E_AGAIN:
784             TRACE("Continue...\n");
785             return SEC_I_CONTINUE_NEEDED;
786
787         case GNUTLS_E_WARNING_ALERT_RECEIVED:
788         case GNUTLS_E_FATAL_ALERT_RECEIVED:
789         {
790             gnutls_alert_description_t alert = pgnutls_alert_get(ctx->session);
791             const char *alert_name = pgnutls_alert_get_name(alert);
792             WARN("ALERT: %d %s\n", alert, alert_name);
793             return SEC_E_INTERNAL_ERROR;
794         }
795
796         default:
797             pgnutls_perror(err);
798             return SEC_E_INTERNAL_ERROR;
799     }
800 }
801
802 /***********************************************************************
803  *              InitializeSecurityContextA
804  */
805 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextA(
806  PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
807  ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
808  PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
809  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
810 {
811     SECURITY_STATUS ret;
812     SEC_WCHAR *target_name = NULL;
813
814     TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
815      debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
816      Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
817
818     if (pszTargetName)
819     {
820         INT len = MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, NULL, 0);
821         target_name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(*target_name));
822         MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, target_name, len);
823     }
824
825     ret = schan_InitializeSecurityContextW(phCredential, phContext, target_name,
826             fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
827             phNewContext, pOutput, pfContextAttr, ptsExpiry);
828
829     HeapFree(GetProcessHeap(), 0, target_name);
830
831     return ret;
832 }
833
834 static unsigned int schannel_get_cipher_block_size(gnutls_cipher_algorithm_t cipher)
835 {
836     const struct
837     {
838         gnutls_cipher_algorithm_t cipher;
839         unsigned int block_size;
840     }
841     algorithms[] =
842     {
843         {GNUTLS_CIPHER_3DES_CBC, 8},
844         {GNUTLS_CIPHER_AES_128_CBC, 16},
845         {GNUTLS_CIPHER_AES_256_CBC, 16},
846         {GNUTLS_CIPHER_ARCFOUR_128, 1},
847         {GNUTLS_CIPHER_ARCFOUR_40, 1},
848         {GNUTLS_CIPHER_DES_CBC, 8},
849         {GNUTLS_CIPHER_NULL, 1},
850         {GNUTLS_CIPHER_RC2_40_CBC, 8},
851     };
852     unsigned int i;
853
854     for (i = 0; i < sizeof(algorithms) / sizeof(*algorithms); ++i)
855     {
856         if (algorithms[i].cipher == cipher)
857             return algorithms[i].block_size;
858     }
859
860     FIXME("Unknown cipher %#x, returning 1\n", cipher);
861
862     return 1;
863 }
864
865 static DWORD schannel_get_protocol(gnutls_protocol_t proto)
866 {
867     /* FIXME: currently schannel only implements client connections, but
868      * there's no reason it couldn't be used for servers as well.  The
869      * context doesn't tell us which it is, so assume client for now.
870      */
871     switch (proto)
872     {
873     case GNUTLS_SSL3: return SP_PROT_SSL3_CLIENT;
874     case GNUTLS_TLS1_0: return SP_PROT_TLS1_CLIENT;
875     default:
876         FIXME("unknown protocol %d\n", proto);
877         return 0;
878     }
879 }
880
881 static ALG_ID schannel_get_cipher_algid(gnutls_cipher_algorithm_t cipher)
882 {
883     switch (cipher)
884     {
885     case GNUTLS_CIPHER_UNKNOWN:
886     case GNUTLS_CIPHER_NULL: return 0;
887     case GNUTLS_CIPHER_ARCFOUR_40:
888     case GNUTLS_CIPHER_ARCFOUR_128: return CALG_RC4;
889     case GNUTLS_CIPHER_DES_CBC:
890     case GNUTLS_CIPHER_3DES_CBC: return CALG_DES;
891     case GNUTLS_CIPHER_AES_128_CBC:
892     case GNUTLS_CIPHER_AES_256_CBC: return CALG_AES;
893     case GNUTLS_CIPHER_RC2_40_CBC: return CALG_RC2;
894     default:
895         FIXME("unknown algorithm %d\n", cipher);
896         return 0;
897     }
898 }
899
900 static ALG_ID schannel_get_mac_algid(gnutls_mac_algorithm_t mac)
901 {
902     switch (mac)
903     {
904     case GNUTLS_MAC_UNKNOWN:
905     case GNUTLS_MAC_NULL: return 0;
906     case GNUTLS_MAC_MD5: return CALG_MD5;
907     case GNUTLS_MAC_SHA1:
908     case GNUTLS_MAC_SHA256:
909     case GNUTLS_MAC_SHA384:
910     case GNUTLS_MAC_SHA512: return CALG_SHA;
911     default:
912         FIXME("unknown algorithm %d\n", mac);
913         return 0;
914     }
915 }
916
917 static ALG_ID schannel_get_kx_algid(gnutls_kx_algorithm_t kx)
918 {
919     switch (kx)
920     {
921         case GNUTLS_KX_RSA: return CALG_RSA_KEYX;
922         case GNUTLS_KX_DHE_DSS:
923         case GNUTLS_KX_DHE_RSA: return CALG_DH_EPHEM;
924     default:
925         FIXME("unknown algorithm %d\n", kx);
926         return 0;
927     }
928 }
929
930 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesW(
931         PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
932 {
933     struct schan_context *ctx;
934
935     TRACE("context_handle %p, attribute %#x, buffer %p\n",
936             context_handle, attribute, buffer);
937
938     if (!context_handle) return SEC_E_INVALID_HANDLE;
939     ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
940
941     switch(attribute)
942     {
943         case SECPKG_ATTR_STREAM_SIZES:
944         {
945             SecPkgContext_StreamSizes *stream_sizes = buffer;
946             gnutls_mac_algorithm_t mac = pgnutls_mac_get(ctx->session);
947             size_t mac_size = pgnutls_mac_get_key_size(mac);
948             gnutls_cipher_algorithm_t cipher = pgnutls_cipher_get(ctx->session);
949             unsigned int block_size = schannel_get_cipher_block_size(cipher);
950
951             TRACE("Using %zu mac bytes, block size %u\n", mac_size, block_size);
952
953             /* These are defined by the TLS RFC */
954             stream_sizes->cbHeader = 5;
955             stream_sizes->cbTrailer = mac_size + 256; /* Max 255 bytes padding + 1 for padding size */
956             stream_sizes->cbMaximumMessage = 1 << 14;
957             stream_sizes->cbBuffers = 4;
958             stream_sizes->cbBlockSize = block_size;
959             return SEC_E_OK;
960         }
961         case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
962         {
963             unsigned int list_size;
964             const gnutls_datum_t *datum;
965
966             datum = pgnutls_certificate_get_peers(ctx->session, &list_size);
967             if (datum)
968             {
969                 PCCERT_CONTEXT *cert = buffer;
970
971                 *cert = CertCreateCertificateContext(X509_ASN_ENCODING,
972                         datum->data, datum->size);
973                 if (!*cert)
974                     return GetLastError();
975                 else
976                     return SEC_E_OK;
977             }
978             else
979                 return SEC_E_INTERNAL_ERROR;
980         }
981         case SECPKG_ATTR_CONNECTION_INFO:
982         {
983             SecPkgContext_ConnectionInfo *info = buffer;
984             gnutls_protocol_t proto = pgnutls_protocol_get_version(ctx->session);
985             gnutls_cipher_algorithm_t alg = pgnutls_cipher_get(ctx->session);
986             gnutls_mac_algorithm_t mac = pgnutls_mac_get(ctx->session);
987             gnutls_kx_algorithm_t kx = pgnutls_kx_get(ctx->session);
988
989             info->dwProtocol = schannel_get_protocol(proto);
990             info->aiCipher = schannel_get_cipher_algid(alg);
991             info->dwCipherStrength = pgnutls_cipher_get_key_size(alg);
992             info->aiHash = schannel_get_mac_algid(mac);
993             info->dwHashStrength = pgnutls_mac_get_key_size(mac);
994             info->aiExch = schannel_get_kx_algid(kx);
995             /* FIXME: info->dwExchStrength? */
996             info->dwExchStrength = 0;
997             return SEC_E_OK;
998         }
999
1000         default:
1001             FIXME("Unhandled attribute %#x\n", attribute);
1002             return SEC_E_UNSUPPORTED_FUNCTION;
1003     }
1004 }
1005
1006 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesA(
1007         PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1008 {
1009     TRACE("context_handle %p, attribute %#x, buffer %p\n",
1010             context_handle, attribute, buffer);
1011
1012     switch(attribute)
1013     {
1014         case SECPKG_ATTR_STREAM_SIZES:
1015             return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1016         case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1017             return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1018         case SECPKG_ATTR_CONNECTION_INFO:
1019             return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1020
1021         default:
1022             FIXME("Unhandled attribute %#x\n", attribute);
1023             return SEC_E_UNSUPPORTED_FUNCTION;
1024     }
1025 }
1026
1027 static int schan_encrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1028 {
1029     SecBuffer *b;
1030
1031     if (s->current_buffer_idx == -1)
1032         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_HEADER);
1033
1034     b = &s->desc->pBuffers[s->current_buffer_idx];
1035
1036     if (b->BufferType == SECBUFFER_STREAM_HEADER)
1037         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1038
1039     if (b->BufferType == SECBUFFER_DATA)
1040         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_TRAILER);
1041
1042     return -1;
1043 }
1044
1045 static int schan_encrypt_message_get_next_buffer_token(const struct schan_transport *t, struct schan_buffers *s)
1046 {
1047     SecBuffer *b;
1048
1049     if (s->current_buffer_idx == -1)
1050         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1051
1052     b = &s->desc->pBuffers[s->current_buffer_idx];
1053
1054     if (b->BufferType == SECBUFFER_TOKEN)
1055     {
1056         int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1057         if (idx != s->current_buffer_idx) return -1;
1058         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1059     }
1060
1061     if (b->BufferType == SECBUFFER_DATA)
1062     {
1063         int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1064         if (idx != -1)
1065             idx = schan_find_sec_buffer_idx(s->desc, idx + 1, SECBUFFER_TOKEN);
1066         return idx;
1067     }
1068
1069     return -1;
1070 }
1071
1072 static SECURITY_STATUS SEC_ENTRY schan_EncryptMessage(PCtxtHandle context_handle,
1073         ULONG quality, PSecBufferDesc message, ULONG message_seq_no)
1074 {
1075     struct schan_transport transport;
1076     struct schan_context *ctx;
1077     struct schan_buffers *b;
1078     SecBuffer *buffer;
1079     SIZE_T data_size;
1080     char *data;
1081     ssize_t sent = 0;
1082     ssize_t ret;
1083     int idx;
1084
1085     TRACE("context_handle %p, quality %d, message %p, message_seq_no %d\n",
1086             context_handle, quality, message, message_seq_no);
1087
1088     if (!context_handle) return SEC_E_INVALID_HANDLE;
1089     ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1090
1091     dump_buffer_desc(message);
1092
1093     idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
1094     if (idx == -1)
1095     {
1096         WARN("No data buffer passed\n");
1097         return SEC_E_INTERNAL_ERROR;
1098     }
1099     buffer = &message->pBuffers[idx];
1100
1101     data_size = buffer->cbBuffer;
1102     data = HeapAlloc(GetProcessHeap(), 0, data_size);
1103     memcpy(data, buffer->pvBuffer, data_size);
1104
1105     transport.ctx = ctx;
1106     init_schan_buffers(&transport.in, NULL, NULL);
1107     if (schan_find_sec_buffer_idx(message, 0, SECBUFFER_STREAM_HEADER) != -1)
1108         init_schan_buffers(&transport.out, message, schan_encrypt_message_get_next_buffer);
1109     else
1110         init_schan_buffers(&transport.out, message, schan_encrypt_message_get_next_buffer_token);
1111     pgnutls_transport_set_ptr(ctx->session, &transport);
1112
1113     while (sent < data_size)
1114     {
1115         ret = pgnutls_record_send(ctx->session, data + sent, data_size - sent);
1116         if (ret < 0)
1117         {
1118             if (ret != GNUTLS_E_AGAIN)
1119             {
1120                 pgnutls_perror(ret);
1121                 HeapFree(GetProcessHeap(), 0, data);
1122                 ERR("Returning SEC_E_INTERNAL_ERROR\n");
1123                 return SEC_E_INTERNAL_ERROR;
1124             }
1125             else break;
1126         }
1127         sent += ret;
1128     }
1129
1130     TRACE("Sent %zd bytes\n", sent);
1131
1132     b = &transport.out;
1133     b->desc->pBuffers[b->current_buffer_idx].cbBuffer = b->offset;
1134     HeapFree(GetProcessHeap(), 0, data);
1135
1136     return SEC_E_OK;
1137 }
1138
1139 static int schan_decrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1140 {
1141     if (s->current_buffer_idx == -1)
1142         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1143
1144     return -1;
1145 }
1146
1147 static SECURITY_STATUS SEC_ENTRY schan_DecryptMessage(PCtxtHandle context_handle,
1148         PSecBufferDesc message, ULONG message_seq_no, PULONG quality)
1149 {
1150     struct schan_transport transport;
1151     struct schan_context *ctx;
1152     SecBuffer *buffer;
1153     SIZE_T data_size;
1154     char *data;
1155     ssize_t received = 0;
1156     ssize_t ret;
1157     int idx;
1158
1159     TRACE("context_handle %p, message %p, message_seq_no %d, quality %p\n",
1160             context_handle, message, message_seq_no, quality);
1161
1162     if (!context_handle) return SEC_E_INVALID_HANDLE;
1163     ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1164
1165     dump_buffer_desc(message);
1166
1167     idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
1168     if (idx == -1)
1169     {
1170         WARN("No data buffer passed\n");
1171         return SEC_E_INTERNAL_ERROR;
1172     }
1173     buffer = &message->pBuffers[idx];
1174
1175     data_size = buffer->cbBuffer;
1176     data = HeapAlloc(GetProcessHeap(), 0, data_size);
1177
1178     transport.ctx = ctx;
1179     init_schan_buffers(&transport.in, message, schan_decrypt_message_get_next_buffer);
1180     init_schan_buffers(&transport.out, NULL, NULL);
1181     pgnutls_transport_set_ptr(ctx->session, (gnutls_transport_ptr_t)&transport);
1182
1183     while (received < data_size)
1184     {
1185         ret = pgnutls_record_recv(ctx->session, data + received, data_size - received);
1186         if (ret < 0)
1187         {
1188             if (ret == GNUTLS_E_AGAIN)
1189             {
1190                 if (!received)
1191                 {
1192                     pgnutls_perror(ret);
1193                     HeapFree(GetProcessHeap(), 0, data);
1194                     TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1195                     return SEC_E_INCOMPLETE_MESSAGE;
1196                 }
1197                 break;
1198             }
1199             else
1200             {
1201                 pgnutls_perror(ret);
1202                 HeapFree(GetProcessHeap(), 0, data);
1203                 ERR("Returning SEC_E_INTERNAL_ERROR\n");
1204                 return SEC_E_INTERNAL_ERROR;
1205             }
1206         }
1207         else if (!ret)
1208             break;
1209
1210         received += ret;
1211     }
1212
1213     TRACE("Received %zd bytes\n", received);
1214
1215     memcpy(buffer->pvBuffer, data, received);
1216     buffer->cbBuffer = received;
1217     HeapFree(GetProcessHeap(), 0, data);
1218
1219     return SEC_E_OK;
1220 }
1221
1222 static SECURITY_STATUS SEC_ENTRY schan_DeleteSecurityContext(PCtxtHandle context_handle)
1223 {
1224     struct schan_context *ctx;
1225
1226     TRACE("context_handle %p\n", context_handle);
1227
1228     if (!context_handle) return SEC_E_INVALID_HANDLE;
1229
1230     ctx = schan_free_handle(context_handle->dwLower, SCHAN_HANDLE_CTX);
1231     if (!ctx) return SEC_E_INVALID_HANDLE;
1232
1233     pgnutls_deinit(ctx->session);
1234     HeapFree(GetProcessHeap(), 0, ctx);
1235
1236     return SEC_E_OK;
1237 }
1238
1239 static void schan_gnutls_log(int level, const char *msg)
1240 {
1241     TRACE("<%d> %s", level, msg);
1242 }
1243
1244 static const SecurityFunctionTableA schanTableA = {
1245     1,
1246     NULL, /* EnumerateSecurityPackagesA */
1247     schan_QueryCredentialsAttributesA,
1248     schan_AcquireCredentialsHandleA,
1249     schan_FreeCredentialsHandle,
1250     NULL, /* Reserved2 */
1251     schan_InitializeSecurityContextA, 
1252     NULL, /* AcceptSecurityContext */
1253     NULL, /* CompleteAuthToken */
1254     schan_DeleteSecurityContext,
1255     NULL, /* ApplyControlToken */
1256     schan_QueryContextAttributesA,
1257     NULL, /* ImpersonateSecurityContext */
1258     NULL, /* RevertSecurityContext */
1259     NULL, /* MakeSignature */
1260     NULL, /* VerifySignature */
1261     FreeContextBuffer,
1262     NULL, /* QuerySecurityPackageInfoA */
1263     NULL, /* Reserved3 */
1264     NULL, /* Reserved4 */
1265     NULL, /* ExportSecurityContext */
1266     NULL, /* ImportSecurityContextA */
1267     NULL, /* AddCredentialsA */
1268     NULL, /* Reserved8 */
1269     NULL, /* QuerySecurityContextToken */
1270     schan_EncryptMessage,
1271     schan_DecryptMessage,
1272     NULL, /* SetContextAttributesA */
1273 };
1274
1275 static const SecurityFunctionTableW schanTableW = {
1276     1,
1277     NULL, /* EnumerateSecurityPackagesW */
1278     schan_QueryCredentialsAttributesW,
1279     schan_AcquireCredentialsHandleW,
1280     schan_FreeCredentialsHandle,
1281     NULL, /* Reserved2 */
1282     schan_InitializeSecurityContextW, 
1283     NULL, /* AcceptSecurityContext */
1284     NULL, /* CompleteAuthToken */
1285     schan_DeleteSecurityContext,
1286     NULL, /* ApplyControlToken */
1287     schan_QueryContextAttributesW,
1288     NULL, /* ImpersonateSecurityContext */
1289     NULL, /* RevertSecurityContext */
1290     NULL, /* MakeSignature */
1291     NULL, /* VerifySignature */
1292     FreeContextBuffer,
1293     NULL, /* QuerySecurityPackageInfoW */
1294     NULL, /* Reserved3 */
1295     NULL, /* Reserved4 */
1296     NULL, /* ExportSecurityContext */
1297     NULL, /* ImportSecurityContextW */
1298     NULL, /* AddCredentialsW */
1299     NULL, /* Reserved8 */
1300     NULL, /* QuerySecurityContextToken */
1301     schan_EncryptMessage,
1302     schan_DecryptMessage,
1303     NULL, /* SetContextAttributesW */
1304 };
1305
1306 static const WCHAR schannelComment[] = { 'S','c','h','a','n','n','e','l',' ',
1307  'S','e','c','u','r','i','t','y',' ','P','a','c','k','a','g','e',0 };
1308 static const WCHAR schannelDllName[] = { 's','c','h','a','n','n','e','l','.','d','l','l',0 };
1309
1310 void SECUR32_initSchannelSP(void)
1311 {
1312     /* This is what Windows reports.  This shouldn't break any applications
1313      * even though the functions are missing, because the wrapper will
1314      * return SEC_E_UNSUPPORTED_FUNCTION if our function is NULL.
1315      */
1316     static const LONG caps =
1317         SECPKG_FLAG_INTEGRITY |
1318         SECPKG_FLAG_PRIVACY |
1319         SECPKG_FLAG_CONNECTION |
1320         SECPKG_FLAG_MULTI_REQUIRED |
1321         SECPKG_FLAG_EXTENDED_ERROR |
1322         SECPKG_FLAG_IMPERSONATION |
1323         SECPKG_FLAG_ACCEPT_WIN32_NAME |
1324         SECPKG_FLAG_STREAM;
1325     static const short version = 1;
1326     static const LONG maxToken = 16384;
1327     SEC_WCHAR *uniSPName = (SEC_WCHAR *)UNISP_NAME_W,
1328               *schannel = (SEC_WCHAR *)SCHANNEL_NAME_W;
1329     const SecPkgInfoW info[] = {
1330         { caps, version, UNISP_RPC_ID, maxToken, uniSPName, uniSPName },
1331         { caps, version, UNISP_RPC_ID, maxToken, schannel,
1332             (SEC_WCHAR *)schannelComment },
1333     };
1334     SecureProvider *provider;
1335     int ret;
1336
1337     libgnutls_handle = wine_dlopen(SONAME_LIBGNUTLS, RTLD_NOW, NULL, 0);
1338     if (!libgnutls_handle)
1339     {
1340         WARN("Failed to load libgnutls.\n");
1341         return;
1342     }
1343
1344 #define LOAD_FUNCPTR(f) \
1345     if (!(p##f = wine_dlsym(libgnutls_handle, #f, NULL, 0))) \
1346     { \
1347         ERR("Failed to load %s\n", #f); \
1348         goto fail; \
1349     }
1350
1351     LOAD_FUNCPTR(gnutls_alert_get)
1352     LOAD_FUNCPTR(gnutls_alert_get_name)
1353     LOAD_FUNCPTR(gnutls_certificate_allocate_credentials)
1354     LOAD_FUNCPTR(gnutls_certificate_free_credentials)
1355     LOAD_FUNCPTR(gnutls_certificate_get_peers)
1356     LOAD_FUNCPTR(gnutls_cipher_get)
1357     LOAD_FUNCPTR(gnutls_cipher_get_key_size)
1358     LOAD_FUNCPTR(gnutls_credentials_set)
1359     LOAD_FUNCPTR(gnutls_deinit)
1360     LOAD_FUNCPTR(gnutls_global_deinit)
1361     LOAD_FUNCPTR(gnutls_global_init)
1362     LOAD_FUNCPTR(gnutls_global_set_log_function)
1363     LOAD_FUNCPTR(gnutls_global_set_log_level)
1364     LOAD_FUNCPTR(gnutls_handshake)
1365     LOAD_FUNCPTR(gnutls_init)
1366     LOAD_FUNCPTR(gnutls_kx_get)
1367     LOAD_FUNCPTR(gnutls_mac_get)
1368     LOAD_FUNCPTR(gnutls_mac_get_key_size)
1369     LOAD_FUNCPTR(gnutls_perror)
1370     LOAD_FUNCPTR(gnutls_protocol_get_version)
1371     LOAD_FUNCPTR(gnutls_set_default_priority)
1372     LOAD_FUNCPTR(gnutls_record_recv);
1373     LOAD_FUNCPTR(gnutls_record_send);
1374     LOAD_FUNCPTR(gnutls_transport_set_errno)
1375     LOAD_FUNCPTR(gnutls_transport_set_ptr)
1376     LOAD_FUNCPTR(gnutls_transport_set_pull_function)
1377     LOAD_FUNCPTR(gnutls_transport_set_push_function)
1378 #undef LOAD_FUNCPTR
1379
1380     ret = pgnutls_global_init();
1381     if (ret != GNUTLS_E_SUCCESS)
1382     {
1383         pgnutls_perror(ret);
1384         goto fail;
1385     }
1386
1387     if (TRACE_ON(secur32))
1388     {
1389         pgnutls_global_set_log_level(4);
1390         pgnutls_global_set_log_function(schan_gnutls_log);
1391     }
1392
1393     schan_handle_table = HeapAlloc(GetProcessHeap(), 0, 64 * sizeof(*schan_handle_table));
1394     if (!schan_handle_table)
1395     {
1396         ERR("Failed to allocate schannel handle table.\n");
1397         goto fail;
1398     }
1399     schan_handle_table_size = 64;
1400
1401     provider = SECUR32_addProvider(&schanTableA, &schanTableW, schannelDllName);
1402     if (!provider)
1403     {
1404         ERR("Failed to add schannel provider.\n");
1405         goto fail;
1406     }
1407
1408     SECUR32_addPackages(provider, sizeof(info) / sizeof(info[0]), NULL, info);
1409
1410     return;
1411
1412 fail:
1413     HeapFree(GetProcessHeap(), 0, schan_handle_table);
1414     schan_handle_table = NULL;
1415     wine_dlclose(libgnutls_handle, NULL, 0);
1416     libgnutls_handle = NULL;
1417     return;
1418 }
1419
1420 void SECUR32_deinitSchannelSP(void)
1421 {
1422     SIZE_T i = schan_handle_count;
1423
1424     if (!libgnutls_handle) return;
1425
1426     /* deinitialized sessions first because a pointer to the credentials
1427      * are stored for the session by calling gnutls_credentials_set. */
1428     while (i--)
1429     {
1430         if (schan_handle_table[i].type == SCHAN_HANDLE_CTX)
1431         {
1432             struct schan_context *ctx = schan_free_handle(i, SCHAN_HANDLE_CTX);
1433             pgnutls_deinit(ctx->session);
1434             HeapFree(GetProcessHeap(), 0, ctx);
1435         }
1436     }
1437     i = schan_handle_count;
1438     while (i--)
1439     {
1440         if (schan_handle_table[i].type != SCHAN_HANDLE_FREE)
1441         {
1442             struct schan_credentials *cred;
1443             cred = schan_free_handle(i, SCHAN_HANDLE_CRED);
1444             pgnutls_certificate_free_credentials(cred->credentials);
1445             HeapFree(GetProcessHeap(), 0, cred);
1446         }
1447     }
1448     HeapFree(GetProcessHeap(), 0, schan_handle_table);
1449     pgnutls_global_deinit();
1450     wine_dlclose(libgnutls_handle, NULL, 0);
1451 }
1452
1453 #else /* SONAME_LIBGNUTLS */
1454
1455 void SECUR32_initSchannelSP(void)
1456 {
1457     ERR("libgnutls not found, SSL connections will fail\n");
1458 }
1459
1460 void SECUR32_deinitSchannelSP(void) {}
1461
1462 #endif /* SONAME_LIBGNUTLS */