OSDN Git Service

2f60ac67276868141c2ef0261ea0d790b352dfe3
[ffftp/ffftp.git] / socketwrapper.c
1 // socketwrapper.c\r
2 // Copyright (C) 2011 Suguru Kawamoto\r
3 // ソケットラッパー\r
4 // socket関連関数をOpenSSL用に置換\r
5 // socket関連関数のIPv6対応\r
6 // コンパイルにはOpenSSLのヘッダーファイルが必要\r
7 // 実行にはOpenSSLのDLLが必要\r
8 \r
9 #include <ws2tcpip.h>\r
10 #include <windows.h>\r
11 #include <mmsystem.h>\r
12 #include <openssl/ssl.h>\r
13 \r
14 #include "socketwrapper.h"\r
15 #include "protectprocess.h"\r
16 #include "mbswrapper.h"\r
17 #include "punycode.h"\r
18 \r
19 typedef void (__cdecl* _SSL_load_error_strings)();\r
20 typedef int (__cdecl* _SSL_library_init)();\r
21 typedef SSL_METHOD* (__cdecl* _SSLv23_method)();\r
22 typedef SSL_CTX* (__cdecl* _SSL_CTX_new)(SSL_METHOD*);\r
23 typedef void (__cdecl* _SSL_CTX_free)(SSL_CTX*);\r
24 typedef SSL* (__cdecl* _SSL_new)(SSL_CTX*);\r
25 typedef void (__cdecl* _SSL_free)(SSL*);\r
26 typedef int (__cdecl* _SSL_shutdown)(SSL*);\r
27 typedef int (__cdecl* _SSL_get_fd)(SSL*);\r
28 typedef int (__cdecl* _SSL_set_fd)(SSL*, int);\r
29 typedef int (__cdecl* _SSL_accept)(SSL*);\r
30 typedef int (__cdecl* _SSL_connect)(SSL*);\r
31 typedef int (__cdecl* _SSL_write)(SSL*, const void*, int);\r
32 typedef int (__cdecl* _SSL_peek)(SSL*, void*, int);\r
33 typedef int (__cdecl* _SSL_read)(SSL*, void*, int);\r
34 typedef int (__cdecl* _SSL_get_error)(SSL*, int);\r
35 typedef X509* (__cdecl* _SSL_get_peer_certificate)(const SSL*);\r
36 typedef long (__cdecl* _SSL_get_verify_result)(const SSL*);\r
37 typedef SSL_SESSION* (__cdecl* _SSL_get_session)(SSL*);\r
38 typedef int (__cdecl* _SSL_set_session)(SSL*, SSL_SESSION*);\r
39 typedef X509_STORE* (__cdecl* _SSL_CTX_get_cert_store)(const SSL_CTX*);\r
40 typedef BIO_METHOD* (__cdecl* _BIO_s_mem)();\r
41 typedef BIO* (__cdecl* _BIO_new)(BIO_METHOD*);\r
42 typedef int (__cdecl* _BIO_free)(BIO*);\r
43 typedef BIO* (__cdecl* _BIO_new_mem_buf)(void*, int);\r
44 typedef long (__cdecl* _BIO_ctrl)(BIO*, int, long, void*);\r
45 typedef void (__cdecl* _X509_free)(X509*);\r
46 typedef int (__cdecl* _X509_print_ex)(BIO*, X509*, unsigned long, unsigned long);\r
47 typedef X509_NAME* (__cdecl* _X509_get_subject_name)(X509*);\r
48 typedef int (__cdecl* _X509_NAME_print_ex)(BIO*, X509_NAME*, int, unsigned long);\r
49 typedef X509* (__cdecl* _PEM_read_bio_X509)(BIO*, X509**, pem_password_cb*, void*);\r
50 typedef int (__cdecl* _X509_STORE_add_cert)(X509_STORE*, X509*);\r
51 \r
52 _SSL_load_error_strings p_SSL_load_error_strings;\r
53 _SSL_library_init p_SSL_library_init;\r
54 _SSLv23_method p_SSLv23_method;\r
55 _SSL_CTX_new p_SSL_CTX_new;\r
56 _SSL_CTX_free p_SSL_CTX_free;\r
57 _SSL_new p_SSL_new;\r
58 _SSL_free p_SSL_free;\r
59 _SSL_shutdown p_SSL_shutdown;\r
60 _SSL_get_fd p_SSL_get_fd;\r
61 _SSL_set_fd p_SSL_set_fd;\r
62 _SSL_accept p_SSL_accept;\r
63 _SSL_connect p_SSL_connect;\r
64 _SSL_write p_SSL_write;\r
65 _SSL_peek p_SSL_peek;\r
66 _SSL_read p_SSL_read;\r
67 _SSL_get_error p_SSL_get_error;\r
68 _SSL_get_peer_certificate p_SSL_get_peer_certificate;\r
69 _SSL_get_verify_result p_SSL_get_verify_result;\r
70 _SSL_get_session p_SSL_get_session;\r
71 _SSL_set_session p_SSL_set_session;\r
72 _SSL_CTX_get_cert_store p_SSL_CTX_get_cert_store;\r
73 _BIO_s_mem p_BIO_s_mem;\r
74 _BIO_new p_BIO_new;\r
75 _BIO_free p_BIO_free;\r
76 _BIO_new_mem_buf p_BIO_new_mem_buf;\r
77 _BIO_ctrl p_BIO_ctrl;\r
78 _X509_free p_X509_free;\r
79 _X509_print_ex p_X509_print_ex;\r
80 _X509_get_subject_name p_X509_get_subject_name;\r
81 _X509_NAME_print_ex p_X509_NAME_print_ex;\r
82 _PEM_read_bio_X509 p_PEM_read_bio_X509;\r
83 _X509_STORE_add_cert p_X509_STORE_add_cert;\r
84 \r
85 #define MAX_SSL_SOCKET 16\r
86 \r
87 BOOL g_bOpenSSLLoaded;\r
88 HMODULE g_hOpenSSL;\r
89 HMODULE g_hOpenSSLCommon;\r
90 CRITICAL_SECTION g_OpenSSLLock;\r
91 DWORD g_OpenSSLTimeout;\r
92 LPSSLTIMEOUTCALLBACK g_pOpenSSLTimeoutCallback;\r
93 LPSSLCONFIRMCALLBACK g_pOpenSSLConfirmCallback;\r
94 SSL_CTX* g_pOpenSSLCTX;\r
95 SSL* g_pOpenSSLHandle[MAX_SSL_SOCKET];\r
96 \r
97 BOOL __stdcall DefaultSSLTimeoutCallback(BOOL* pbAborted)\r
98 {\r
99         Sleep(100);\r
100         return *pbAborted;\r
101 }\r
102 \r
103 BOOL __stdcall DefaultSSLConfirmCallback(BOOL* pbAborted, BOOL bVerified, LPCSTR Certificate, LPCSTR CommonName)\r
104 {\r
105         return bVerified;\r
106 }\r
107 \r
108 // OpenSSLを初期化\r
109 BOOL LoadOpenSSL()\r
110 {\r
111         if(g_bOpenSSLLoaded)\r
112                 return FALSE;\r
113 #ifdef ENABLE_PROCESS_PROTECTION\r
114         // 同梱するOpenSSLのバージョンに合わせてSHA1ハッシュ値を変更すること\r
115         // ssleay32.dll 1.0.0e\r
116         // libssl32.dll 1.0.0e\r
117         RegisterTrustedModuleSHA1Hash("\x4E\xB7\xA0\x22\x14\x4B\x58\x6D\xBC\xF5\x21\x0D\x96\x78\x0D\x79\x7D\x66\xB2\xB0");\r
118         // libeay32.dll 1.0.0e\r
119         RegisterTrustedModuleSHA1Hash("\x01\x32\x7A\xAE\x69\x26\xE6\x58\xC7\x63\x22\x1E\x53\x5A\x78\xBC\x61\xC7\xB5\xC1");\r
120 #endif\r
121         g_hOpenSSL = LoadLibrary("ssleay32.dll");\r
122         // バージョン固定のためlibssl32.dllの読み込みは脆弱性の原因になり得るので廃止\r
123 //      if(!g_hOpenSSL)\r
124 //              g_hOpenSSL = LoadLibrary("libssl32.dll");\r
125         if(!g_hOpenSSL\r
126                 || !(p_SSL_load_error_strings = (_SSL_load_error_strings)GetProcAddress(g_hOpenSSL, "SSL_load_error_strings"))\r
127                 || !(p_SSL_library_init = (_SSL_library_init)GetProcAddress(g_hOpenSSL, "SSL_library_init"))\r
128                 || !(p_SSLv23_method = (_SSLv23_method)GetProcAddress(g_hOpenSSL, "SSLv23_method"))\r
129                 || !(p_SSL_CTX_new = (_SSL_CTX_new)GetProcAddress(g_hOpenSSL, "SSL_CTX_new"))\r
130                 || !(p_SSL_CTX_free = (_SSL_CTX_free)GetProcAddress(g_hOpenSSL, "SSL_CTX_free"))\r
131                 || !(p_SSL_new = (_SSL_new)GetProcAddress(g_hOpenSSL, "SSL_new"))\r
132                 || !(p_SSL_free = (_SSL_free)GetProcAddress(g_hOpenSSL, "SSL_free"))\r
133                 || !(p_SSL_shutdown = (_SSL_shutdown)GetProcAddress(g_hOpenSSL, "SSL_shutdown"))\r
134                 || !(p_SSL_get_fd = (_SSL_get_fd)GetProcAddress(g_hOpenSSL, "SSL_get_fd"))\r
135                 || !(p_SSL_set_fd = (_SSL_set_fd)GetProcAddress(g_hOpenSSL, "SSL_set_fd"))\r
136                 || !(p_SSL_accept = (_SSL_accept)GetProcAddress(g_hOpenSSL, "SSL_accept"))\r
137                 || !(p_SSL_connect = (_SSL_connect)GetProcAddress(g_hOpenSSL, "SSL_connect"))\r
138                 || !(p_SSL_write = (_SSL_write)GetProcAddress(g_hOpenSSL, "SSL_write"))\r
139                 || !(p_SSL_peek = (_SSL_peek)GetProcAddress(g_hOpenSSL, "SSL_peek"))\r
140                 || !(p_SSL_read = (_SSL_read)GetProcAddress(g_hOpenSSL, "SSL_read"))\r
141                 || !(p_SSL_get_error = (_SSL_get_error)GetProcAddress(g_hOpenSSL, "SSL_get_error"))\r
142                 || !(p_SSL_get_peer_certificate = (_SSL_get_peer_certificate)GetProcAddress(g_hOpenSSL, "SSL_get_peer_certificate"))\r
143                 || !(p_SSL_get_verify_result = (_SSL_get_verify_result)GetProcAddress(g_hOpenSSL, "SSL_get_verify_result"))\r
144                 || !(p_SSL_get_session = (_SSL_get_session)GetProcAddress(g_hOpenSSL, "SSL_get_session"))\r
145                 || !(p_SSL_set_session = (_SSL_set_session)GetProcAddress(g_hOpenSSL, "SSL_set_session"))\r
146                 || !(p_SSL_CTX_get_cert_store = (_SSL_CTX_get_cert_store)GetProcAddress(g_hOpenSSL, "SSL_CTX_get_cert_store")))\r
147         {\r
148                 if(g_hOpenSSL)\r
149                         FreeLibrary(g_hOpenSSL);\r
150                 g_hOpenSSL = NULL;\r
151                 return FALSE;\r
152         }\r
153         g_hOpenSSLCommon = LoadLibrary("libeay32.dll");\r
154         if(!g_hOpenSSLCommon\r
155                 || !(p_BIO_s_mem = (_BIO_s_mem)GetProcAddress(g_hOpenSSLCommon, "BIO_s_mem"))\r
156                 || !(p_BIO_new = (_BIO_new)GetProcAddress(g_hOpenSSLCommon, "BIO_new"))\r
157                 || !(p_BIO_free = (_BIO_free)GetProcAddress(g_hOpenSSLCommon, "BIO_free"))\r
158                 || !(p_BIO_new_mem_buf = (_BIO_new_mem_buf)GetProcAddress(g_hOpenSSLCommon, "BIO_new_mem_buf"))\r
159                 || !(p_BIO_ctrl = (_BIO_ctrl)GetProcAddress(g_hOpenSSLCommon, "BIO_ctrl"))\r
160                 || !(p_X509_free = (_X509_free)GetProcAddress(g_hOpenSSLCommon, "X509_free"))\r
161                 || !(p_X509_print_ex = (_X509_print_ex)GetProcAddress(g_hOpenSSLCommon, "X509_print_ex"))\r
162                 || !(p_X509_get_subject_name = (_X509_get_subject_name)GetProcAddress(g_hOpenSSLCommon, "X509_get_subject_name"))\r
163                 || !(p_X509_NAME_print_ex = (_X509_NAME_print_ex)GetProcAddress(g_hOpenSSLCommon, "X509_NAME_print_ex"))\r
164                 || !(p_PEM_read_bio_X509 = (_PEM_read_bio_X509)GetProcAddress(g_hOpenSSLCommon, "PEM_read_bio_X509"))\r
165                 || !(p_X509_STORE_add_cert = (_X509_STORE_add_cert)GetProcAddress(g_hOpenSSLCommon, "X509_STORE_add_cert")))\r
166         {\r
167                 if(g_hOpenSSL)\r
168                         FreeLibrary(g_hOpenSSL);\r
169                 g_hOpenSSL = NULL;\r
170                 if(g_hOpenSSLCommon)\r
171                         FreeLibrary(g_hOpenSSLCommon);\r
172                 g_hOpenSSLCommon = NULL;\r
173                 return FALSE;\r
174         }\r
175         InitializeCriticalSection(&g_OpenSSLLock);\r
176         p_SSL_load_error_strings();\r
177         p_SSL_library_init();\r
178         SetSSLTimeoutCallback(60000, DefaultSSLTimeoutCallback);\r
179         SetSSLConfirmCallback(DefaultSSLConfirmCallback);\r
180         g_bOpenSSLLoaded = TRUE;\r
181         return TRUE;\r
182 }\r
183 \r
184 // OpenSSLを解放\r
185 void FreeOpenSSL()\r
186 {\r
187         int i;\r
188         if(!g_bOpenSSLLoaded)\r
189                 return;\r
190         EnterCriticalSection(&g_OpenSSLLock);\r
191         for(i = 0; i < MAX_SSL_SOCKET; i++)\r
192         {\r
193                 if(g_pOpenSSLHandle[i])\r
194                 {\r
195                         p_SSL_shutdown(g_pOpenSSLHandle[i]);\r
196                         p_SSL_free(g_pOpenSSLHandle[i]);\r
197                         g_pOpenSSLHandle[i] = NULL;\r
198                 }\r
199         }\r
200         if(g_pOpenSSLCTX)\r
201                 p_SSL_CTX_free(g_pOpenSSLCTX);\r
202         g_pOpenSSLCTX = NULL;\r
203         FreeLibrary(g_hOpenSSL);\r
204         g_hOpenSSL = NULL;\r
205         FreeLibrary(g_hOpenSSLCommon);\r
206         g_hOpenSSLCommon = NULL;\r
207         LeaveCriticalSection(&g_OpenSSLLock);\r
208         DeleteCriticalSection(&g_OpenSSLLock);\r
209         g_bOpenSSLLoaded = FALSE;\r
210 }\r
211 \r
212 // OpenSSLが使用可能かどうか確認\r
213 BOOL IsOpenSSLLoaded()\r
214 {\r
215         return g_bOpenSSLLoaded;\r
216 }\r
217 \r
218 SSL** GetUnusedSSLPointer()\r
219 {\r
220         int i;\r
221         for(i = 0; i < MAX_SSL_SOCKET; i++)\r
222         {\r
223                 if(!g_pOpenSSLHandle[i])\r
224                         return &g_pOpenSSLHandle[i];\r
225         }\r
226         return NULL;\r
227 }\r
228 \r
229 SSL** FindSSLPointerFromSocket(SOCKET s)\r
230 {\r
231         int i;\r
232         for(i = 0; i < MAX_SSL_SOCKET; i++)\r
233         {\r
234                 if(g_pOpenSSLHandle[i])\r
235                 {\r
236                         if(p_SSL_get_fd(g_pOpenSSLHandle[i]) == s)\r
237                                 return &g_pOpenSSLHandle[i];\r
238                 }\r
239         }\r
240         return NULL;\r
241 }\r
242 \r
243 BOOL ConfirmSSLCertificate(SSL* pSSL, BOOL* pbAborted)\r
244 {\r
245         BOOL bResult;\r
246         BOOL bVerified;\r
247         char* pData;\r
248         char* pSubject;\r
249         X509* pX509;\r
250         BIO* pBIO;\r
251         long Length;\r
252         char* pBuffer;\r
253         char* pCN;\r
254         char* p;\r
255         bResult = FALSE;\r
256         bVerified = FALSE;\r
257         pData = NULL;\r
258         pSubject = NULL;\r
259         if(pX509 = p_SSL_get_peer_certificate(pSSL))\r
260         {\r
261                 if(pBIO = p_BIO_new(p_BIO_s_mem()))\r
262                 {\r
263                         p_X509_print_ex(pBIO, pX509, 0, XN_FLAG_RFC2253);\r
264                         if((Length = p_BIO_ctrl(pBIO, BIO_CTRL_INFO, 0, &pBuffer)) > 0)\r
265                         {\r
266                                 if(pData = (char*)malloc(Length + sizeof(char)))\r
267                                 {\r
268                                         memcpy(pData, pBuffer, Length);\r
269                                         *(char*)((size_t)pData + Length) = '\0';\r
270                                 }\r
271                         }\r
272                         p_BIO_free(pBIO);\r
273                 }\r
274                 if(pBIO = p_BIO_new(p_BIO_s_mem()))\r
275                 {\r
276                         p_X509_NAME_print_ex(pBIO, p_X509_get_subject_name(pX509), 0, XN_FLAG_RFC2253);\r
277                         if((Length = p_BIO_ctrl(pBIO, BIO_CTRL_INFO, 0, &pBuffer)) > 0)\r
278                         {\r
279                                 if(pSubject = (char*)malloc(Length + sizeof(char)))\r
280                                 {\r
281                                         memcpy(pSubject, pBuffer, Length);\r
282                                         *(char*)((size_t)pSubject + Length) = '\0';\r
283                                 }\r
284                         }\r
285                         p_BIO_free(pBIO);\r
286                 }\r
287                 p_X509_free(pX509);\r
288         }\r
289         if(pX509 && p_SSL_get_verify_result(pSSL) == X509_V_OK)\r
290                 bVerified = TRUE;\r
291         pCN = pSubject;\r
292         while(pCN)\r
293         {\r
294                 if(strncmp(pCN, "CN=", strlen("CN=")) == 0)\r
295                 {\r
296                         pCN += strlen("CN=");\r
297                         if(p = strchr(pCN, ','))\r
298                                 *p = '\0';\r
299                         break;\r
300                 }\r
301                 if(pCN = strchr(pCN, ','))\r
302                         pCN++;\r
303         }\r
304         bResult = g_pOpenSSLConfirmCallback(pbAborted, bVerified, pData, pCN);\r
305         if(pData)\r
306                 free(pData);\r
307         if(pSubject)\r
308                 free(pSubject);\r
309         return bResult;\r
310 }\r
311 \r
312 void SetSSLTimeoutCallback(DWORD Timeout, LPSSLTIMEOUTCALLBACK pCallback)\r
313 {\r
314         if(!g_bOpenSSLLoaded)\r
315                 return;\r
316         EnterCriticalSection(&g_OpenSSLLock);\r
317         g_OpenSSLTimeout = Timeout;\r
318         g_pOpenSSLTimeoutCallback = pCallback;\r
319         LeaveCriticalSection(&g_OpenSSLLock);\r
320 }\r
321 \r
322 void SetSSLConfirmCallback(LPSSLCONFIRMCALLBACK pCallback)\r
323 {\r
324         if(!g_bOpenSSLLoaded)\r
325                 return;\r
326         EnterCriticalSection(&g_OpenSSLLock);\r
327         g_pOpenSSLConfirmCallback = pCallback;\r
328         LeaveCriticalSection(&g_OpenSSLLock);\r
329 }\r
330 \r
331 // SSLルート証明書を設定\r
332 // PEM形式のみ指定可能\r
333 BOOL SetSSLRootCertificate(const void* pData, DWORD Length)\r
334 {\r
335         BOOL r;\r
336         X509_STORE* pStore;\r
337         BYTE* p;\r
338         BYTE* pBegin;\r
339         BYTE* pEnd;\r
340         BIO* pBIO;\r
341         X509* pX509;\r
342         if(!g_bOpenSSLLoaded)\r
343                 return FALSE;\r
344         r = FALSE;\r
345         EnterCriticalSection(&g_OpenSSLLock);\r
346         if(!g_pOpenSSLCTX)\r
347                 g_pOpenSSLCTX = p_SSL_CTX_new(p_SSLv23_method());\r
348         if(g_pOpenSSLCTX)\r
349         {\r
350                 if(pStore = p_SSL_CTX_get_cert_store(g_pOpenSSLCTX))\r
351                 {\r
352                         p = (BYTE*)pData;\r
353                         pBegin = NULL;\r
354                         pEnd = NULL;\r
355                         while(Length > 0)\r
356                         {\r
357                                 if(!pBegin)\r
358                                 {\r
359                                         if(Length < 27)\r
360                                                 break;\r
361                                         if(memcmp(p, "-----BEGIN CERTIFICATE-----", 27) == 0)\r
362                                                 pBegin = p;\r
363                                 }\r
364                                 else if(!pEnd)\r
365                                 {\r
366                                         if(Length < 25)\r
367                                                 break;\r
368                                         if(memcmp(p, "-----END CERTIFICATE-----", 25) == 0)\r
369                                                 pEnd = p + 25;\r
370                                 }\r
371                                 if(pBegin && pEnd)\r
372                                 {\r
373                                         if(pBIO = p_BIO_new_mem_buf(pBegin, (int)((size_t)pEnd - (size_t)pBegin)))\r
374                                         {\r
375                                                 if(pX509 = p_PEM_read_bio_X509(pBIO, NULL, NULL, NULL))\r
376                                                 {\r
377                                                         if(p_X509_STORE_add_cert(pStore, pX509) == 1)\r
378                                                                 r = TRUE;\r
379                                                         p_X509_free(pX509);\r
380                                                 }\r
381                                                 p_BIO_free(pBIO);\r
382                                         }\r
383                                         pBegin = NULL;\r
384                                         pEnd = NULL;\r
385                                 }\r
386                                 p++;\r
387                                 Length--;\r
388                         }\r
389                 }\r
390         }\r
391         LeaveCriticalSection(&g_OpenSSLLock);\r
392         return r;\r
393 }\r
394 \r
395 // ワイルドカードの比較\r
396 // 主にSSL証明書のCN確認用\r
397 BOOL IsHostNameMatched(LPCSTR HostName, LPCSTR CommonName)\r
398 {\r
399         BOOL bResult;\r
400         char* pAsterisk;\r
401         bResult = FALSE;\r
402         if(HostName && CommonName)\r
403         {\r
404                 if(pAsterisk = strchr(CommonName, '*'))\r
405                 {\r
406                         if(_strnicmp(HostName, CommonName, ((size_t)pAsterisk - (size_t)CommonName) / sizeof(char)) == 0)\r
407                         {\r
408                                 while(*pAsterisk == '*')\r
409                                 {\r
410                                         pAsterisk++;\r
411                                 }\r
412                                 if(_stricmp(HostName + strlen(HostName) - strlen(pAsterisk), pAsterisk) == 0)\r
413                                         bResult = TRUE;\r
414                         }\r
415                 }\r
416                 else if(_stricmp(HostName, CommonName) == 0)\r
417                         bResult = TRUE;\r
418         }\r
419         return bResult;\r
420 }\r
421 \r
422 // SSLセッションを開始\r
423 BOOL AttachSSL(SOCKET s, SOCKET parent, BOOL* pbAborted)\r
424 {\r
425         BOOL r;\r
426         DWORD Time;\r
427         SSL** ppSSL;\r
428         SSL** ppSSLParent;\r
429         SSL_SESSION* pSession;\r
430         int Return;\r
431         int Error;\r
432         if(!g_bOpenSSLLoaded)\r
433                 return FALSE;\r
434         r = FALSE;\r
435         Time = timeGetTime();\r
436         EnterCriticalSection(&g_OpenSSLLock);\r
437         if(!g_pOpenSSLCTX)\r
438                 g_pOpenSSLCTX = p_SSL_CTX_new(p_SSLv23_method());\r
439         if(g_pOpenSSLCTX)\r
440         {\r
441                 if(ppSSL = GetUnusedSSLPointer())\r
442                 {\r
443                         if(*ppSSL = p_SSL_new(g_pOpenSSLCTX))\r
444                         {\r
445                                 if(p_SSL_set_fd(*ppSSL, s) != 0)\r
446                                 {\r
447                                         if(parent != INVALID_SOCKET)\r
448                                         {\r
449                                                 if(ppSSLParent = FindSSLPointerFromSocket(parent))\r
450                                                 {\r
451                                                         if(pSession = p_SSL_get_session(*ppSSLParent))\r
452                                                         {\r
453                                                                 if(p_SSL_set_session(*ppSSL, pSession) == 1)\r
454                                                                 {\r
455                                                                 }\r
456                                                         }\r
457                                                 }\r
458                                         }\r
459                                         // SSLのネゴシエーションには時間がかかる場合がある\r
460                                         r = TRUE;\r
461                                         while(r)\r
462                                         {\r
463                                                 Return = p_SSL_connect(*ppSSL);\r
464                                                 if(Return == 1)\r
465                                                         break;\r
466                                                 Error = p_SSL_get_error(*ppSSL, Return);\r
467                                                 if(Error == SSL_ERROR_WANT_READ || Error == SSL_ERROR_WANT_WRITE)\r
468                                                 {\r
469                                                         LeaveCriticalSection(&g_OpenSSLLock);\r
470                                                         if(g_pOpenSSLTimeoutCallback(pbAborted) || (g_OpenSSLTimeout > 0 && timeGetTime() - Time >= g_OpenSSLTimeout))\r
471                                                                 r = FALSE;\r
472                                                         EnterCriticalSection(&g_OpenSSLLock);\r
473                                                 }\r
474                                                 else\r
475                                                         r = FALSE;\r
476                                         }\r
477                                         if(r)\r
478                                         {\r
479                                                 if(ConfirmSSLCertificate(*ppSSL, pbAborted))\r
480                                                 {\r
481                                                 }\r
482                                                 else\r
483                                                 {\r
484                                                         LeaveCriticalSection(&g_OpenSSLLock);\r
485                                                         DetachSSL(s);\r
486                                                         r = FALSE;\r
487                                                         EnterCriticalSection(&g_OpenSSLLock);\r
488                                                 }\r
489                                         }\r
490                                         else\r
491                                         {\r
492                                                 LeaveCriticalSection(&g_OpenSSLLock);\r
493                                                 DetachSSL(s);\r
494                                                 EnterCriticalSection(&g_OpenSSLLock);\r
495                                         }\r
496                                 }\r
497                                 else\r
498                                 {\r
499                                         LeaveCriticalSection(&g_OpenSSLLock);\r
500                                         DetachSSL(s);\r
501                                         EnterCriticalSection(&g_OpenSSLLock);\r
502                                 }\r
503                         }\r
504                 }\r
505         }\r
506         LeaveCriticalSection(&g_OpenSSLLock);\r
507         return r;\r
508 }\r
509 \r
510 // SSLセッションを終了\r
511 BOOL DetachSSL(SOCKET s)\r
512 {\r
513         BOOL r;\r
514         SSL** ppSSL;\r
515         if(!g_bOpenSSLLoaded)\r
516                 return FALSE;\r
517         r = FALSE;\r
518         EnterCriticalSection(&g_OpenSSLLock);\r
519         if(ppSSL = FindSSLPointerFromSocket(s))\r
520         {\r
521                 p_SSL_shutdown(*ppSSL);\r
522                 p_SSL_free(*ppSSL);\r
523                 *ppSSL = NULL;\r
524                 r = TRUE;\r
525         }\r
526         LeaveCriticalSection(&g_OpenSSLLock);\r
527         return r;\r
528 }\r
529 \r
530 // SSLとしてマークされているか確認\r
531 // マークされていればTRUEを返す\r
532 BOOL IsSSLAttached(SOCKET s)\r
533 {\r
534         SSL** ppSSL;\r
535         if(!g_bOpenSSLLoaded)\r
536                 return FALSE;\r
537         EnterCriticalSection(&g_OpenSSLLock);\r
538         ppSSL = FindSSLPointerFromSocket(s);\r
539         LeaveCriticalSection(&g_OpenSSLLock);\r
540         if(!ppSSL)\r
541                 return FALSE;\r
542         return TRUE;\r
543 }\r
544 \r
545 SOCKET socketS(int af, int type, int protocol)\r
546 {\r
547         return socket(af, type, protocol);\r
548 }\r
549 \r
550 int bindS(SOCKET s, const struct sockaddr *addr, int namelen)\r
551 {\r
552         return bind(s, addr, namelen);\r
553 }\r
554 \r
555 int listenS(SOCKET s, int backlog)\r
556 {\r
557         return listen(s, backlog);\r
558 }\r
559 \r
560 // accept相当の関数\r
561 // ただし初めからSSLのネゴシエーションを行う\r
562 SOCKET acceptS(SOCKET s, struct sockaddr *addr, int *addrlen)\r
563 {\r
564         SOCKET r;\r
565         BOOL bAborted;\r
566         r = accept(s, addr, addrlen);\r
567         bAborted = FALSE;\r
568         if(!AttachSSL(r, INVALID_SOCKET, &bAborted))\r
569         {\r
570                 closesocket(r);\r
571                 return INVALID_SOCKET;\r
572         }\r
573         return r;\r
574 }\r
575 \r
576 // connect相当の関数\r
577 // ただし初めからSSLのネゴシエーションを行う\r
578 int connectS(SOCKET s, const struct sockaddr *name, int namelen)\r
579 {\r
580         int r;\r
581         BOOL bAborted;\r
582         r = connect(s, name, namelen);\r
583         bAborted = FALSE;\r
584         if(!AttachSSL(r, INVALID_SOCKET, &bAborted))\r
585                 return SOCKET_ERROR;\r
586         return r;\r
587 }\r
588 \r
589 // closesocket相当の関数\r
590 int closesocketS(SOCKET s)\r
591 {\r
592         DetachSSL(s);\r
593         return closesocket(s);\r
594 }\r
595 \r
596 // send相当の関数\r
597 int sendS(SOCKET s, const char * buf, int len, int flags)\r
598 {\r
599         SSL** ppSSL;\r
600         if(!g_bOpenSSLLoaded)\r
601                 return send(s, buf, len, flags);\r
602         EnterCriticalSection(&g_OpenSSLLock);\r
603         ppSSL = FindSSLPointerFromSocket(s);\r
604         LeaveCriticalSection(&g_OpenSSLLock);\r
605         if(!ppSSL)\r
606                 return send(s, buf, len, flags);\r
607         return p_SSL_write(*ppSSL, buf, len);\r
608 }\r
609 \r
610 // recv相当の関数\r
611 int recvS(SOCKET s, char * buf, int len, int flags)\r
612 {\r
613         SSL** ppSSL;\r
614         if(!g_bOpenSSLLoaded)\r
615                 return recv(s, buf, len, flags);\r
616         EnterCriticalSection(&g_OpenSSLLock);\r
617         ppSSL = FindSSLPointerFromSocket(s);\r
618         LeaveCriticalSection(&g_OpenSSLLock);\r
619         if(!ppSSL)\r
620                 return recv(s, buf, len, flags);\r
621         if(flags & MSG_PEEK)\r
622                 return p_SSL_peek(*ppSSL, buf, len);\r
623         return p_SSL_read(*ppSSL, buf, len);\r
624 }\r
625 \r
626 // IPv6対応\r
627 \r
628 typedef struct\r
629 {\r
630         HANDLE h;\r
631         HWND hWnd;\r
632         u_int wMsg;\r
633         char * name;\r
634         char * buf;\r
635         int buflen;\r
636         short Family;\r
637 } GETHOSTBYNAMEDATA;\r
638 \r
639 DWORD WINAPI WSAAsyncGetHostByNameIPv6ThreadProc(LPVOID lpParameter)\r
640 {\r
641         GETHOSTBYNAMEDATA* pData;\r
642         struct hostent* pHost;\r
643         struct addrinfo* pAddr;\r
644         struct addrinfo* p;\r
645         pHost = NULL;\r
646         pData = (GETHOSTBYNAMEDATA*)lpParameter;\r
647         if(getaddrinfo(pData->name, NULL, NULL, &pAddr) == 0)\r
648         {\r
649                 p = pAddr;\r
650                 while(p)\r
651                 {\r
652                         if(p->ai_family == pData->Family)\r
653                         {\r
654                                 switch(p->ai_family)\r
655                                 {\r
656                                 case AF_INET:\r
657                                         pHost = (struct hostent*)pData->buf;\r
658                                         if((size_t)pData->buflen >= sizeof(struct hostent) + sizeof(char*) * 2 + sizeof(struct in_addr)\r
659                                                 && p->ai_addrlen >= sizeof(struct sockaddr_in))\r
660                                         {\r
661                                                 pHost->h_name = NULL;\r
662                                                 pHost->h_aliases = NULL;\r
663                                                 pHost->h_addrtype = p->ai_family;\r
664                                                 pHost->h_length = sizeof(struct in_addr);\r
665                                                 pHost->h_addr_list = (char**)(&pHost[1]);\r
666                                                 pHost->h_addr_list[0] = (char*)(&pHost->h_addr_list[2]);\r
667                                                 pHost->h_addr_list[1] = NULL;\r
668                                                 memcpy(pHost->h_addr_list[0], &((struct sockaddr_in*)p->ai_addr)->sin_addr, sizeof(struct in_addr));\r
669                                                 PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(sizeof(struct hostent) + sizeof(char*) * 2 + p->ai_addrlen));\r
670                                         }\r
671                                         else\r
672                                                 PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(WSAENOBUFS << 16));\r
673                                         break;\r
674                                 case AF_INET6:\r
675                                         pHost = (struct hostent*)pData->buf;\r
676                                         if((size_t)pData->buflen >= sizeof(struct hostent) + sizeof(char*) * 2 + sizeof(struct in6_addr)\r
677                                                 && p->ai_addrlen >= sizeof(struct sockaddr_in6))\r
678                                         {\r
679                                                 pHost->h_name = NULL;\r
680                                                 pHost->h_aliases = NULL;\r
681                                                 pHost->h_addrtype = p->ai_family;\r
682                                                 pHost->h_length = sizeof(struct in6_addr);\r
683                                                 pHost->h_addr_list = (char**)(&pHost[1]);\r
684                                                 pHost->h_addr_list[0] = (char*)(&pHost->h_addr_list[2]);\r
685                                                 pHost->h_addr_list[1] = NULL;\r
686                                                 memcpy(pHost->h_addr_list[0], &((struct sockaddr_in6*)p->ai_addr)->sin6_addr, sizeof(struct in6_addr));\r
687                                                 PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(sizeof(struct hostent) + sizeof(char*) * 2 + p->ai_addrlen));\r
688                                         }\r
689                                         else\r
690                                                 PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(WSAENOBUFS << 16));\r
691                                         break;\r
692                                 }\r
693                         }\r
694                         if(pHost)\r
695                                 break;\r
696                         p = p->ai_next;\r
697                 }\r
698                 if(!p)\r
699                         PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(ERROR_INVALID_FUNCTION << 16));\r
700                 freeaddrinfo(pAddr);\r
701         }\r
702         else\r
703                 PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(ERROR_INVALID_FUNCTION << 16));\r
704         free(pData->name);\r
705         free(pData);\r
706         // CreateThreadが返すハンドルが重複するのを回避\r
707         Sleep(10000);\r
708         return 0;\r
709 }\r
710 \r
711 // IPv6対応のWSAAsyncGetHostByName相当の関数\r
712 // FamilyにはAF_INETまたはAF_INET6を指定可能\r
713 // ただしANSI用\r
714 HANDLE WSAAsyncGetHostByNameIPv6(HWND hWnd, u_int wMsg, const char * name, char * buf, int buflen, short Family)\r
715 {\r
716         HANDLE hResult;\r
717         GETHOSTBYNAMEDATA* pData;\r
718         hResult = NULL;\r
719         if(pData = malloc(sizeof(GETHOSTBYNAMEDATA)))\r
720         {\r
721                 pData->hWnd = hWnd;\r
722                 pData->wMsg = wMsg;\r
723                 if(pData->name = malloc(sizeof(char) * (strlen(name) + 1)))\r
724                 {\r
725                         strcpy(pData->name, name);\r
726                         pData->buf = buf;\r
727                         pData->buflen = buflen;\r
728                         pData->Family = Family;\r
729                         if(pData->h = CreateThread(NULL, 0, WSAAsyncGetHostByNameIPv6ThreadProc, pData, CREATE_SUSPENDED, NULL))\r
730                         {\r
731                                 ResumeThread(pData->h);\r
732                                 hResult = pData->h;\r
733                         }\r
734                 }\r
735         }\r
736         if(!hResult)\r
737         {\r
738                 if(pData)\r
739                 {\r
740                         if(pData->name)\r
741                                 free(pData->name);\r
742                         free(pData);\r
743                 }\r
744         }\r
745         return hResult;\r
746 }\r
747 \r
748 // WSAAsyncGetHostByNameIPv6用のWSACancelAsyncRequest相当の関数\r
749 int WSACancelAsyncRequestIPv6(HANDLE hAsyncTaskHandle)\r
750 {\r
751         int Result;\r
752         Result = SOCKET_ERROR;\r
753         if(TerminateThread(hAsyncTaskHandle, 0))\r
754                 Result = 0;\r
755         return Result;\r
756 }\r
757 \r
758 char* AddressToStringIPv6(char* str, void* in6)\r
759 {\r
760         char* pResult;\r
761         unsigned char* p;\r
762         int MaxZero;\r
763         int MaxZeroLen;\r
764         int i;\r
765         int j;\r
766         char Tmp[5];\r
767         pResult = str;\r
768         p = (unsigned char*)in6;\r
769         MaxZero = 8;\r
770         MaxZeroLen = 1;\r
771         for(i = 0; i < 8; i++)\r
772         {\r
773                 for(j = i; j < 8; j++)\r
774                 {\r
775                         if(p[j * 2] != 0 || p[j * 2 + 1] != 0)\r
776                                 break;\r
777                 }\r
778                 if(j - i > MaxZeroLen)\r
779                 {\r
780                         MaxZero = i;\r
781                         MaxZeroLen = j - i;\r
782                 }\r
783         }\r
784         strcpy(str, "");\r
785         for(i = 0; i < 8; i++)\r
786         {\r
787                 if(i == MaxZero)\r
788                 {\r
789                         if(i == 0)\r
790                                 strcat(str, ":");\r
791                         strcat(str, ":");\r
792                 }\r
793                 else if(i < MaxZero || i >= MaxZero + MaxZeroLen)\r
794                 {\r
795                         sprintf(Tmp, "%x", (((int)p[i * 2] & 0xff) << 8) | ((int)p[i * 2 + 1] & 0xff));\r
796                         strcat(str, Tmp);\r
797                         if(i < 7)\r
798                                 strcat(str, ":");\r
799                 }\r
800         }\r
801         return pResult;\r
802 }\r
803 \r
804 // IPv6対応のinet_ntoa相当の関数\r
805 // ただしANSI用\r
806 char* inet6_ntoa(struct in6_addr in6)\r
807 {\r
808         char* pResult;\r
809         static char Adrs[40];\r
810         pResult = NULL;\r
811         memset(Adrs, 0, sizeof(Adrs));\r
812         pResult = AddressToStringIPv6(Adrs, &in6);\r
813         return pResult;\r
814 }\r
815 \r
816 // IPv6対応のinet_addr相当の関数\r
817 // ただしANSI用\r
818 struct in6_addr inet6_addr(const char* cp)\r
819 {\r
820         struct in6_addr Result;\r
821         int AfterZero;\r
822         int i;\r
823         char* p;\r
824         memset(&Result, 0, sizeof(Result));\r
825         AfterZero = 0;\r
826         for(i = 0; i < 8; i++)\r
827         {\r
828                 if(!cp)\r
829                 {\r
830                         memset(&Result, 0xff, sizeof(Result));\r
831                         break;\r
832                 }\r
833                 if(i >= AfterZero)\r
834                 {\r
835                         if(strncmp(cp, ":", 1) == 0)\r
836                         {\r
837                                 cp = cp + 1;\r
838                                 if(i == 0 && strncmp(cp, ":", 1) == 0)\r
839                                         cp = cp + 1;\r
840                                 p = (char*)cp;\r
841                                 AfterZero = 7;\r
842                                 while(p = strstr(p, ":"))\r
843                                 {\r
844                                         p = p + 1;\r
845                                         AfterZero--;\r
846                                 }\r
847                         }\r
848                         else\r
849                         {\r
850                                 Result.u.Word[i] = (USHORT)strtol(cp, &p, 16);\r
851                                 Result.u.Word[i] = ((Result.u.Word[i] & 0xff00) >> 8) | ((Result.u.Word[i] & 0x00ff) << 8);\r
852                                 if(strncmp(p, ":", 1) != 0 && strlen(p) > 0)\r
853                                 {\r
854                                         memset(&Result, 0xff, sizeof(Result));\r
855                                         break;\r
856                                 }\r
857                                 if(cp = strstr(cp, ":"))\r
858                                         cp = cp + 1;\r
859                         }\r
860                 }\r
861         }\r
862         return Result;\r
863 }\r
864 \r
865 BOOL ConvertDomainNameToPunycode(LPSTR Output, DWORD Count, LPCSTR Input)\r
866 {\r
867         BOOL bResult;\r
868         punycode_uint* pUnicode;\r
869         punycode_uint* p;\r
870         BOOL bNeeded;\r
871         LPCSTR InputString;\r
872         punycode_uint Length;\r
873         punycode_uint OutputLength;\r
874         bResult = FALSE;\r
875         if(pUnicode = malloc(sizeof(punycode_uint) * strlen(Input)))\r
876         {\r
877                 p = pUnicode;\r
878                 bNeeded = FALSE;\r
879                 InputString = Input;\r
880                 Length = 0;\r
881                 while(*InputString != '\0')\r
882                 {\r
883                         *p = (punycode_uint)GetNextCharM(InputString, &InputString);\r
884                         if(*p >= 0x80)\r
885                                 bNeeded = TRUE;\r
886                         p++;\r
887                         Length++;\r
888                 }\r
889                 if(bNeeded)\r
890                 {\r
891                         if(Count >= strlen("xn--") + 1)\r
892                         {\r
893                                 strcpy(Output, "xn--");\r
894                                 OutputLength = Count - strlen("xn--");\r
895                                 if(punycode_encode(Length, pUnicode, NULL, (punycode_uint*)&OutputLength, Output + strlen("xn--")) == punycode_success)\r
896                                 {\r
897                                         Output[strlen("xn--") + OutputLength] = '\0';\r
898                                         bResult = TRUE;\r
899                                 }\r
900                         }\r
901                 }\r
902                 free(pUnicode);\r
903         }\r
904         if(!bResult)\r
905         {\r
906                 if(Count >= strlen(Input) + 1)\r
907                 {\r
908                         strcpy(Output, Input);\r
909                         bResult = TRUE;\r
910                 }\r
911         }\r
912         return bResult;\r
913 }\r
914 \r
915 BOOL ConvertNameToPunycode(LPSTR Output, LPCSTR Input)\r
916 {\r
917         BOOL bResult;\r
918         DWORD Length;\r
919         char* pm0;\r
920         char* pm1;\r
921         char* p;\r
922         char* pNext;\r
923         bResult = FALSE;\r
924         Length = strlen(Input);\r
925         if(pm0 = AllocateStringM(Length + 1))\r
926         {\r
927                 if(pm1 = AllocateStringM(Length * 4 + 1))\r
928                 {\r
929                         strcpy(pm0, Input);\r
930                         p = pm0;\r
931                         while(p)\r
932                         {\r
933                                 if(pNext = strchr(p, '.'))\r
934                                 {\r
935                                         *pNext = '\0';\r
936                                         pNext++;\r
937                                 }\r
938                                 if(ConvertDomainNameToPunycode(pm1, Length * 4, p))\r
939                                         strcat(Output, pm1);\r
940                                 if(pNext)\r
941                                         strcat(Output, ".");\r
942                                 p = pNext;\r
943                         }\r
944                         bResult = TRUE;\r
945                         FreeDuplicatedString(pm1);\r
946                 }\r
947                 FreeDuplicatedString(pm0);\r
948         }\r
949         return bResult;\r
950 }\r
951 \r
952 HANDLE WSAAsyncGetHostByNameM(HWND hWnd, u_int wMsg, const char * name, char * buf, int buflen)\r
953 {\r
954         HANDLE r = NULL;\r
955         char* pa0 = NULL;\r
956         if(pa0 = AllocateStringA(strlen(name) * 4))\r
957         {\r
958                 if(ConvertNameToPunycode(pa0, name))\r
959                         r = WSAAsyncGetHostByName(hWnd, wMsg, pa0, buf, buflen);\r
960         }\r
961         FreeDuplicatedString(pa0);\r
962         return r;\r
963 }\r
964 \r
965 HANDLE WSAAsyncGetHostByNameIPv6M(HWND hWnd, u_int wMsg, const char * name, char * buf, int buflen, short Family)\r
966 {\r
967         HANDLE r = NULL;\r
968         char* pa0 = NULL;\r
969         if(pa0 = AllocateStringA(strlen(name) * 4))\r
970         {\r
971                 if(ConvertNameToPunycode(pa0, name))\r
972                         r = WSAAsyncGetHostByNameIPv6(hWnd, wMsg, pa0, buf, buflen, Family);\r
973         }\r
974         FreeDuplicatedString(pa0);\r
975         return r;\r
976 }\r
977 \r