OSDN Git Service

Normalize half / full width characters
[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 // FTPS対応\r
20 \r
21 typedef void (__cdecl* _SSL_load_error_strings)();\r
22 typedef int (__cdecl* _SSL_library_init)();\r
23 typedef SSL_METHOD* (__cdecl* _SSLv23_method)();\r
24 typedef SSL_CTX* (__cdecl* _SSL_CTX_new)(SSL_METHOD*);\r
25 typedef void (__cdecl* _SSL_CTX_free)(SSL_CTX*);\r
26 typedef SSL* (__cdecl* _SSL_new)(SSL_CTX*);\r
27 typedef void (__cdecl* _SSL_free)(SSL*);\r
28 typedef int (__cdecl* _SSL_shutdown)(SSL*);\r
29 typedef int (__cdecl* _SSL_get_fd)(SSL*);\r
30 typedef int (__cdecl* _SSL_set_fd)(SSL*, int);\r
31 typedef int (__cdecl* _SSL_accept)(SSL*);\r
32 typedef int (__cdecl* _SSL_connect)(SSL*);\r
33 typedef int (__cdecl* _SSL_write)(SSL*, const void*, int);\r
34 typedef int (__cdecl* _SSL_peek)(SSL*, void*, int);\r
35 typedef int (__cdecl* _SSL_read)(SSL*, void*, int);\r
36 typedef int (__cdecl* _SSL_get_error)(SSL*, int);\r
37 typedef X509* (__cdecl* _SSL_get_peer_certificate)(const SSL*);\r
38 typedef long (__cdecl* _SSL_get_verify_result)(const SSL*);\r
39 typedef SSL_SESSION* (__cdecl* _SSL_get_session)(SSL*);\r
40 typedef int (__cdecl* _SSL_set_session)(SSL*, SSL_SESSION*);\r
41 typedef X509_STORE* (__cdecl* _SSL_CTX_get_cert_store)(const SSL_CTX*);\r
42 typedef BIO_METHOD* (__cdecl* _BIO_s_mem)();\r
43 typedef BIO* (__cdecl* _BIO_new)(BIO_METHOD*);\r
44 typedef int (__cdecl* _BIO_free)(BIO*);\r
45 typedef BIO* (__cdecl* _BIO_new_mem_buf)(void*, int);\r
46 typedef long (__cdecl* _BIO_ctrl)(BIO*, int, long, void*);\r
47 typedef void (__cdecl* _X509_free)(X509*);\r
48 typedef int (__cdecl* _X509_print_ex)(BIO*, X509*, unsigned long, unsigned long);\r
49 typedef X509_NAME* (__cdecl* _X509_get_subject_name)(X509*);\r
50 typedef int (__cdecl* _X509_NAME_print_ex)(BIO*, X509_NAME*, int, unsigned long);\r
51 typedef X509* (__cdecl* _PEM_read_bio_X509)(BIO*, X509**, pem_password_cb*, void*);\r
52 typedef int (__cdecl* _X509_STORE_add_cert)(X509_STORE*, X509*);\r
53 \r
54 _SSL_load_error_strings p_SSL_load_error_strings;\r
55 _SSL_library_init p_SSL_library_init;\r
56 _SSLv23_method p_SSLv23_method;\r
57 _SSL_CTX_new p_SSL_CTX_new;\r
58 _SSL_CTX_free p_SSL_CTX_free;\r
59 _SSL_new p_SSL_new;\r
60 _SSL_free p_SSL_free;\r
61 _SSL_shutdown p_SSL_shutdown;\r
62 _SSL_get_fd p_SSL_get_fd;\r
63 _SSL_set_fd p_SSL_set_fd;\r
64 _SSL_accept p_SSL_accept;\r
65 _SSL_connect p_SSL_connect;\r
66 _SSL_write p_SSL_write;\r
67 _SSL_peek p_SSL_peek;\r
68 _SSL_read p_SSL_read;\r
69 _SSL_get_error p_SSL_get_error;\r
70 _SSL_get_peer_certificate p_SSL_get_peer_certificate;\r
71 _SSL_get_verify_result p_SSL_get_verify_result;\r
72 _SSL_get_session p_SSL_get_session;\r
73 _SSL_set_session p_SSL_set_session;\r
74 _SSL_CTX_get_cert_store p_SSL_CTX_get_cert_store;\r
75 _BIO_s_mem p_BIO_s_mem;\r
76 _BIO_new p_BIO_new;\r
77 _BIO_free p_BIO_free;\r
78 _BIO_new_mem_buf p_BIO_new_mem_buf;\r
79 _BIO_ctrl p_BIO_ctrl;\r
80 _X509_free p_X509_free;\r
81 _X509_print_ex p_X509_print_ex;\r
82 _X509_get_subject_name p_X509_get_subject_name;\r
83 _X509_NAME_print_ex p_X509_NAME_print_ex;\r
84 _PEM_read_bio_X509 p_PEM_read_bio_X509;\r
85 _X509_STORE_add_cert p_X509_STORE_add_cert;\r
86 \r
87 #define MAX_SSL_SOCKET 16\r
88 \r
89 BOOL g_bOpenSSLLoaded;\r
90 HMODULE g_hOpenSSL;\r
91 HMODULE g_hOpenSSLCommon;\r
92 CRITICAL_SECTION g_OpenSSLLock;\r
93 DWORD g_OpenSSLTimeout;\r
94 LPSSLTIMEOUTCALLBACK g_pOpenSSLTimeoutCallback;\r
95 LPSSLCONFIRMCALLBACK g_pOpenSSLConfirmCallback;\r
96 SSL_CTX* g_pOpenSSLCTX;\r
97 SSL* g_pOpenSSLHandle[MAX_SSL_SOCKET];\r
98 \r
99 BOOL __stdcall DefaultSSLTimeoutCallback(BOOL* pbAborted)\r
100 {\r
101         Sleep(100);\r
102         return *pbAborted;\r
103 }\r
104 \r
105 BOOL __stdcall DefaultSSLConfirmCallback(BOOL* pbAborted, BOOL bVerified, LPCSTR Certificate, LPCSTR CommonName)\r
106 {\r
107         return bVerified;\r
108 }\r
109 \r
110 // OpenSSLを初期化\r
111 BOOL LoadOpenSSL()\r
112 {\r
113         if(g_bOpenSSLLoaded)\r
114                 return FALSE;\r
115 #ifdef ENABLE_PROCESS_PROTECTION\r
116         // 同梱するOpenSSLのバージョンに合わせてSHA1ハッシュ値を変更すること\r
117         // ssleay32.dll 1.0.0e\r
118         // libssl32.dll 1.0.0e\r
119         RegisterTrustedModuleSHA1Hash("\x4E\xB7\xA0\x22\x14\x4B\x58\x6D\xBC\xF5\x21\x0D\x96\x78\x0D\x79\x7D\x66\xB2\xB0");\r
120         // libeay32.dll 1.0.0e\r
121         RegisterTrustedModuleSHA1Hash("\x01\x32\x7A\xAE\x69\x26\xE6\x58\xC7\x63\x22\x1E\x53\x5A\x78\xBC\x61\xC7\xB5\xC1");\r
122 #endif\r
123         g_hOpenSSL = LoadLibrary("ssleay32.dll");\r
124         // バージョン固定のためlibssl32.dllの読み込みは脆弱性の原因になり得るので廃止\r
125 //      if(!g_hOpenSSL)\r
126 //              g_hOpenSSL = LoadLibrary("libssl32.dll");\r
127         if(!g_hOpenSSL\r
128                 || !(p_SSL_load_error_strings = (_SSL_load_error_strings)GetProcAddress(g_hOpenSSL, "SSL_load_error_strings"))\r
129                 || !(p_SSL_library_init = (_SSL_library_init)GetProcAddress(g_hOpenSSL, "SSL_library_init"))\r
130                 || !(p_SSLv23_method = (_SSLv23_method)GetProcAddress(g_hOpenSSL, "SSLv23_method"))\r
131                 || !(p_SSL_CTX_new = (_SSL_CTX_new)GetProcAddress(g_hOpenSSL, "SSL_CTX_new"))\r
132                 || !(p_SSL_CTX_free = (_SSL_CTX_free)GetProcAddress(g_hOpenSSL, "SSL_CTX_free"))\r
133                 || !(p_SSL_new = (_SSL_new)GetProcAddress(g_hOpenSSL, "SSL_new"))\r
134                 || !(p_SSL_free = (_SSL_free)GetProcAddress(g_hOpenSSL, "SSL_free"))\r
135                 || !(p_SSL_shutdown = (_SSL_shutdown)GetProcAddress(g_hOpenSSL, "SSL_shutdown"))\r
136                 || !(p_SSL_get_fd = (_SSL_get_fd)GetProcAddress(g_hOpenSSL, "SSL_get_fd"))\r
137                 || !(p_SSL_set_fd = (_SSL_set_fd)GetProcAddress(g_hOpenSSL, "SSL_set_fd"))\r
138                 || !(p_SSL_accept = (_SSL_accept)GetProcAddress(g_hOpenSSL, "SSL_accept"))\r
139                 || !(p_SSL_connect = (_SSL_connect)GetProcAddress(g_hOpenSSL, "SSL_connect"))\r
140                 || !(p_SSL_write = (_SSL_write)GetProcAddress(g_hOpenSSL, "SSL_write"))\r
141                 || !(p_SSL_peek = (_SSL_peek)GetProcAddress(g_hOpenSSL, "SSL_peek"))\r
142                 || !(p_SSL_read = (_SSL_read)GetProcAddress(g_hOpenSSL, "SSL_read"))\r
143                 || !(p_SSL_get_error = (_SSL_get_error)GetProcAddress(g_hOpenSSL, "SSL_get_error"))\r
144                 || !(p_SSL_get_peer_certificate = (_SSL_get_peer_certificate)GetProcAddress(g_hOpenSSL, "SSL_get_peer_certificate"))\r
145                 || !(p_SSL_get_verify_result = (_SSL_get_verify_result)GetProcAddress(g_hOpenSSL, "SSL_get_verify_result"))\r
146                 || !(p_SSL_get_session = (_SSL_get_session)GetProcAddress(g_hOpenSSL, "SSL_get_session"))\r
147                 || !(p_SSL_set_session = (_SSL_set_session)GetProcAddress(g_hOpenSSL, "SSL_set_session"))\r
148                 || !(p_SSL_CTX_get_cert_store = (_SSL_CTX_get_cert_store)GetProcAddress(g_hOpenSSL, "SSL_CTX_get_cert_store")))\r
149         {\r
150                 if(g_hOpenSSL)\r
151                         FreeLibrary(g_hOpenSSL);\r
152                 g_hOpenSSL = NULL;\r
153                 return FALSE;\r
154         }\r
155         g_hOpenSSLCommon = LoadLibrary("libeay32.dll");\r
156         if(!g_hOpenSSLCommon\r
157                 || !(p_BIO_s_mem = (_BIO_s_mem)GetProcAddress(g_hOpenSSLCommon, "BIO_s_mem"))\r
158                 || !(p_BIO_new = (_BIO_new)GetProcAddress(g_hOpenSSLCommon, "BIO_new"))\r
159                 || !(p_BIO_free = (_BIO_free)GetProcAddress(g_hOpenSSLCommon, "BIO_free"))\r
160                 || !(p_BIO_new_mem_buf = (_BIO_new_mem_buf)GetProcAddress(g_hOpenSSLCommon, "BIO_new_mem_buf"))\r
161                 || !(p_BIO_ctrl = (_BIO_ctrl)GetProcAddress(g_hOpenSSLCommon, "BIO_ctrl"))\r
162                 || !(p_X509_free = (_X509_free)GetProcAddress(g_hOpenSSLCommon, "X509_free"))\r
163                 || !(p_X509_print_ex = (_X509_print_ex)GetProcAddress(g_hOpenSSLCommon, "X509_print_ex"))\r
164                 || !(p_X509_get_subject_name = (_X509_get_subject_name)GetProcAddress(g_hOpenSSLCommon, "X509_get_subject_name"))\r
165                 || !(p_X509_NAME_print_ex = (_X509_NAME_print_ex)GetProcAddress(g_hOpenSSLCommon, "X509_NAME_print_ex"))\r
166                 || !(p_PEM_read_bio_X509 = (_PEM_read_bio_X509)GetProcAddress(g_hOpenSSLCommon, "PEM_read_bio_X509"))\r
167                 || !(p_X509_STORE_add_cert = (_X509_STORE_add_cert)GetProcAddress(g_hOpenSSLCommon, "X509_STORE_add_cert")))\r
168         {\r
169                 if(g_hOpenSSL)\r
170                         FreeLibrary(g_hOpenSSL);\r
171                 g_hOpenSSL = NULL;\r
172                 if(g_hOpenSSLCommon)\r
173                         FreeLibrary(g_hOpenSSLCommon);\r
174                 g_hOpenSSLCommon = NULL;\r
175                 return FALSE;\r
176         }\r
177         InitializeCriticalSection(&g_OpenSSLLock);\r
178         p_SSL_load_error_strings();\r
179         p_SSL_library_init();\r
180         SetSSLTimeoutCallback(60000, DefaultSSLTimeoutCallback);\r
181         SetSSLConfirmCallback(DefaultSSLConfirmCallback);\r
182         g_bOpenSSLLoaded = TRUE;\r
183         return TRUE;\r
184 }\r
185 \r
186 // OpenSSLを解放\r
187 void FreeOpenSSL()\r
188 {\r
189         int i;\r
190         if(!g_bOpenSSLLoaded)\r
191                 return;\r
192         EnterCriticalSection(&g_OpenSSLLock);\r
193         for(i = 0; i < MAX_SSL_SOCKET; i++)\r
194         {\r
195                 if(g_pOpenSSLHandle[i])\r
196                 {\r
197                         p_SSL_shutdown(g_pOpenSSLHandle[i]);\r
198                         p_SSL_free(g_pOpenSSLHandle[i]);\r
199                         g_pOpenSSLHandle[i] = NULL;\r
200                 }\r
201         }\r
202         if(g_pOpenSSLCTX)\r
203                 p_SSL_CTX_free(g_pOpenSSLCTX);\r
204         g_pOpenSSLCTX = NULL;\r
205         FreeLibrary(g_hOpenSSL);\r
206         g_hOpenSSL = NULL;\r
207         FreeLibrary(g_hOpenSSLCommon);\r
208         g_hOpenSSLCommon = NULL;\r
209         LeaveCriticalSection(&g_OpenSSLLock);\r
210         DeleteCriticalSection(&g_OpenSSLLock);\r
211         g_bOpenSSLLoaded = FALSE;\r
212 }\r
213 \r
214 // OpenSSLが使用可能かどうか確認\r
215 BOOL IsOpenSSLLoaded()\r
216 {\r
217         return g_bOpenSSLLoaded;\r
218 }\r
219 \r
220 SSL** GetUnusedSSLPointer()\r
221 {\r
222         int i;\r
223         for(i = 0; i < MAX_SSL_SOCKET; i++)\r
224         {\r
225                 if(!g_pOpenSSLHandle[i])\r
226                         return &g_pOpenSSLHandle[i];\r
227         }\r
228         return NULL;\r
229 }\r
230 \r
231 SSL** FindSSLPointerFromSocket(SOCKET s)\r
232 {\r
233         int i;\r
234         for(i = 0; i < MAX_SSL_SOCKET; i++)\r
235         {\r
236                 if(g_pOpenSSLHandle[i])\r
237                 {\r
238                         if(p_SSL_get_fd(g_pOpenSSLHandle[i]) == s)\r
239                                 return &g_pOpenSSLHandle[i];\r
240                 }\r
241         }\r
242         return NULL;\r
243 }\r
244 \r
245 BOOL ConfirmSSLCertificate(SSL* pSSL, BOOL* pbAborted)\r
246 {\r
247         BOOL bResult;\r
248         BOOL bVerified;\r
249         char* pData;\r
250         char* pSubject;\r
251         X509* pX509;\r
252         BIO* pBIO;\r
253         long Length;\r
254         char* pBuffer;\r
255         char* pCN;\r
256         char* p;\r
257         bResult = FALSE;\r
258         bVerified = FALSE;\r
259         pData = NULL;\r
260         pSubject = NULL;\r
261         if(pX509 = p_SSL_get_peer_certificate(pSSL))\r
262         {\r
263                 if(pBIO = p_BIO_new(p_BIO_s_mem()))\r
264                 {\r
265                         p_X509_print_ex(pBIO, pX509, 0, XN_FLAG_RFC2253);\r
266                         if((Length = p_BIO_ctrl(pBIO, BIO_CTRL_INFO, 0, &pBuffer)) > 0)\r
267                         {\r
268                                 if(pData = (char*)malloc(Length + sizeof(char)))\r
269                                 {\r
270                                         memcpy(pData, pBuffer, Length);\r
271                                         *(char*)((size_t)pData + Length) = '\0';\r
272                                 }\r
273                         }\r
274                         p_BIO_free(pBIO);\r
275                 }\r
276                 if(pBIO = p_BIO_new(p_BIO_s_mem()))\r
277                 {\r
278                         p_X509_NAME_print_ex(pBIO, p_X509_get_subject_name(pX509), 0, XN_FLAG_RFC2253);\r
279                         if((Length = p_BIO_ctrl(pBIO, BIO_CTRL_INFO, 0, &pBuffer)) > 0)\r
280                         {\r
281                                 if(pSubject = (char*)malloc(Length + sizeof(char)))\r
282                                 {\r
283                                         memcpy(pSubject, pBuffer, Length);\r
284                                         *(char*)((size_t)pSubject + Length) = '\0';\r
285                                 }\r
286                         }\r
287                         p_BIO_free(pBIO);\r
288                 }\r
289                 p_X509_free(pX509);\r
290         }\r
291         if(pX509 && p_SSL_get_verify_result(pSSL) == X509_V_OK)\r
292                 bVerified = TRUE;\r
293         pCN = pSubject;\r
294         while(pCN)\r
295         {\r
296                 if(strncmp(pCN, "CN=", strlen("CN=")) == 0)\r
297                 {\r
298                         pCN += strlen("CN=");\r
299                         if(p = strchr(pCN, ','))\r
300                                 *p = '\0';\r
301                         break;\r
302                 }\r
303                 if(pCN = strchr(pCN, ','))\r
304                         pCN++;\r
305         }\r
306         bResult = g_pOpenSSLConfirmCallback(pbAborted, bVerified, pData, pCN);\r
307         if(pData)\r
308                 free(pData);\r
309         if(pSubject)\r
310                 free(pSubject);\r
311         return bResult;\r
312 }\r
313 \r
314 void SetSSLTimeoutCallback(DWORD Timeout, LPSSLTIMEOUTCALLBACK pCallback)\r
315 {\r
316         if(!g_bOpenSSLLoaded)\r
317                 return;\r
318         EnterCriticalSection(&g_OpenSSLLock);\r
319         g_OpenSSLTimeout = Timeout;\r
320         g_pOpenSSLTimeoutCallback = pCallback;\r
321         LeaveCriticalSection(&g_OpenSSLLock);\r
322 }\r
323 \r
324 void SetSSLConfirmCallback(LPSSLCONFIRMCALLBACK pCallback)\r
325 {\r
326         if(!g_bOpenSSLLoaded)\r
327                 return;\r
328         EnterCriticalSection(&g_OpenSSLLock);\r
329         g_pOpenSSLConfirmCallback = pCallback;\r
330         LeaveCriticalSection(&g_OpenSSLLock);\r
331 }\r
332 \r
333 // SSLルート証明書を設定\r
334 // PEM形式のみ指定可能\r
335 BOOL SetSSLRootCertificate(const void* pData, DWORD Length)\r
336 {\r
337         BOOL r;\r
338         X509_STORE* pStore;\r
339         BYTE* p;\r
340         BYTE* pBegin;\r
341         BYTE* pEnd;\r
342         BIO* pBIO;\r
343         X509* pX509;\r
344         if(!g_bOpenSSLLoaded)\r
345                 return FALSE;\r
346         r = FALSE;\r
347         EnterCriticalSection(&g_OpenSSLLock);\r
348         if(!g_pOpenSSLCTX)\r
349                 g_pOpenSSLCTX = p_SSL_CTX_new(p_SSLv23_method());\r
350         if(g_pOpenSSLCTX)\r
351         {\r
352                 if(pStore = p_SSL_CTX_get_cert_store(g_pOpenSSLCTX))\r
353                 {\r
354                         p = (BYTE*)pData;\r
355                         pBegin = NULL;\r
356                         pEnd = NULL;\r
357                         while(Length > 0)\r
358                         {\r
359                                 if(!pBegin)\r
360                                 {\r
361                                         if(Length < 27)\r
362                                                 break;\r
363                                         if(memcmp(p, "-----BEGIN CERTIFICATE-----", 27) == 0)\r
364                                                 pBegin = p;\r
365                                 }\r
366                                 else if(!pEnd)\r
367                                 {\r
368                                         if(Length < 25)\r
369                                                 break;\r
370                                         if(memcmp(p, "-----END CERTIFICATE-----", 25) == 0)\r
371                                                 pEnd = p + 25;\r
372                                 }\r
373                                 if(pBegin && pEnd)\r
374                                 {\r
375                                         if(pBIO = p_BIO_new_mem_buf(pBegin, (int)((size_t)pEnd - (size_t)pBegin)))\r
376                                         {\r
377                                                 if(pX509 = p_PEM_read_bio_X509(pBIO, NULL, NULL, NULL))\r
378                                                 {\r
379                                                         if(p_X509_STORE_add_cert(pStore, pX509) == 1)\r
380                                                                 r = TRUE;\r
381                                                         p_X509_free(pX509);\r
382                                                 }\r
383                                                 p_BIO_free(pBIO);\r
384                                         }\r
385                                         pBegin = NULL;\r
386                                         pEnd = NULL;\r
387                                 }\r
388                                 p++;\r
389                                 Length--;\r
390                         }\r
391                 }\r
392         }\r
393         LeaveCriticalSection(&g_OpenSSLLock);\r
394         return r;\r
395 }\r
396 \r
397 // ワイルドカードの比較\r
398 // 主にSSL証明書のCN確認用\r
399 BOOL IsHostNameMatched(LPCSTR HostName, LPCSTR CommonName)\r
400 {\r
401         BOOL bResult;\r
402         const char* pAsterisk;\r
403         size_t BeforeAsterisk;\r
404         const char* pBeginAsterisk;\r
405         const char* pEndAsterisk;\r
406         const char* pDot;\r
407         bResult = FALSE;\r
408         if(HostName && CommonName)\r
409         {\r
410                 if(pAsterisk = strchr(CommonName, '*'))\r
411                 {\r
412                         BeforeAsterisk = ((size_t)pAsterisk - (size_t)CommonName) / sizeof(char);\r
413                         pBeginAsterisk = HostName + BeforeAsterisk;\r
414                         while(*pAsterisk == '*')\r
415                         {\r
416                                 pAsterisk++;\r
417                         }\r
418                         pEndAsterisk = HostName + strlen(HostName) - strlen(pAsterisk);\r
419                         // "*"より前は大文字小文字を無視して完全一致\r
420                         if(_strnicmp(HostName, CommonName, BeforeAsterisk) == 0)\r
421                         {\r
422                                 // "*"より後は大文字小文字を無視して完全一致\r
423                                 if(_stricmp(pEndAsterisk, pAsterisk) == 0)\r
424                                 {\r
425                                         // "*"と一致する範囲に"."が含まれてはならない\r
426                                         pDot = strchr(pBeginAsterisk, '.');\r
427                                         if(!pDot || pDot >= pEndAsterisk)\r
428                                                 bResult = TRUE;\r
429                                 }\r
430                         }\r
431                 }\r
432                 else if(_stricmp(HostName, CommonName) == 0)\r
433                         bResult = TRUE;\r
434         }\r
435         return bResult;\r
436 }\r
437 \r
438 // SSLセッションを開始\r
439 BOOL AttachSSL(SOCKET s, SOCKET parent, BOOL* pbAborted)\r
440 {\r
441         BOOL r;\r
442         DWORD Time;\r
443         SSL** ppSSL;\r
444         SSL** ppSSLParent;\r
445         SSL_SESSION* pSession;\r
446         int Return;\r
447         int Error;\r
448         if(!g_bOpenSSLLoaded)\r
449                 return FALSE;\r
450         r = FALSE;\r
451         Time = timeGetTime();\r
452         EnterCriticalSection(&g_OpenSSLLock);\r
453         if(!g_pOpenSSLCTX)\r
454                 g_pOpenSSLCTX = p_SSL_CTX_new(p_SSLv23_method());\r
455         if(g_pOpenSSLCTX)\r
456         {\r
457                 if(ppSSL = GetUnusedSSLPointer())\r
458                 {\r
459                         if(*ppSSL = p_SSL_new(g_pOpenSSLCTX))\r
460                         {\r
461                                 if(p_SSL_set_fd(*ppSSL, s) != 0)\r
462                                 {\r
463                                         if(parent != INVALID_SOCKET)\r
464                                         {\r
465                                                 if(ppSSLParent = FindSSLPointerFromSocket(parent))\r
466                                                 {\r
467                                                         if(pSession = p_SSL_get_session(*ppSSLParent))\r
468                                                         {\r
469                                                                 if(p_SSL_set_session(*ppSSL, pSession) == 1)\r
470                                                                 {\r
471                                                                 }\r
472                                                         }\r
473                                                 }\r
474                                         }\r
475                                         // SSLのネゴシエーションには時間がかかる場合がある\r
476                                         r = TRUE;\r
477                                         while(r)\r
478                                         {\r
479                                                 Return = p_SSL_connect(*ppSSL);\r
480                                                 if(Return == 1)\r
481                                                         break;\r
482                                                 Error = p_SSL_get_error(*ppSSL, Return);\r
483                                                 if(Error == SSL_ERROR_WANT_READ || Error == SSL_ERROR_WANT_WRITE)\r
484                                                 {\r
485                                                         LeaveCriticalSection(&g_OpenSSLLock);\r
486                                                         if(g_pOpenSSLTimeoutCallback(pbAborted) || (g_OpenSSLTimeout > 0 && timeGetTime() - Time >= g_OpenSSLTimeout))\r
487                                                                 r = FALSE;\r
488                                                         EnterCriticalSection(&g_OpenSSLLock);\r
489                                                 }\r
490                                                 else\r
491                                                         r = FALSE;\r
492                                         }\r
493                                         if(r)\r
494                                         {\r
495                                                 if(ConfirmSSLCertificate(*ppSSL, pbAborted))\r
496                                                 {\r
497                                                 }\r
498                                                 else\r
499                                                 {\r
500                                                         LeaveCriticalSection(&g_OpenSSLLock);\r
501                                                         DetachSSL(s);\r
502                                                         r = FALSE;\r
503                                                         EnterCriticalSection(&g_OpenSSLLock);\r
504                                                 }\r
505                                         }\r
506                                         else\r
507                                         {\r
508                                                 LeaveCriticalSection(&g_OpenSSLLock);\r
509                                                 DetachSSL(s);\r
510                                                 EnterCriticalSection(&g_OpenSSLLock);\r
511                                         }\r
512                                 }\r
513                                 else\r
514                                 {\r
515                                         LeaveCriticalSection(&g_OpenSSLLock);\r
516                                         DetachSSL(s);\r
517                                         EnterCriticalSection(&g_OpenSSLLock);\r
518                                 }\r
519                         }\r
520                 }\r
521         }\r
522         LeaveCriticalSection(&g_OpenSSLLock);\r
523         return r;\r
524 }\r
525 \r
526 // SSLセッションを終了\r
527 BOOL DetachSSL(SOCKET s)\r
528 {\r
529         BOOL r;\r
530         SSL** ppSSL;\r
531         if(!g_bOpenSSLLoaded)\r
532                 return FALSE;\r
533         r = FALSE;\r
534         EnterCriticalSection(&g_OpenSSLLock);\r
535         if(ppSSL = FindSSLPointerFromSocket(s))\r
536         {\r
537                 p_SSL_shutdown(*ppSSL);\r
538                 p_SSL_free(*ppSSL);\r
539                 *ppSSL = NULL;\r
540                 r = TRUE;\r
541         }\r
542         LeaveCriticalSection(&g_OpenSSLLock);\r
543         return r;\r
544 }\r
545 \r
546 // SSLとしてマークされているか確認\r
547 // マークされていればTRUEを返す\r
548 BOOL IsSSLAttached(SOCKET s)\r
549 {\r
550         SSL** ppSSL;\r
551         if(!g_bOpenSSLLoaded)\r
552                 return FALSE;\r
553         EnterCriticalSection(&g_OpenSSLLock);\r
554         ppSSL = FindSSLPointerFromSocket(s);\r
555         LeaveCriticalSection(&g_OpenSSLLock);\r
556         if(!ppSSL)\r
557                 return FALSE;\r
558         return TRUE;\r
559 }\r
560 \r
561 SOCKET FTPS_socket(int af, int type, int protocol)\r
562 {\r
563         return socket(af, type, protocol);\r
564 }\r
565 \r
566 int FTPS_bind(SOCKET s, const struct sockaddr *addr, int namelen)\r
567 {\r
568         return bind(s, addr, namelen);\r
569 }\r
570 \r
571 int FTPS_listen(SOCKET s, int backlog)\r
572 {\r
573         return listen(s, backlog);\r
574 }\r
575 \r
576 // accept相当の関数\r
577 // ただし初めからSSLのネゴシエーションを行う\r
578 SOCKET FTPS_accept(SOCKET s, struct sockaddr *addr, int *addrlen)\r
579 {\r
580         SOCKET r;\r
581         BOOL bAborted;\r
582         r = accept(s, addr, addrlen);\r
583         bAborted = FALSE;\r
584         if(!AttachSSL(r, INVALID_SOCKET, &bAborted))\r
585         {\r
586                 closesocket(r);\r
587                 return INVALID_SOCKET;\r
588         }\r
589         return r;\r
590 }\r
591 \r
592 // connect相当の関数\r
593 // ただし初めからSSLのネゴシエーションを行う\r
594 int FTPS_connect(SOCKET s, const struct sockaddr *name, int namelen)\r
595 {\r
596         int r;\r
597         BOOL bAborted;\r
598         r = connect(s, name, namelen);\r
599         bAborted = FALSE;\r
600         if(!AttachSSL(r, INVALID_SOCKET, &bAborted))\r
601                 return SOCKET_ERROR;\r
602         return r;\r
603 }\r
604 \r
605 // closesocket相当の関数\r
606 int FTPS_closesocket(SOCKET s)\r
607 {\r
608         DetachSSL(s);\r
609         return closesocket(s);\r
610 }\r
611 \r
612 // send相当の関数\r
613 int FTPS_send(SOCKET s, const char * buf, int len, int flags)\r
614 {\r
615         SSL** ppSSL;\r
616         if(!g_bOpenSSLLoaded)\r
617                 return send(s, buf, len, flags);\r
618         EnterCriticalSection(&g_OpenSSLLock);\r
619         ppSSL = FindSSLPointerFromSocket(s);\r
620         LeaveCriticalSection(&g_OpenSSLLock);\r
621         if(!ppSSL)\r
622                 return send(s, buf, len, flags);\r
623         return p_SSL_write(*ppSSL, buf, len);\r
624 }\r
625 \r
626 // recv相当の関数\r
627 int FTPS_recv(SOCKET s, char * buf, int len, int flags)\r
628 {\r
629         SSL** ppSSL;\r
630         if(!g_bOpenSSLLoaded)\r
631                 return recv(s, buf, len, flags);\r
632         EnterCriticalSection(&g_OpenSSLLock);\r
633         ppSSL = FindSSLPointerFromSocket(s);\r
634         LeaveCriticalSection(&g_OpenSSLLock);\r
635         if(!ppSSL)\r
636                 return recv(s, buf, len, flags);\r
637         if(flags & MSG_PEEK)\r
638                 return p_SSL_peek(*ppSSL, buf, len);\r
639         return p_SSL_read(*ppSSL, buf, len);\r
640 }\r
641 \r
642 // IPv6対応\r
643 \r
644 typedef struct\r
645 {\r
646         HANDLE h;\r
647         HWND hWnd;\r
648         u_int wMsg;\r
649         char * name;\r
650         char * buf;\r
651         int buflen;\r
652         short Family;\r
653 } GETHOSTBYNAMEDATA;\r
654 \r
655 DWORD WINAPI WSAAsyncGetHostByNameIPv6ThreadProc(LPVOID lpParameter)\r
656 {\r
657         GETHOSTBYNAMEDATA* pData;\r
658         struct hostent* pHost;\r
659         struct addrinfo* pAddr;\r
660         struct addrinfo* p;\r
661         pHost = NULL;\r
662         pData = (GETHOSTBYNAMEDATA*)lpParameter;\r
663         if(getaddrinfo(pData->name, NULL, NULL, &pAddr) == 0)\r
664         {\r
665                 p = pAddr;\r
666                 while(p)\r
667                 {\r
668                         if(p->ai_family == pData->Family)\r
669                         {\r
670                                 switch(p->ai_family)\r
671                                 {\r
672                                 case AF_INET:\r
673                                         pHost = (struct hostent*)pData->buf;\r
674                                         if((size_t)pData->buflen >= sizeof(struct hostent) + sizeof(char*) * 2 + sizeof(struct in_addr)\r
675                                                 && p->ai_addrlen >= sizeof(struct sockaddr_in))\r
676                                         {\r
677                                                 pHost->h_name = NULL;\r
678                                                 pHost->h_aliases = NULL;\r
679                                                 pHost->h_addrtype = p->ai_family;\r
680                                                 pHost->h_length = sizeof(struct in_addr);\r
681                                                 pHost->h_addr_list = (char**)(&pHost[1]);\r
682                                                 pHost->h_addr_list[0] = (char*)(&pHost->h_addr_list[2]);\r
683                                                 pHost->h_addr_list[1] = NULL;\r
684                                                 memcpy(pHost->h_addr_list[0], &((struct sockaddr_in*)p->ai_addr)->sin_addr, sizeof(struct in_addr));\r
685                                                 PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(sizeof(struct hostent) + sizeof(char*) * 2 + p->ai_addrlen));\r
686                                         }\r
687                                         else\r
688                                                 PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(WSAENOBUFS << 16));\r
689                                         break;\r
690                                 case AF_INET6:\r
691                                         pHost = (struct hostent*)pData->buf;\r
692                                         if((size_t)pData->buflen >= sizeof(struct hostent) + sizeof(char*) * 2 + sizeof(struct in6_addr)\r
693                                                 && p->ai_addrlen >= sizeof(struct sockaddr_in6))\r
694                                         {\r
695                                                 pHost->h_name = NULL;\r
696                                                 pHost->h_aliases = NULL;\r
697                                                 pHost->h_addrtype = p->ai_family;\r
698                                                 pHost->h_length = sizeof(struct in6_addr);\r
699                                                 pHost->h_addr_list = (char**)(&pHost[1]);\r
700                                                 pHost->h_addr_list[0] = (char*)(&pHost->h_addr_list[2]);\r
701                                                 pHost->h_addr_list[1] = NULL;\r
702                                                 memcpy(pHost->h_addr_list[0], &((struct sockaddr_in6*)p->ai_addr)->sin6_addr, sizeof(struct in6_addr));\r
703                                                 PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(sizeof(struct hostent) + sizeof(char*) * 2 + p->ai_addrlen));\r
704                                         }\r
705                                         else\r
706                                                 PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(WSAENOBUFS << 16));\r
707                                         break;\r
708                                 }\r
709                         }\r
710                         if(pHost)\r
711                                 break;\r
712                         p = p->ai_next;\r
713                 }\r
714                 if(!p)\r
715                         PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(ERROR_INVALID_FUNCTION << 16));\r
716                 freeaddrinfo(pAddr);\r
717         }\r
718         else\r
719                 PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(ERROR_INVALID_FUNCTION << 16));\r
720         free(pData->name);\r
721         free(pData);\r
722         // CreateThreadが返すハンドルが重複するのを回避\r
723         Sleep(10000);\r
724         return 0;\r
725 }\r
726 \r
727 // IPv6対応のWSAAsyncGetHostByName相当の関数\r
728 // FamilyにはAF_INETまたはAF_INET6を指定可能\r
729 // ただしANSI用\r
730 HANDLE WSAAsyncGetHostByNameIPv6(HWND hWnd, u_int wMsg, const char * name, char * buf, int buflen, short Family)\r
731 {\r
732         HANDLE hResult;\r
733         GETHOSTBYNAMEDATA* pData;\r
734         hResult = NULL;\r
735         if(pData = malloc(sizeof(GETHOSTBYNAMEDATA)))\r
736         {\r
737                 pData->hWnd = hWnd;\r
738                 pData->wMsg = wMsg;\r
739                 if(pData->name = malloc(sizeof(char) * (strlen(name) + 1)))\r
740                 {\r
741                         strcpy(pData->name, name);\r
742                         pData->buf = buf;\r
743                         pData->buflen = buflen;\r
744                         pData->Family = Family;\r
745                         if(pData->h = CreateThread(NULL, 0, WSAAsyncGetHostByNameIPv6ThreadProc, pData, CREATE_SUSPENDED, NULL))\r
746                         {\r
747                                 ResumeThread(pData->h);\r
748                                 hResult = pData->h;\r
749                         }\r
750                 }\r
751         }\r
752         if(!hResult)\r
753         {\r
754                 if(pData)\r
755                 {\r
756                         if(pData->name)\r
757                                 free(pData->name);\r
758                         free(pData);\r
759                 }\r
760         }\r
761         return hResult;\r
762 }\r
763 \r
764 // WSAAsyncGetHostByNameIPv6用のWSACancelAsyncRequest相当の関数\r
765 int WSACancelAsyncRequestIPv6(HANDLE hAsyncTaskHandle)\r
766 {\r
767         int Result;\r
768         Result = SOCKET_ERROR;\r
769         if(TerminateThread(hAsyncTaskHandle, 0))\r
770                 Result = 0;\r
771         return Result;\r
772 }\r
773 \r
774 char* AddressToStringIPv6(char* str, void* in6)\r
775 {\r
776         char* pResult;\r
777         unsigned char* p;\r
778         int MaxZero;\r
779         int MaxZeroLen;\r
780         int i;\r
781         int j;\r
782         char Tmp[5];\r
783         pResult = str;\r
784         p = (unsigned char*)in6;\r
785         MaxZero = 8;\r
786         MaxZeroLen = 1;\r
787         for(i = 0; i < 8; i++)\r
788         {\r
789                 for(j = i; j < 8; j++)\r
790                 {\r
791                         if(p[j * 2] != 0 || p[j * 2 + 1] != 0)\r
792                                 break;\r
793                 }\r
794                 if(j - i > MaxZeroLen)\r
795                 {\r
796                         MaxZero = i;\r
797                         MaxZeroLen = j - i;\r
798                 }\r
799         }\r
800         strcpy(str, "");\r
801         for(i = 0; i < 8; i++)\r
802         {\r
803                 if(i == MaxZero)\r
804                 {\r
805                         if(i == 0)\r
806                                 strcat(str, ":");\r
807                         strcat(str, ":");\r
808                 }\r
809                 else if(i < MaxZero || i >= MaxZero + MaxZeroLen)\r
810                 {\r
811                         sprintf(Tmp, "%x", (((int)p[i * 2] & 0xff) << 8) | ((int)p[i * 2 + 1] & 0xff));\r
812                         strcat(str, Tmp);\r
813                         if(i < 7)\r
814                                 strcat(str, ":");\r
815                 }\r
816         }\r
817         return pResult;\r
818 }\r
819 \r
820 // IPv6対応のinet_ntoa相当の関数\r
821 // ただしANSI用\r
822 char* inet6_ntoa(struct in6_addr in6)\r
823 {\r
824         char* pResult;\r
825         static char Adrs[40];\r
826         pResult = NULL;\r
827         memset(Adrs, 0, sizeof(Adrs));\r
828         pResult = AddressToStringIPv6(Adrs, &in6);\r
829         return pResult;\r
830 }\r
831 \r
832 // IPv6対応のinet_addr相当の関数\r
833 // ただしANSI用\r
834 struct in6_addr inet6_addr(const char* cp)\r
835 {\r
836         struct in6_addr Result;\r
837         int AfterZero;\r
838         int i;\r
839         char* p;\r
840         memset(&Result, 0, sizeof(Result));\r
841         AfterZero = 0;\r
842         for(i = 0; i < 8; i++)\r
843         {\r
844                 if(!cp)\r
845                 {\r
846                         memset(&Result, 0xff, sizeof(Result));\r
847                         break;\r
848                 }\r
849                 if(i >= AfterZero)\r
850                 {\r
851                         if(strncmp(cp, ":", 1) == 0)\r
852                         {\r
853                                 cp = cp + 1;\r
854                                 if(i == 0 && strncmp(cp, ":", 1) == 0)\r
855                                         cp = cp + 1;\r
856                                 p = (char*)cp;\r
857                                 AfterZero = 7;\r
858                                 while(p = strstr(p, ":"))\r
859                                 {\r
860                                         p = p + 1;\r
861                                         AfterZero--;\r
862                                 }\r
863                         }\r
864                         else\r
865                         {\r
866                                 Result.u.Word[i] = (USHORT)strtol(cp, &p, 16);\r
867                                 Result.u.Word[i] = ((Result.u.Word[i] & 0xff00) >> 8) | ((Result.u.Word[i] & 0x00ff) << 8);\r
868                                 if(strncmp(p, ":", 1) != 0 && strlen(p) > 0)\r
869                                 {\r
870                                         memset(&Result, 0xff, sizeof(Result));\r
871                                         break;\r
872                                 }\r
873                                 if(cp = strstr(cp, ":"))\r
874                                         cp = cp + 1;\r
875                         }\r
876                 }\r
877         }\r
878         return Result;\r
879 }\r
880 \r
881 BOOL ConvertDomainNameToPunycode(LPSTR Output, DWORD Count, LPCSTR Input)\r
882 {\r
883         BOOL bResult;\r
884         punycode_uint* pUnicode;\r
885         punycode_uint* p;\r
886         BOOL bNeeded;\r
887         LPCSTR InputString;\r
888         punycode_uint Length;\r
889         punycode_uint OutputLength;\r
890         bResult = FALSE;\r
891         if(pUnicode = malloc(sizeof(punycode_uint) * strlen(Input)))\r
892         {\r
893                 p = pUnicode;\r
894                 bNeeded = FALSE;\r
895                 InputString = Input;\r
896                 Length = 0;\r
897                 while(*InputString != '\0')\r
898                 {\r
899                         *p = (punycode_uint)GetNextCharM(InputString, &InputString);\r
900                         if(*p >= 0x80)\r
901                                 bNeeded = TRUE;\r
902                         p++;\r
903                         Length++;\r
904                 }\r
905                 if(bNeeded)\r
906                 {\r
907                         if(Count >= strlen("xn--") + 1)\r
908                         {\r
909                                 strcpy(Output, "xn--");\r
910                                 OutputLength = Count - strlen("xn--");\r
911                                 if(punycode_encode(Length, pUnicode, NULL, (punycode_uint*)&OutputLength, Output + strlen("xn--")) == punycode_success)\r
912                                 {\r
913                                         Output[strlen("xn--") + OutputLength] = '\0';\r
914                                         bResult = TRUE;\r
915                                 }\r
916                         }\r
917                 }\r
918                 free(pUnicode);\r
919         }\r
920         if(!bResult)\r
921         {\r
922                 if(Count >= strlen(Input) + 1)\r
923                 {\r
924                         strcpy(Output, Input);\r
925                         bResult = TRUE;\r
926                 }\r
927         }\r
928         return bResult;\r
929 }\r
930 \r
931 BOOL ConvertNameToPunycode(LPSTR Output, LPCSTR Input)\r
932 {\r
933         BOOL bResult;\r
934         DWORD Length;\r
935         char* pm0;\r
936         char* pm1;\r
937         char* p;\r
938         char* pNext;\r
939         bResult = FALSE;\r
940         Length = strlen(Input);\r
941         if(pm0 = AllocateStringM(Length + 1))\r
942         {\r
943                 if(pm1 = AllocateStringM(Length * 4 + 1))\r
944                 {\r
945                         strcpy(pm0, Input);\r
946                         p = pm0;\r
947                         while(p)\r
948                         {\r
949                                 if(pNext = strchr(p, '.'))\r
950                                 {\r
951                                         *pNext = '\0';\r
952                                         pNext++;\r
953                                 }\r
954                                 if(ConvertDomainNameToPunycode(pm1, Length * 4, p))\r
955                                         strcat(Output, pm1);\r
956                                 if(pNext)\r
957                                         strcat(Output, ".");\r
958                                 p = pNext;\r
959                         }\r
960                         bResult = TRUE;\r
961                         FreeDuplicatedString(pm1);\r
962                 }\r
963                 FreeDuplicatedString(pm0);\r
964         }\r
965         return bResult;\r
966 }\r
967 \r
968 HANDLE WSAAsyncGetHostByNameM(HWND hWnd, u_int wMsg, const char * name, char * buf, int buflen)\r
969 {\r
970         HANDLE r = NULL;\r
971         char* pa0 = NULL;\r
972         if(pa0 = AllocateStringA(strlen(name) * 4))\r
973         {\r
974                 if(ConvertNameToPunycode(pa0, name))\r
975                         r = WSAAsyncGetHostByName(hWnd, wMsg, pa0, buf, buflen);\r
976         }\r
977         FreeDuplicatedString(pa0);\r
978         return r;\r
979 }\r
980 \r
981 HANDLE WSAAsyncGetHostByNameIPv6M(HWND hWnd, u_int wMsg, const char * name, char * buf, int buflen, short Family)\r
982 {\r
983         HANDLE r = NULL;\r
984         char* pa0 = NULL;\r
985         if(pa0 = AllocateStringA(strlen(name) * 4))\r
986         {\r
987                 if(ConvertNameToPunycode(pa0, name))\r
988                         r = WSAAsyncGetHostByNameIPv6(hWnd, wMsg, pa0, buf, buflen, Family);\r
989         }\r
990         FreeDuplicatedString(pa0);\r
991         return r;\r
992 }\r
993 \r
994 // SFTP対応\r
995 \r
996 typedef void* (__cdecl* _SFTP_Create)();\r
997 typedef void (__cdecl* _SFTP_Destroy)(void*);\r
998 typedef BOOL (__cdecl* _SFTP_IsExited)(void*);\r
999 typedef BOOL (__cdecl* _SFTP_SetTimeoutCallback)(void*, void*);\r
1000 typedef size_t (__cdecl* _SFTP_PeekStdOut)(void*, void*, size_t);\r
1001 typedef size_t (__cdecl* _SFTP_ReadStdOut)(void*, void*, size_t);\r
1002 typedef size_t (__cdecl* _SFTP_WriteStdIn)(void*, const void*, size_t);\r
1003 typedef size_t (__cdecl* _SFTP_PeekDataOut)(void*, void*, size_t);\r
1004 typedef size_t (__cdecl* _SFTP_ReadDataOut)(void*, void*, size_t);\r
1005 typedef size_t (__cdecl* _SFTP_WriteDataIn)(void*, const void*, size_t);\r
1006 typedef BOOL (__cdecl* _SFTP_SetFilePosition)(void*, LONGLONG);\r
1007 \r
1008 _SFTP_Create p_SFTP_Create;\r
1009 _SFTP_Destroy p_SFTP_Destroy;\r
1010 _SFTP_IsExited p_SFTP_IsExited;\r
1011 _SFTP_SetTimeoutCallback p_SFTP_SetTimeoutCallback;\r
1012 _SFTP_PeekStdOut p_SFTP_PeekStdOut;\r
1013 _SFTP_ReadStdOut p_SFTP_ReadStdOut;\r
1014 _SFTP_WriteStdIn p_SFTP_WriteStdIn;\r
1015 _SFTP_PeekDataOut p_SFTP_PeekDataOut;\r
1016 _SFTP_ReadDataOut p_SFTP_ReadDataOut;\r
1017 _SFTP_WriteDataIn p_SFTP_WriteDataIn;\r
1018 _SFTP_SetFilePosition p_SFTP_SetFilePosition;\r
1019 \r
1020 typedef struct\r
1021 {\r
1022         SOCKET Control;\r
1023         SOCKET Data;\r
1024         void* Handle;\r
1025         char Host[1024];\r
1026         int Port;\r
1027         char User[1024];\r
1028         char Password[1024];\r
1029 } SFTPDATA;\r
1030 \r
1031 #define MAX_SFTP_SOCKET 16\r
1032 \r
1033 BOOL g_bPuTTYLoaded;\r
1034 HMODULE g_hPuTTY;\r
1035 CRITICAL_SECTION g_PuTTYLock;\r
1036 SFTPDATA g_SFTPData[MAX_SFTP_SOCKET];\r
1037 \r
1038 // PuTTYを初期化\r
1039 BOOL LoadPuTTY()\r
1040 {\r
1041         int i;\r
1042         if(g_bPuTTYLoaded)\r
1043                 return FALSE;\r
1044 #ifdef ENABLE_PROCESS_PROTECTION\r
1045         // ビルドしたputty.dllに合わせてSHA1ハッシュ値を変更すること\r
1046         RegisterTrustedModuleSHA1Hash("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00");\r
1047 #endif\r
1048 //      g_hPuTTY = LoadLibrary("putty.dll");\r
1049         g_hPuTTY = LoadLibrary("C:\\SourceForge\\ffftp\\putty\\Debug\\PuTTY.dll");\r
1050         if(!g_hPuTTY\r
1051                 || !(p_SFTP_Create = (_SFTP_Create)GetProcAddress(g_hPuTTY, "SFTP_Create"))\r
1052                 || !(p_SFTP_Destroy = (_SFTP_Destroy)GetProcAddress(g_hPuTTY, "SFTP_Destroy"))\r
1053                 || !(p_SFTP_IsExited = (_SFTP_IsExited)GetProcAddress(g_hPuTTY, "SFTP_IsExited"))\r
1054                 || !(p_SFTP_SetTimeoutCallback = (_SFTP_SetTimeoutCallback)GetProcAddress(g_hPuTTY, "SFTP_SetTimeoutCallback"))\r
1055                 || !(p_SFTP_PeekStdOut = (_SFTP_PeekStdOut)GetProcAddress(g_hPuTTY, "SFTP_PeekStdOut"))\r
1056                 || !(p_SFTP_ReadStdOut = (_SFTP_ReadStdOut)GetProcAddress(g_hPuTTY, "SFTP_ReadStdOut"))\r
1057                 || !(p_SFTP_WriteStdIn = (_SFTP_WriteStdIn)GetProcAddress(g_hPuTTY, "SFTP_WriteStdIn"))\r
1058                 || !(p_SFTP_PeekDataOut = (_SFTP_PeekDataOut)GetProcAddress(g_hPuTTY, "SFTP_PeekDataOut"))\r
1059                 || !(p_SFTP_ReadDataOut = (_SFTP_ReadDataOut)GetProcAddress(g_hPuTTY, "SFTP_ReadDataOut"))\r
1060                 || !(p_SFTP_WriteDataIn = (_SFTP_WriteDataIn)GetProcAddress(g_hPuTTY, "SFTP_WriteDataIn"))\r
1061                 || !(p_SFTP_SetFilePosition = (_SFTP_SetFilePosition)GetProcAddress(g_hPuTTY, "SFTP_SetFilePosition")))\r
1062         {\r
1063                 if(g_hPuTTY)\r
1064                         FreeLibrary(g_hPuTTY);\r
1065                 g_hPuTTY = NULL;\r
1066                 return FALSE;\r
1067         }\r
1068         for(i = 0; i < MAX_SFTP_SOCKET; i++)\r
1069         {\r
1070                 g_SFTPData[i].Control = INVALID_SOCKET;\r
1071                 g_SFTPData[i].Data = INVALID_SOCKET;\r
1072         }\r
1073         InitializeCriticalSection(&g_PuTTYLock);\r
1074         g_bPuTTYLoaded = TRUE;\r
1075         return TRUE;\r
1076 }\r
1077 \r
1078 // PuTTYを解放\r
1079 void FreePuTTY()\r
1080 {\r
1081         int i;\r
1082         if(!g_bPuTTYLoaded)\r
1083                 return;\r
1084         EnterCriticalSection(&g_PuTTYLock);\r
1085         for(i = 0; i < MAX_SFTP_SOCKET; i++)\r
1086         {\r
1087                 if(g_SFTPData[i].Control != INVALID_SOCKET)\r
1088                 {\r
1089                         closesocket(g_SFTPData[i].Control);\r
1090                         g_SFTPData[i].Control = INVALID_SOCKET;\r
1091                         p_SFTP_Destroy(g_SFTPData[i].Handle);\r
1092                 }\r
1093                 if(g_SFTPData[i].Data != INVALID_SOCKET)\r
1094                 {\r
1095                         closesocket(g_SFTPData[i].Data);\r
1096                         g_SFTPData[i].Data = INVALID_SOCKET;\r
1097                 }\r
1098         }\r
1099         FreeLibrary(g_hPuTTY);\r
1100         g_hPuTTY = NULL;\r
1101         LeaveCriticalSection(&g_PuTTYLock);\r
1102         DeleteCriticalSection(&g_PuTTYLock);\r
1103         g_bPuTTYLoaded = FALSE;\r
1104 }\r
1105 \r
1106 // PuTTYが使用可能かどうか確認\r
1107 BOOL IsPuTTYLoaded()\r
1108 {\r
1109         return g_bPuTTYLoaded;\r
1110 }\r
1111 \r
1112 SFTPDATA* GetUnusedSFTPData()\r
1113 {\r
1114         int i;\r
1115         for(i = 0; i < MAX_SFTP_SOCKET; i++)\r
1116         {\r
1117                 if(g_SFTPData[i].Control == INVALID_SOCKET)\r
1118                 {\r
1119                         memset(&g_SFTPData[i], 0, sizeof(SFTPDATA));\r
1120                         return &g_SFTPData[i];\r
1121                 }\r
1122         }\r
1123         return NULL;\r
1124 }\r
1125 \r
1126 SFTPDATA* FindSFTPDataFromSocket(SOCKET s)\r
1127 {\r
1128         int i;\r
1129         for(i = 0; i < MAX_SFTP_SOCKET; i++)\r
1130         {\r
1131                 if(g_SFTPData[i].Control == s || g_SFTPData[i].Data == s)\r
1132                         return &g_SFTPData[i];\r
1133         }\r
1134         return NULL;\r
1135 }\r
1136 \r
1137 // SFTPとしてマークされているか確認\r
1138 // マークされていればTRUEを返す\r
1139 BOOL IsSFTPAttached(SOCKET s)\r
1140 {\r
1141         SFTPDATA* pSFTPData;\r
1142         if(!g_bPuTTYLoaded)\r
1143                 return FALSE;\r
1144         EnterCriticalSection(&g_PuTTYLock);\r
1145         pSFTPData = FindSFTPDataFromSocket(s);\r
1146         LeaveCriticalSection(&g_PuTTYLock);\r
1147         if(!pSFTPData)\r
1148                 return FALSE;\r
1149         return TRUE;\r
1150 }\r
1151 \r
1152 // コントロール用の仮想的なソケットを取得\r
1153 // 識別子としてダミーのソケットを返す\r
1154 SOCKET SFTP_socket(int af, int type, int protocol)\r
1155 {\r
1156         SOCKET r;\r
1157         SFTPDATA* pSFTPData;\r
1158         if(!g_bPuTTYLoaded)\r
1159                 return INVALID_SOCKET;\r
1160         r = INVALID_SOCKET;\r
1161         EnterCriticalSection(&g_PuTTYLock);\r
1162         if(pSFTPData = GetUnusedSFTPData())\r
1163         {\r
1164                 r = socket(af, type, protocol);\r
1165                 pSFTPData->Control = r;\r
1166                 pSFTPData->Data = INVALID_SOCKET;\r
1167                 pSFTPData->Handle = p_SFTP_Create();\r
1168         }\r
1169         LeaveCriticalSection(&g_PuTTYLock);\r
1170         return r;\r
1171 }\r
1172 \r
1173 int SFTP_bind(SOCKET s, const struct sockaddr *addr, int namelen)\r
1174 {\r
1175         return SOCKET_ERROR;\r
1176 }\r
1177 \r
1178 int SFTP_listen(SOCKET s, int backlog)\r
1179 {\r
1180         return SOCKET_ERROR;\r
1181 }\r
1182 \r
1183 // accept相当の関数\r
1184 SOCKET SFTP_accept(SOCKET s, struct sockaddr *addr, int *addrlen)\r
1185 {\r
1186         return INVALID_SOCKET;\r
1187 }\r
1188 \r
1189 // connect相当の関数\r
1190 int SFTP_connect(SOCKET s, const struct sockaddr *name, int namelen)\r
1191 {\r
1192         SFTPDATA* pSFTPData;\r
1193         if(!g_bPuTTYLoaded)\r
1194                 return SOCKET_ERROR;\r
1195         EnterCriticalSection(&g_PuTTYLock);\r
1196         pSFTPData = FindSFTPDataFromSocket(s);\r
1197         LeaveCriticalSection(&g_PuTTYLock);\r
1198         if(!pSFTPData)\r
1199                 return SOCKET_ERROR;\r
1200         if(namelen == sizeof(struct sockaddr_in))\r
1201         {\r
1202         }\r
1203         else if(namelen == sizeof(struct sockaddr_in6))\r
1204         {\r
1205         }\r
1206         else\r
1207                 return SOCKET_ERROR;\r
1208         return 0;\r
1209 }\r
1210 \r
1211 // closesocket相当の関数\r
1212 int SFTP_closesocket(SOCKET s)\r
1213 {\r
1214         SFTPDATA* pSFTPData;\r
1215         if(!g_bPuTTYLoaded)\r
1216                 return SOCKET_ERROR;\r
1217         EnterCriticalSection(&g_PuTTYLock);\r
1218         if(pSFTPData = FindSFTPDataFromSocket(s))\r
1219         {\r
1220                 if(pSFTPData->Control == s)\r
1221                 {\r
1222                         pSFTPData->Control = INVALID_SOCKET;\r
1223                         p_SFTP_Destroy(pSFTPData->Handle);\r
1224                 }\r
1225                 if(pSFTPData->Data == s)\r
1226                         pSFTPData->Data = INVALID_SOCKET;\r
1227         }\r
1228         LeaveCriticalSection(&g_PuTTYLock);\r
1229         return closesocket(s);\r
1230 }\r
1231 \r
1232 // send相当の関数\r
1233 int SFTP_send(SOCKET s, const char * buf, int len, int flags)\r
1234 {\r
1235         int r;\r
1236         SFTPDATA* pSFTPData;\r
1237         if(!g_bPuTTYLoaded)\r
1238                 return SOCKET_ERROR;\r
1239         EnterCriticalSection(&g_PuTTYLock);\r
1240         pSFTPData = FindSFTPDataFromSocket(s);\r
1241         LeaveCriticalSection(&g_PuTTYLock);\r
1242         if(!pSFTPData)\r
1243                 return SOCKET_ERROR;\r
1244         if(p_SFTP_IsExited(pSFTPData->Handle))\r
1245                 return SOCKET_ERROR;\r
1246         r = SOCKET_ERROR;\r
1247         if(pSFTPData->Control == s)\r
1248                 r = (int)p_SFTP_WriteStdIn(pSFTPData->Handle, buf, len);\r
1249         else if(pSFTPData->Data == s)\r
1250                 r = (int)p_SFTP_WriteDataIn(pSFTPData->Handle, buf, len);\r
1251         return r;\r
1252 }\r
1253 \r
1254 // recv相当の関数\r
1255 int SFTP_recv(SOCKET s, char * buf, int len, int flags)\r
1256 {\r
1257         int r;\r
1258         SFTPDATA* pSFTPData;\r
1259         if(!g_bPuTTYLoaded)\r
1260                 return SOCKET_ERROR;\r
1261         EnterCriticalSection(&g_PuTTYLock);\r
1262         pSFTPData = FindSFTPDataFromSocket(s);\r
1263         LeaveCriticalSection(&g_PuTTYLock);\r
1264         if(!pSFTPData)\r
1265                 return SOCKET_ERROR;\r
1266         if(p_SFTP_IsExited(pSFTPData->Handle))\r
1267                 return SOCKET_ERROR;\r
1268         r = SOCKET_ERROR;\r
1269         if(pSFTPData->Control == s)\r
1270         {\r
1271                 if(flags & MSG_PEEK)\r
1272                         r = (int)p_SFTP_PeekStdOut(pSFTPData->Handle, buf, len);\r
1273                 else\r
1274                         r = (int)p_SFTP_ReadStdOut(pSFTPData->Handle, buf, len);\r
1275         }\r
1276         else if(pSFTPData->Data == s)\r
1277         {\r
1278                 if(flags & MSG_PEEK)\r
1279                         r = (int)p_SFTP_PeekDataOut(pSFTPData->Handle, buf, len);\r
1280                 else\r
1281                         r = (int)p_SFTP_ReadDataOut(pSFTPData->Handle, buf, len);\r
1282         }\r
1283         return r;\r
1284 }\r
1285 \r
1286 BOOL SFTP_SetTimeoutCallback(SOCKET s, void* pCallback)\r
1287 {\r
1288         SFTPDATA* pSFTPData;\r
1289         if(!g_bPuTTYLoaded)\r
1290                 return FALSE;\r
1291         EnterCriticalSection(&g_PuTTYLock);\r
1292         pSFTPData = FindSFTPDataFromSocket(s);\r
1293         LeaveCriticalSection(&g_PuTTYLock);\r
1294         if(!pSFTPData)\r
1295                 return FALSE;\r
1296         return p_SFTP_SetTimeoutCallback(pSFTPData->Handle, pCallback);\r
1297 }\r
1298 \r
1299 // データ用の仮想的なソケットを取得\r
1300 // 識別子としてダミーのソケットを返す\r
1301 SOCKET SFTP_GetDataHandle(SOCKET s, int af, int type, int protocol)\r
1302 {\r
1303         SOCKET r;\r
1304         SFTPDATA* pSFTPData;\r
1305         if(!g_bPuTTYLoaded)\r
1306                 return INVALID_SOCKET;\r
1307         r = INVALID_SOCKET;\r
1308         EnterCriticalSection(&g_PuTTYLock);\r
1309         if(pSFTPData = FindSFTPDataFromSocket(s))\r
1310         {\r
1311                 r = socket(af, type, protocol);\r
1312                 pSFTPData->Data = r;\r
1313         }\r
1314         LeaveCriticalSection(&g_PuTTYLock);\r
1315         return r;\r
1316 }\r
1317 \r
1318 BOOL SFTP_SetFilePosition(SOCKET s, LONGLONG Position)\r
1319 {\r
1320         SFTPDATA* pSFTPData;\r
1321         if(!g_bPuTTYLoaded)\r
1322                 return FALSE;\r
1323         EnterCriticalSection(&g_PuTTYLock);\r
1324         pSFTPData = FindSFTPDataFromSocket(s);\r
1325         LeaveCriticalSection(&g_PuTTYLock);\r
1326         if(!pSFTPData)\r
1327                 return FALSE;\r
1328         return p_SFTP_SetFilePosition(pSFTPData->Handle, Position);\r
1329 }\r
1330 \r