msi: Add tests for MsiEnumPatches.
[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_credentials_set);
52 MAKE_FUNCPTR(gnutls_deinit);
53 MAKE_FUNCPTR(gnutls_global_deinit);
54 MAKE_FUNCPTR(gnutls_global_init);
55 MAKE_FUNCPTR(gnutls_global_set_log_function);
56 MAKE_FUNCPTR(gnutls_global_set_log_level);
57 MAKE_FUNCPTR(gnutls_handshake);
58 MAKE_FUNCPTR(gnutls_init);
59 MAKE_FUNCPTR(gnutls_perror);
60 MAKE_FUNCPTR(gnutls_set_default_priority);
61 MAKE_FUNCPTR(gnutls_transport_set_errno);
62 MAKE_FUNCPTR(gnutls_transport_set_ptr);
63 MAKE_FUNCPTR(gnutls_transport_set_pull_function);
64 MAKE_FUNCPTR(gnutls_transport_set_push_function);
65 #undef MAKE_FUNCPTR
66
67 #define SCHAN_INVALID_HANDLE ~0UL
68
69 enum schan_handle_type
70 {
71     SCHAN_HANDLE_CRED,
72     SCHAN_HANDLE_CTX,
73     SCHAN_HANDLE_FREE
74 };
75
76 struct schan_handle
77 {
78     void *object;
79     enum schan_handle_type type;
80 };
81
82 struct schan_credentials
83 {
84     ULONG credential_use;
85     gnutls_certificate_credentials credentials;
86 };
87
88 struct schan_context
89 {
90     gnutls_session_t session;
91     ULONG req_ctx_attr;
92 };
93
94 struct schan_transport;
95
96 struct schan_buffers
97 {
98     SIZE_T offset;
99     const SecBufferDesc *desc;
100     int current_buffer_idx;
101     BOOL allow_buffer_resize;
102     int (*get_next_buffer)(const struct schan_transport *, struct schan_buffers *);
103 };
104
105 struct schan_transport
106 {
107     struct schan_context *ctx;
108     struct schan_buffers in;
109     struct schan_buffers out;
110 };
111
112 static struct schan_handle *schan_handle_table;
113 static struct schan_handle *schan_free_handles;
114 static SIZE_T schan_handle_table_size;
115 static SIZE_T schan_handle_count;
116
117 static ULONG_PTR schan_alloc_handle(void *object, enum schan_handle_type type)
118 {
119     struct schan_handle *handle;
120
121     if (schan_free_handles)
122     {
123         /* Use a free handle */
124         handle = schan_free_handles;
125         if (handle->type != SCHAN_HANDLE_FREE)
126         {
127             ERR("Handle %d(%p) is in the free list, but has type %#x.\n", (handle-schan_handle_table), handle, handle->type);
128             return SCHAN_INVALID_HANDLE;
129         }
130         schan_free_handles = (struct schan_handle *)handle->object;
131         handle->object = object;
132         handle->type = type;
133
134         return handle - schan_handle_table;
135     }
136     if (!(schan_handle_count < schan_handle_table_size))
137     {
138         /* Grow the table */
139         SIZE_T new_size = schan_handle_table_size + (schan_handle_table_size >> 1);
140         struct schan_handle *new_table = HeapReAlloc(GetProcessHeap(), 0, schan_handle_table, new_size * sizeof(*schan_handle_table));
141         if (!new_table)
142         {
143             ERR("Failed to grow the handle table\n");
144             return SCHAN_INVALID_HANDLE;
145         }
146         schan_handle_table = new_table;
147         schan_handle_table_size = new_size;
148     }
149
150     handle = &schan_handle_table[schan_handle_count++];
151     handle->object = object;
152     handle->type = type;
153
154     return handle - schan_handle_table;
155 }
156
157 static void *schan_free_handle(ULONG_PTR handle_idx, enum schan_handle_type type)
158 {
159     struct schan_handle *handle;
160     void *object;
161
162     if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
163     handle = &schan_handle_table[handle_idx];
164     if (handle->type != type)
165     {
166         ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
167         return NULL;
168     }
169
170     object = handle->object;
171     handle->object = schan_free_handles;
172     handle->type = SCHAN_HANDLE_FREE;
173     schan_free_handles = handle;
174
175     return object;
176 }
177
178 static void *schan_get_object(ULONG_PTR handle_idx, enum schan_handle_type type)
179 {
180     struct schan_handle *handle;
181
182     if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
183     handle = &schan_handle_table[handle_idx];
184     if (handle->type != type)
185     {
186         ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
187         return NULL;
188     }
189
190     return handle->object;
191 }
192
193 static SECURITY_STATUS schan_QueryCredentialsAttributes(
194  PCredHandle phCredential, ULONG ulAttribute, VOID *pBuffer)
195 {
196     SECURITY_STATUS ret;
197
198     switch (ulAttribute)
199     {
200     case SECPKG_ATTR_SUPPORTED_ALGS:
201         if (pBuffer)
202         {
203             /* FIXME: get from CryptoAPI */
204             FIXME("SECPKG_ATTR_SUPPORTED_ALGS: stub\n");
205             ret = SEC_E_UNSUPPORTED_FUNCTION;
206         }
207         else
208             ret = SEC_E_INTERNAL_ERROR;
209         break;
210     case SECPKG_ATTR_CIPHER_STRENGTHS:
211         if (pBuffer)
212         {
213             SecPkgCred_CipherStrengths *r = (SecPkgCred_CipherStrengths*)pBuffer;
214
215             /* FIXME: get from CryptoAPI */
216             FIXME("SECPKG_ATTR_CIPHER_STRENGTHS: semi-stub\n");
217             r->dwMinimumCipherStrength = 40;
218             r->dwMaximumCipherStrength = 168;
219             ret = SEC_E_OK;
220         }
221         else
222             ret = SEC_E_INTERNAL_ERROR;
223         break;
224     case SECPKG_ATTR_SUPPORTED_PROTOCOLS:
225         if (pBuffer)
226         {
227             /* FIXME: get from OpenSSL? */
228             FIXME("SECPKG_ATTR_SUPPORTED_PROTOCOLS: stub\n");
229             ret = SEC_E_UNSUPPORTED_FUNCTION;
230         }
231         else
232             ret = SEC_E_INTERNAL_ERROR;
233         break;
234     default:
235         ret = SEC_E_UNSUPPORTED_FUNCTION;
236     }
237     return ret;
238 }
239
240 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesA(
241  PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
242 {
243     SECURITY_STATUS ret;
244
245     TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
246
247     switch (ulAttribute)
248     {
249     case SECPKG_CRED_ATTR_NAMES:
250         FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
251         ret = SEC_E_UNSUPPORTED_FUNCTION;
252         break;
253     default:
254         ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
255          pBuffer);
256     }
257     return ret;
258 }
259
260 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesW(
261  PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
262 {
263     SECURITY_STATUS ret;
264
265     TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
266
267     switch (ulAttribute)
268     {
269     case SECPKG_CRED_ATTR_NAMES:
270         FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
271         ret = SEC_E_UNSUPPORTED_FUNCTION;
272         break;
273     default:
274         ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
275          pBuffer);
276     }
277     return ret;
278 }
279
280 static SECURITY_STATUS schan_CheckCreds(const SCHANNEL_CRED *schanCred)
281 {
282     SECURITY_STATUS st;
283
284     switch (schanCred->dwVersion)
285     {
286     case SCH_CRED_V3:
287     case SCHANNEL_CRED_VERSION:
288         break;
289     default:
290         return SEC_E_INTERNAL_ERROR;
291     }
292
293     if (schanCred->cCreds == 0)
294         st = SEC_E_NO_CREDENTIALS;
295     else if (schanCred->cCreds > 1)
296         st = SEC_E_UNKNOWN_CREDENTIALS;
297     else
298     {
299         DWORD keySpec;
300         HCRYPTPROV csp;
301         BOOL ret, freeCSP;
302
303         ret = CryptAcquireCertificatePrivateKey(schanCred->paCred[0],
304          0, /* FIXME: what flags to use? */ NULL,
305          &csp, &keySpec, &freeCSP);
306         if (ret)
307         {
308             st = SEC_E_OK;
309             if (freeCSP)
310                 CryptReleaseContext(csp, 0);
311         }
312         else
313             st = SEC_E_UNKNOWN_CREDENTIALS;
314     }
315     return st;
316 }
317
318 static SECURITY_STATUS schan_AcquireClientCredentials(const SCHANNEL_CRED *schanCred,
319  PCredHandle phCredential, PTimeStamp ptsExpiry)
320 {
321     struct schan_credentials *creds;
322     SECURITY_STATUS st = SEC_E_OK;
323
324     TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
325
326     if (schanCred)
327     {
328         st = schan_CheckCreds(schanCred);
329         if (st == SEC_E_NO_CREDENTIALS)
330             st = SEC_E_OK;
331     }
332
333     /* For now, the only thing I'm interested in is the direction of the
334      * connection, so just store it.
335      */
336     if (st == SEC_E_OK)
337     {
338         ULONG_PTR handle;
339         int ret;
340
341         creds = HeapAlloc(GetProcessHeap(), 0, sizeof(*creds));
342         if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
343
344         handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
345         if (handle == SCHAN_INVALID_HANDLE) goto fail;
346
347         creds->credential_use = SECPKG_CRED_OUTBOUND;
348         ret = pgnutls_certificate_allocate_credentials(&creds->credentials);
349         if (ret != GNUTLS_E_SUCCESS)
350         {
351             pgnutls_perror(ret);
352             schan_free_handle(handle, SCHAN_HANDLE_CRED);
353             goto fail;
354         }
355
356         phCredential->dwLower = handle;
357         phCredential->dwUpper = 0;
358
359         /* Outbound credentials have no expiry */
360         if (ptsExpiry)
361         {
362             ptsExpiry->LowPart = 0;
363             ptsExpiry->HighPart = 0;
364         }
365     }
366     return st;
367
368 fail:
369     HeapFree(GetProcessHeap(), 0, creds);
370     return SEC_E_INTERNAL_ERROR;
371 }
372
373 static SECURITY_STATUS schan_AcquireServerCredentials(const SCHANNEL_CRED *schanCred,
374  PCredHandle phCredential, PTimeStamp ptsExpiry)
375 {
376     SECURITY_STATUS st;
377
378     TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
379
380     if (!schanCred) return SEC_E_NO_CREDENTIALS;
381
382     st = schan_CheckCreds(schanCred);
383     if (st == SEC_E_OK)
384     {
385         ULONG_PTR handle;
386         struct schan_credentials *creds;
387
388         creds = HeapAlloc(GetProcessHeap(), 0, sizeof(*creds));
389         if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
390         creds->credential_use = SECPKG_CRED_INBOUND;
391
392         handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
393         if (handle == SCHAN_INVALID_HANDLE)
394         {
395             HeapFree(GetProcessHeap(), 0, creds);
396             return SEC_E_INTERNAL_ERROR;
397         }
398
399         phCredential->dwLower = handle;
400         phCredential->dwUpper = 0;
401
402         /* FIXME: get expiry from cert */
403     }
404     return st;
405 }
406
407 static SECURITY_STATUS schan_AcquireCredentialsHandle(ULONG fCredentialUse,
408  const SCHANNEL_CRED *schanCred, PCredHandle phCredential, PTimeStamp ptsExpiry)
409 {
410     SECURITY_STATUS ret;
411
412     if (fCredentialUse == SECPKG_CRED_OUTBOUND)
413         ret = schan_AcquireClientCredentials(schanCred, phCredential,
414          ptsExpiry);
415     else
416         ret = schan_AcquireServerCredentials(schanCred, phCredential,
417          ptsExpiry);
418     return ret;
419 }
420
421 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleA(
422  SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
423  PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
424  PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
425 {
426     TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
427      debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
428      pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
429     return schan_AcquireCredentialsHandle(fCredentialUse,
430      (PSCHANNEL_CRED)pAuthData, phCredential, ptsExpiry);
431 }
432
433 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleW(
434  SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
435  PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
436  PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
437 {
438     TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
439      debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
440      pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
441     return schan_AcquireCredentialsHandle(fCredentialUse,
442      (PSCHANNEL_CRED)pAuthData, phCredential, ptsExpiry);
443 }
444
445 static SECURITY_STATUS SEC_ENTRY schan_FreeCredentialsHandle(
446  PCredHandle phCredential)
447 {
448     struct schan_credentials *creds;
449
450     TRACE("phCredential %p\n", phCredential);
451
452     if (!phCredential) return SEC_E_INVALID_HANDLE;
453
454     creds = schan_free_handle(phCredential->dwLower, SCHAN_HANDLE_CRED);
455     if (!creds) return SEC_E_INVALID_HANDLE;
456
457     if (creds->credential_use == SECPKG_CRED_OUTBOUND)
458         pgnutls_certificate_free_credentials(creds->credentials);
459     HeapFree(GetProcessHeap(), 0, creds);
460
461     return SEC_E_OK;
462 }
463
464 static void init_schan_buffers(struct schan_buffers *s, const PSecBufferDesc desc,
465         int (*get_next_buffer)(const struct schan_transport *, struct schan_buffers *))
466 {
467     s->offset = 0;
468     s->desc = desc;
469     s->current_buffer_idx = -1;
470     s->allow_buffer_resize = FALSE;
471     s->get_next_buffer = get_next_buffer;
472 }
473
474 static int schan_find_sec_buffer_idx(const SecBufferDesc *desc, unsigned int start_idx, ULONG buffer_type)
475 {
476     unsigned int i;
477     PSecBuffer buffer;
478
479     for (i = start_idx; i < desc->cBuffers; ++i)
480     {
481         buffer = &desc->pBuffers[i];
482         if (buffer->BufferType == buffer_type) return i;
483     }
484
485     return -1;
486 }
487
488 static void schan_resize_current_buffer(const struct schan_buffers *s, SIZE_T min_size)
489 {
490     SecBuffer *b = &s->desc->pBuffers[s->current_buffer_idx];
491     SIZE_T new_size = b->cbBuffer ? b->cbBuffer * 2 : 128;
492     void *new_data;
493
494     if (b->cbBuffer >= min_size || !s->allow_buffer_resize || min_size > UINT_MAX / 2) return;
495
496     while (new_size < min_size) new_size *= 2;
497
498     if (b->pvBuffer)
499         new_data = HeapReAlloc(GetProcessHeap(), 0, b->pvBuffer, new_size);
500     else
501         new_data = HeapAlloc(GetProcessHeap(), 0, new_size);
502
503     if (!new_data)
504     {
505         TRACE("Failed to resize %p from %ld to %ld\n", b->pvBuffer, b->cbBuffer, new_size);
506         return;
507     }
508
509     b->cbBuffer = new_size;
510     b->pvBuffer = new_data;
511 }
512
513 static char *schan_get_buffer(const struct schan_transport *t, struct schan_buffers *s, size_t *count)
514 {
515     SIZE_T max_count;
516     PSecBuffer buffer;
517
518     if (!s->desc)
519     {
520         TRACE("No desc\n");
521         return NULL;
522     }
523
524     if (s->current_buffer_idx == -1)
525     {
526         /* Initial buffer */
527         int buffer_idx = s->get_next_buffer(t, s);
528         if (buffer_idx == -1)
529         {
530             TRACE("No next buffer\n");
531             return NULL;
532         }
533         s->current_buffer_idx = buffer_idx;
534     }
535
536     buffer = &s->desc->pBuffers[s->current_buffer_idx];
537     TRACE("Using buffer %d: cbBuffer %ld, BufferType %#lx, pvBuffer %p\n", s->current_buffer_idx, buffer->cbBuffer, buffer->BufferType, buffer->pvBuffer);
538
539     schan_resize_current_buffer(s, s->offset + *count);
540     max_count = buffer->cbBuffer - s->offset;
541     if (!max_count)
542     {
543         int buffer_idx;
544
545         s->allow_buffer_resize = FALSE;
546         buffer_idx = s->get_next_buffer(t, s);
547         if (buffer_idx == -1)
548         {
549             TRACE("No next buffer\n");
550             return NULL;
551         }
552         s->current_buffer_idx = buffer_idx;
553         s->offset = 0;
554         return schan_get_buffer(t, s, count);
555     }
556
557     if (*count > max_count) *count = max_count;
558     return (char *)buffer->pvBuffer + s->offset;
559 }
560
561 static ssize_t schan_pull(gnutls_transport_ptr_t transport, void *buff, size_t buff_len)
562 {
563     struct schan_transport *t = (struct schan_transport *)transport;
564     char *b;
565
566     TRACE("Pull %zu bytes\n", buff_len);
567
568     b = schan_get_buffer(t, &t->in, &buff_len);
569     if (!b)
570     {
571         pgnutls_transport_set_errno(t->ctx->session, EAGAIN);
572         return -1;
573     }
574
575     memcpy(buff, b, buff_len);
576     t->in.offset += buff_len;
577
578     TRACE("Read %zu bytes\n", buff_len);
579
580     return buff_len;
581 }
582
583 static ssize_t schan_push(gnutls_transport_ptr_t transport, const void *buff, size_t buff_len)
584 {
585     struct schan_transport *t = (struct schan_transport *)transport;
586     char *b;
587
588     TRACE("Push %zu bytes\n", buff_len);
589
590     b = schan_get_buffer(t, &t->out, &buff_len);
591     if (!b)
592     {
593         pgnutls_transport_set_errno(t->ctx->session, EAGAIN);
594         return -1;
595     }
596
597     memcpy(b, buff, buff_len);
598     t->out.offset += buff_len;
599
600     TRACE("Wrote %zu bytes\n", buff_len);
601
602     return buff_len;
603 }
604
605 static int schan_init_sec_ctx_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
606 {
607     if (s->current_buffer_idx == -1)
608     {
609         int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
610         if (idx != -1 && !s->desc->pBuffers[idx].pvBuffer
611                 && (t->ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY))
612             s->allow_buffer_resize = TRUE;
613         return idx;
614     }
615
616     return -1;
617 }
618
619 /***********************************************************************
620  *              InitializeSecurityContextW
621  */
622 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextW(
623  PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName,
624  ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
625  PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
626  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
627 {
628     struct schan_context *ctx;
629     struct schan_buffers *out_buffers;
630     struct schan_credentials *cred;
631     struct schan_transport transport;
632     int err;
633
634     TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
635      debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
636      Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
637
638     if (!phContext)
639     {
640         ULONG_PTR handle;
641
642         if (!phCredential) return SEC_E_INVALID_HANDLE;
643
644         cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
645         if (!cred) return SEC_E_INVALID_HANDLE;
646
647         if (!(cred->credential_use & SECPKG_CRED_OUTBOUND))
648         {
649             WARN("Invalid credential use %#x\n", cred->credential_use);
650             return SEC_E_INVALID_HANDLE;
651         }
652
653         ctx = HeapAlloc(GetProcessHeap(), 0, sizeof(*ctx));
654         if (!ctx) return SEC_E_INSUFFICIENT_MEMORY;
655
656         handle = schan_alloc_handle(ctx, SCHAN_HANDLE_CTX);
657         if (handle == SCHAN_INVALID_HANDLE)
658         {
659             HeapFree(GetProcessHeap(), 0, ctx);
660             return SEC_E_INTERNAL_ERROR;
661         }
662
663         err = pgnutls_init(&ctx->session, GNUTLS_CLIENT);
664         if (err != GNUTLS_E_SUCCESS)
665         {
666             pgnutls_perror(err);
667             schan_free_handle(handle, SCHAN_HANDLE_CTX);
668             HeapFree(GetProcessHeap(), 0, ctx);
669             return SEC_E_INTERNAL_ERROR;
670         }
671
672         /* FIXME: We should be using the information from the credentials here. */
673         FIXME("Using hardcoded \"NORMAL\" priority\n");
674         err = pgnutls_set_default_priority(ctx->session);
675         if (err != GNUTLS_E_SUCCESS)
676         {
677             pgnutls_perror(err);
678             pgnutls_deinit(ctx->session);
679             schan_free_handle(handle, SCHAN_HANDLE_CTX);
680             HeapFree(GetProcessHeap(), 0, ctx);
681         }
682
683         err = pgnutls_credentials_set(ctx->session, GNUTLS_CRD_CERTIFICATE, cred->credentials);
684         if (err != GNUTLS_E_SUCCESS)
685         {
686             pgnutls_perror(err);
687             pgnutls_deinit(ctx->session);
688             schan_free_handle(handle, SCHAN_HANDLE_CTX);
689             HeapFree(GetProcessHeap(), 0, ctx);
690         }
691
692         pgnutls_transport_set_pull_function(ctx->session, schan_pull);
693         pgnutls_transport_set_push_function(ctx->session, schan_push);
694
695         phNewContext->dwLower = handle;
696         phNewContext->dwUpper = 0;
697     }
698     else
699     {
700         ctx = schan_get_object(phContext->dwLower, SCHAN_HANDLE_CTX);
701     }
702
703     ctx->req_ctx_attr = fContextReq;
704
705     transport.ctx = ctx;
706     init_schan_buffers(&transport.in, pInput, schan_init_sec_ctx_get_next_buffer);
707     init_schan_buffers(&transport.out, pOutput, schan_init_sec_ctx_get_next_buffer);
708     pgnutls_transport_set_ptr(ctx->session, &transport);
709
710     /* Perform the TLS handshake */
711     err = pgnutls_handshake(ctx->session);
712
713     out_buffers = &transport.out;
714     if (out_buffers->current_buffer_idx != -1)
715     {
716         SecBuffer *buffer = &out_buffers->desc->pBuffers[out_buffers->current_buffer_idx];
717         buffer->cbBuffer = out_buffers->offset;
718     }
719
720     *pfContextAttr = 0;
721     if (ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
722         *pfContextAttr |= ISC_RET_ALLOCATED_MEMORY;
723
724     switch(err)
725     {
726         case GNUTLS_E_SUCCESS:
727             TRACE("Handshake completed\n");
728             return SEC_E_OK;
729
730         case GNUTLS_E_AGAIN:
731             TRACE("Continue...\n");
732             return SEC_I_CONTINUE_NEEDED;
733
734         case GNUTLS_E_WARNING_ALERT_RECEIVED:
735         case GNUTLS_E_FATAL_ALERT_RECEIVED:
736         {
737             gnutls_alert_description_t alert = pgnutls_alert_get(ctx->session);
738             const char *alert_name = pgnutls_alert_get_name(alert);
739             WARN("ALERT: %d %s\n", alert, alert_name);
740             return SEC_E_INTERNAL_ERROR;
741         }
742
743         default:
744             pgnutls_perror(err);
745             return SEC_E_INTERNAL_ERROR;
746     }
747 }
748
749 /***********************************************************************
750  *              InitializeSecurityContextA
751  */
752 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextA(
753  PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
754  ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
755  PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
756  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
757 {
758     SECURITY_STATUS ret;
759     SEC_WCHAR *target_name = NULL;
760
761     TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
762      debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
763      Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
764
765     if (pszTargetName)
766     {
767         INT len = MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, NULL, 0);
768         target_name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(*target_name));
769         MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, target_name, len);
770     }
771
772     ret = schan_InitializeSecurityContextW(phCredential, phContext, target_name,
773             fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
774             phNewContext, pOutput, pfContextAttr, ptsExpiry);
775
776     HeapFree(GetProcessHeap(), 0, target_name);
777
778     return ret;
779 }
780
781 static SECURITY_STATUS SEC_ENTRY schan_DeleteSecurityContext(PCtxtHandle context_handle)
782 {
783     struct schan_context *ctx;
784
785     TRACE("context_handle %p\n", context_handle);
786
787     if (!context_handle) return SEC_E_INVALID_HANDLE;
788
789     ctx = schan_free_handle(context_handle->dwLower, SCHAN_HANDLE_CTX);
790     if (!ctx) return SEC_E_INVALID_HANDLE;
791
792     pgnutls_deinit(ctx->session);
793     HeapFree(GetProcessHeap(), 0, ctx);
794
795     return SEC_E_OK;
796 }
797
798 static void schan_gnutls_log(int level, const char *msg)
799 {
800     TRACE("<%d> %s", level, msg);
801 }
802
803 static const SecurityFunctionTableA schanTableA = {
804     1,
805     NULL, /* EnumerateSecurityPackagesA */
806     schan_QueryCredentialsAttributesA,
807     schan_AcquireCredentialsHandleA,
808     schan_FreeCredentialsHandle,
809     NULL, /* Reserved2 */
810     schan_InitializeSecurityContextA, 
811     NULL, /* AcceptSecurityContext */
812     NULL, /* CompleteAuthToken */
813     schan_DeleteSecurityContext,
814     NULL, /* ApplyControlToken */
815     NULL, /* QueryContextAttributesA */
816     NULL, /* ImpersonateSecurityContext */
817     NULL, /* RevertSecurityContext */
818     NULL, /* MakeSignature */
819     NULL, /* VerifySignature */
820     FreeContextBuffer,
821     NULL, /* QuerySecurityPackageInfoA */
822     NULL, /* Reserved3 */
823     NULL, /* Reserved4 */
824     NULL, /* ExportSecurityContext */
825     NULL, /* ImportSecurityContextA */
826     NULL, /* AddCredentialsA */
827     NULL, /* Reserved8 */
828     NULL, /* QuerySecurityContextToken */
829     NULL, /* EncryptMessage */
830     NULL, /* DecryptMessage */
831     NULL, /* SetContextAttributesA */
832 };
833
834 static const SecurityFunctionTableW schanTableW = {
835     1,
836     NULL, /* EnumerateSecurityPackagesW */
837     schan_QueryCredentialsAttributesW,
838     schan_AcquireCredentialsHandleW,
839     schan_FreeCredentialsHandle,
840     NULL, /* Reserved2 */
841     schan_InitializeSecurityContextW, 
842     NULL, /* AcceptSecurityContext */
843     NULL, /* CompleteAuthToken */
844     schan_DeleteSecurityContext,
845     NULL, /* ApplyControlToken */
846     NULL, /* QueryContextAttributesW */
847     NULL, /* ImpersonateSecurityContext */
848     NULL, /* RevertSecurityContext */
849     NULL, /* MakeSignature */
850     NULL, /* VerifySignature */
851     FreeContextBuffer,
852     NULL, /* QuerySecurityPackageInfoW */
853     NULL, /* Reserved3 */
854     NULL, /* Reserved4 */
855     NULL, /* ExportSecurityContext */
856     NULL, /* ImportSecurityContextW */
857     NULL, /* AddCredentialsW */
858     NULL, /* Reserved8 */
859     NULL, /* QuerySecurityContextToken */
860     NULL, /* EncryptMessage */
861     NULL, /* DecryptMessage */
862     NULL, /* SetContextAttributesW */
863 };
864
865 static const WCHAR schannelComment[] = { 'S','c','h','a','n','n','e','l',' ',
866  'S','e','c','u','r','i','t','y',' ','P','a','c','k','a','g','e',0 };
867 static const WCHAR schannelDllName[] = { 's','c','h','a','n','n','e','l','.','d','l','l',0 };
868
869 void SECUR32_initSchannelSP(void)
870 {
871     /* This is what Windows reports.  This shouldn't break any applications
872      * even though the functions are missing, because the wrapper will
873      * return SEC_E_UNSUPPORTED_FUNCTION if our function is NULL.
874      */
875     static const long caps =
876         SECPKG_FLAG_INTEGRITY |
877         SECPKG_FLAG_PRIVACY |
878         SECPKG_FLAG_CONNECTION |
879         SECPKG_FLAG_MULTI_REQUIRED |
880         SECPKG_FLAG_EXTENDED_ERROR |
881         SECPKG_FLAG_IMPERSONATION |
882         SECPKG_FLAG_ACCEPT_WIN32_NAME |
883         SECPKG_FLAG_STREAM;
884     static const short version = 1;
885     static const long maxToken = 16384;
886     SEC_WCHAR *uniSPName = (SEC_WCHAR *)UNISP_NAME_W,
887               *schannel = (SEC_WCHAR *)SCHANNEL_NAME_W;
888     const SecPkgInfoW info[] = {
889         { caps, version, UNISP_RPC_ID, maxToken, uniSPName, uniSPName },
890         { caps, version, UNISP_RPC_ID, maxToken, schannel,
891             (SEC_WCHAR *)schannelComment },
892     };
893     SecureProvider *provider;
894     int ret;
895
896     libgnutls_handle = wine_dlopen(SONAME_LIBGNUTLS, RTLD_NOW, NULL, 0);
897     if (!libgnutls_handle)
898     {
899         WARN("Failed to load libgnutls.\n");
900         return;
901     }
902
903 #define LOAD_FUNCPTR(f) \
904     if (!(p##f = wine_dlsym(libgnutls_handle, #f, NULL, 0))) \
905     { \
906         ERR("Failed to load %s\n", #f); \
907         goto fail; \
908     }
909
910     LOAD_FUNCPTR(gnutls_alert_get)
911     LOAD_FUNCPTR(gnutls_alert_get_name)
912     LOAD_FUNCPTR(gnutls_certificate_allocate_credentials)
913     LOAD_FUNCPTR(gnutls_certificate_free_credentials)
914     LOAD_FUNCPTR(gnutls_credentials_set)
915     LOAD_FUNCPTR(gnutls_deinit)
916     LOAD_FUNCPTR(gnutls_global_deinit)
917     LOAD_FUNCPTR(gnutls_global_init)
918     LOAD_FUNCPTR(gnutls_global_set_log_function)
919     LOAD_FUNCPTR(gnutls_global_set_log_level)
920     LOAD_FUNCPTR(gnutls_handshake)
921     LOAD_FUNCPTR(gnutls_init)
922     LOAD_FUNCPTR(gnutls_perror)
923     LOAD_FUNCPTR(gnutls_set_default_priority)
924     LOAD_FUNCPTR(gnutls_transport_set_errno)
925     LOAD_FUNCPTR(gnutls_transport_set_ptr)
926     LOAD_FUNCPTR(gnutls_transport_set_pull_function)
927     LOAD_FUNCPTR(gnutls_transport_set_push_function)
928 #undef LOAD_FUNCPTR
929
930     ret = pgnutls_global_init();
931     if (ret != GNUTLS_E_SUCCESS)
932     {
933         pgnutls_perror(ret);
934         goto fail;
935     }
936
937     if (TRACE_ON(secur32))
938     {
939         pgnutls_global_set_log_level(4);
940         pgnutls_global_set_log_function(schan_gnutls_log);
941     }
942
943     schan_handle_table = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 64 * sizeof(*schan_handle_table));
944     if (!schan_handle_table)
945     {
946         ERR("Failed to allocate schannel handle table.\n");
947         goto fail;
948     }
949     schan_handle_table_size = 64;
950
951     provider = SECUR32_addProvider(&schanTableA, &schanTableW, schannelDllName);
952     if (!provider)
953     {
954         ERR("Failed to add schannel provider.\n");
955         goto fail;
956     }
957
958     SECUR32_addPackages(provider, sizeof(info) / sizeof(info[0]), NULL, info);
959
960     return;
961
962 fail:
963     HeapFree(GetProcessHeap(), 0, schan_handle_table);
964     schan_handle_table = NULL;
965     wine_dlclose(libgnutls_handle, NULL, 0);
966     libgnutls_handle = NULL;
967     return;
968 }
969
970 void SECUR32_deinitSchannelSP(void)
971 {
972     if (!libgnutls_handle) return;
973
974     pgnutls_global_deinit();
975     wine_dlclose(libgnutls_handle, NULL, 0);
976 }
977
978 #else /* SONAME_LIBGNUTLS */
979
980 void SECUR32_initSchannelSP(void) {}
981 void SECUR32_deinitSchannelSP(void) {}
982
983 #endif /* SONAME_LIBGNUTLS */