OSDN Git Service

Add support for retaining time stamps on uploading files.
[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.0g\r
118         // libssl32.dll 1.0.0g\r
119         RegisterTrustedModuleSHA1Hash("\x42\x32\x3E\x44\x35\xBC\x98\x6C\x45\xC9\xA2\xB8\x41\xE7\xDA\x7B\x6A\x98\xB2\x28");\r
120         // libeay32.dll 1.0.0g\r
121         RegisterTrustedModuleSHA1Hash("\x3F\xC8\x07\x84\xB3\xF0\x71\x4A\x18\x59\x52\x1F\x99\x09\x65\xB9\x49\xA7\x15\x36");\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 const struct in6_addr IN6ADDR_NONE = {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};\r
645 \r
646 typedef struct\r
647 {\r
648         HANDLE h;\r
649         HWND hWnd;\r
650         u_int wMsg;\r
651         char * name;\r
652         char * buf;\r
653         int buflen;\r
654         short Family;\r
655 } GETHOSTBYNAMEDATA;\r
656 \r
657 DWORD WINAPI WSAAsyncGetHostByNameIPv6ThreadProc(LPVOID lpParameter)\r
658 {\r
659         GETHOSTBYNAMEDATA* pData;\r
660         struct hostent* pHost;\r
661         struct addrinfo* pAddr;\r
662         struct addrinfo* p;\r
663         pHost = NULL;\r
664         pData = (GETHOSTBYNAMEDATA*)lpParameter;\r
665         if(getaddrinfo(pData->name, NULL, NULL, &pAddr) == 0)\r
666         {\r
667                 p = pAddr;\r
668                 while(p)\r
669                 {\r
670                         if(p->ai_family == pData->Family)\r
671                         {\r
672                                 switch(p->ai_family)\r
673                                 {\r
674                                 case AF_INET:\r
675                                         pHost = (struct hostent*)pData->buf;\r
676                                         if((size_t)pData->buflen >= sizeof(struct hostent) + sizeof(char*) * 2 + sizeof(struct in_addr)\r
677                                                 && p->ai_addrlen >= sizeof(struct sockaddr_in))\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 in_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_in*)p->ai_addr)->sin_addr, sizeof(struct in_addr));\r
687                                                 PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(sizeof(struct hostent) + sizeof(char*) * 2 + sizeof(struct in_addr)));\r
688                                         }\r
689                                         else\r
690                                                 PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(WSAENOBUFS << 16));\r
691                                         break;\r
692                                 case AF_INET6:\r
693                                         pHost = (struct hostent*)pData->buf;\r
694                                         if((size_t)pData->buflen >= sizeof(struct hostent) + sizeof(char*) * 2 + sizeof(struct in6_addr)\r
695                                                 && p->ai_addrlen >= sizeof(struct sockaddr_in6))\r
696                                         {\r
697                                                 pHost->h_name = NULL;\r
698                                                 pHost->h_aliases = NULL;\r
699                                                 pHost->h_addrtype = p->ai_family;\r
700                                                 pHost->h_length = sizeof(struct in6_addr);\r
701                                                 pHost->h_addr_list = (char**)(&pHost[1]);\r
702                                                 pHost->h_addr_list[0] = (char*)(&pHost->h_addr_list[2]);\r
703                                                 pHost->h_addr_list[1] = NULL;\r
704                                                 memcpy(pHost->h_addr_list[0], &((struct sockaddr_in6*)p->ai_addr)->sin6_addr, sizeof(struct in6_addr));\r
705                                                 PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(sizeof(struct hostent) + sizeof(char*) * 2 + sizeof(struct in6_addr)));\r
706                                         }\r
707                                         else\r
708                                                 PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(WSAENOBUFS << 16));\r
709                                         break;\r
710                                 }\r
711                         }\r
712                         if(pHost)\r
713                                 break;\r
714                         p = p->ai_next;\r
715                 }\r
716                 if(!p)\r
717                         PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(ERROR_INVALID_FUNCTION << 16));\r
718                 freeaddrinfo(pAddr);\r
719         }\r
720         else\r
721                 PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(ERROR_INVALID_FUNCTION << 16));\r
722         // CreateThreadが返すハンドルが重複するのを回避\r
723         Sleep(10000);\r
724         CloseHandle(pData->h);\r
725         free(pData->name);\r
726         free(pData);\r
727         return 0;\r
728 }\r
729 \r
730 // IPv6対応のWSAAsyncGetHostByName相当の関数\r
731 // FamilyにはAF_INETまたはAF_INET6を指定可能\r
732 // ただしANSI用\r
733 HANDLE WSAAsyncGetHostByNameIPv6(HWND hWnd, u_int wMsg, const char * name, char * buf, int buflen, short Family)\r
734 {\r
735         HANDLE hResult;\r
736         GETHOSTBYNAMEDATA* pData;\r
737         hResult = NULL;\r
738         if(pData = malloc(sizeof(GETHOSTBYNAMEDATA)))\r
739         {\r
740                 pData->hWnd = hWnd;\r
741                 pData->wMsg = wMsg;\r
742                 if(pData->name = malloc(sizeof(char) * (strlen(name) + 1)))\r
743                 {\r
744                         strcpy(pData->name, name);\r
745                         pData->buf = buf;\r
746                         pData->buflen = buflen;\r
747                         pData->Family = Family;\r
748                         if(pData->h = CreateThread(NULL, 0, WSAAsyncGetHostByNameIPv6ThreadProc, pData, CREATE_SUSPENDED, NULL))\r
749                         {\r
750                                 ResumeThread(pData->h);\r
751                                 hResult = pData->h;\r
752                         }\r
753                 }\r
754         }\r
755         if(!hResult)\r
756         {\r
757                 if(pData)\r
758                 {\r
759                         if(pData->name)\r
760                                 free(pData->name);\r
761                         free(pData);\r
762                 }\r
763         }\r
764         return hResult;\r
765 }\r
766 \r
767 // WSAAsyncGetHostByNameIPv6用のWSACancelAsyncRequest相当の関数\r
768 int WSACancelAsyncRequestIPv6(HANDLE hAsyncTaskHandle)\r
769 {\r
770         int Result;\r
771         Result = SOCKET_ERROR;\r
772         if(TerminateThread(hAsyncTaskHandle, 0))\r
773         {\r
774                 CloseHandle(hAsyncTaskHandle);\r
775                 Result = 0;\r
776         }\r
777         return Result;\r
778 }\r
779 \r
780 char* AddressToStringIPv6(char* str, void* in6)\r
781 {\r
782         char* pResult;\r
783         unsigned char* p;\r
784         int MaxZero;\r
785         int MaxZeroLen;\r
786         int i;\r
787         int j;\r
788         char Tmp[5];\r
789         pResult = str;\r
790         p = (unsigned char*)in6;\r
791         MaxZero = 8;\r
792         MaxZeroLen = 1;\r
793         for(i = 0; i < 8; i++)\r
794         {\r
795                 for(j = i; j < 8; j++)\r
796                 {\r
797                         if(p[j * 2] != 0 || p[j * 2 + 1] != 0)\r
798                                 break;\r
799                 }\r
800                 if(j - i > MaxZeroLen)\r
801                 {\r
802                         MaxZero = i;\r
803                         MaxZeroLen = j - i;\r
804                 }\r
805         }\r
806         strcpy(str, "");\r
807         for(i = 0; i < 8; i++)\r
808         {\r
809                 if(i == MaxZero)\r
810                 {\r
811                         if(i == 0)\r
812                                 strcat(str, ":");\r
813                         strcat(str, ":");\r
814                 }\r
815                 else if(i < MaxZero || i >= MaxZero + MaxZeroLen)\r
816                 {\r
817                         sprintf(Tmp, "%x", (((int)p[i * 2] & 0xff) << 8) | ((int)p[i * 2 + 1] & 0xff));\r
818                         strcat(str, Tmp);\r
819                         if(i < 7)\r
820                                 strcat(str, ":");\r
821                 }\r
822         }\r
823         return pResult;\r
824 }\r
825 \r
826 // IPv6対応のinet_ntoa相当の関数\r
827 // ただしANSI用\r
828 char* inet6_ntoa(struct in6_addr in6)\r
829 {\r
830         char* pResult;\r
831         static char Adrs[40];\r
832         pResult = NULL;\r
833         memset(Adrs, 0, sizeof(Adrs));\r
834         pResult = AddressToStringIPv6(Adrs, &in6);\r
835         return pResult;\r
836 }\r
837 \r
838 // IPv6対応のinet_addr相当の関数\r
839 // ただしANSI用\r
840 struct in6_addr inet6_addr(const char* cp)\r
841 {\r
842         struct in6_addr Result;\r
843         int AfterZero;\r
844         int i;\r
845         char* p;\r
846         memset(&Result, 0, sizeof(Result));\r
847         AfterZero = 0;\r
848         for(i = 0; i < 8; i++)\r
849         {\r
850                 if(!cp)\r
851                 {\r
852                         memcpy(&Result, &IN6ADDR_NONE, sizeof(struct in6_addr));\r
853                         break;\r
854                 }\r
855                 if(i >= AfterZero)\r
856                 {\r
857                         if(strncmp(cp, ":", 1) == 0)\r
858                         {\r
859                                 cp = cp + 1;\r
860                                 if(i == 0 && strncmp(cp, ":", 1) == 0)\r
861                                         cp = cp + 1;\r
862                                 p = (char*)cp;\r
863                                 AfterZero = 7;\r
864                                 while(p = strstr(p, ":"))\r
865                                 {\r
866                                         p = p + 1;\r
867                                         AfterZero--;\r
868                                 }\r
869                         }\r
870                         else\r
871                         {\r
872                                 Result.u.Word[i] = (USHORT)strtol(cp, &p, 16);\r
873                                 Result.u.Word[i] = ((Result.u.Word[i] & 0xff00) >> 8) | ((Result.u.Word[i] & 0x00ff) << 8);\r
874                                 if(strncmp(p, ":", 1) != 0 && strlen(p) > 0)\r
875                                 {\r
876                                         memcpy(&Result, &IN6ADDR_NONE, sizeof(struct in6_addr));\r
877                                         break;\r
878                                 }\r
879                                 if(cp = strstr(cp, ":"))\r
880                                         cp = cp + 1;\r
881                         }\r
882                 }\r
883         }\r
884         return Result;\r
885 }\r
886 \r
887 BOOL ConvertDomainNameToPunycode(LPSTR Output, DWORD Count, LPCSTR Input)\r
888 {\r
889         BOOL bResult;\r
890         punycode_uint* pUnicode;\r
891         punycode_uint* p;\r
892         BOOL bNeeded;\r
893         LPCSTR InputString;\r
894         punycode_uint Length;\r
895         punycode_uint OutputLength;\r
896         bResult = FALSE;\r
897         if(pUnicode = malloc(sizeof(punycode_uint) * strlen(Input)))\r
898         {\r
899                 p = pUnicode;\r
900                 bNeeded = FALSE;\r
901                 InputString = Input;\r
902                 Length = 0;\r
903                 while(*InputString != '\0')\r
904                 {\r
905                         *p = (punycode_uint)GetNextCharM(InputString, &InputString);\r
906                         if(*p >= 0x80)\r
907                                 bNeeded = TRUE;\r
908                         p++;\r
909                         Length++;\r
910                 }\r
911                 if(bNeeded)\r
912                 {\r
913                         if(Count >= strlen("xn--") + 1)\r
914                         {\r
915                                 strcpy(Output, "xn--");\r
916                                 OutputLength = Count - strlen("xn--");\r
917                                 if(punycode_encode(Length, pUnicode, NULL, (punycode_uint*)&OutputLength, Output + strlen("xn--")) == punycode_success)\r
918                                 {\r
919                                         Output[strlen("xn--") + OutputLength] = '\0';\r
920                                         bResult = TRUE;\r
921                                 }\r
922                         }\r
923                 }\r
924                 free(pUnicode);\r
925         }\r
926         if(!bResult)\r
927         {\r
928                 if(Count >= strlen(Input) + 1)\r
929                 {\r
930                         strcpy(Output, Input);\r
931                         bResult = TRUE;\r
932                 }\r
933         }\r
934         return bResult;\r
935 }\r
936 \r
937 BOOL ConvertNameToPunycode(LPSTR Output, LPCSTR Input)\r
938 {\r
939         BOOL bResult;\r
940         DWORD Length;\r
941         char* pm0;\r
942         char* pm1;\r
943         char* p;\r
944         char* pNext;\r
945         bResult = FALSE;\r
946         Length = strlen(Input);\r
947         if(pm0 = AllocateStringM(Length + 1))\r
948         {\r
949                 if(pm1 = AllocateStringM(Length * 4 + 1))\r
950                 {\r
951                         strcpy(pm0, Input);\r
952                         p = pm0;\r
953                         while(p)\r
954                         {\r
955                                 if(pNext = strchr(p, '.'))\r
956                                 {\r
957                                         *pNext = '\0';\r
958                                         pNext++;\r
959                                 }\r
960                                 if(ConvertDomainNameToPunycode(pm1, Length * 4, p))\r
961                                         strcat(Output, pm1);\r
962                                 if(pNext)\r
963                                         strcat(Output, ".");\r
964                                 p = pNext;\r
965                         }\r
966                         bResult = TRUE;\r
967                         FreeDuplicatedString(pm1);\r
968                 }\r
969                 FreeDuplicatedString(pm0);\r
970         }\r
971         return bResult;\r
972 }\r
973 \r
974 HANDLE WSAAsyncGetHostByNameM(HWND hWnd, u_int wMsg, const char * name, char * buf, int buflen)\r
975 {\r
976         HANDLE r = NULL;\r
977         char* pa0 = NULL;\r
978         if(pa0 = AllocateStringA(strlen(name) * 4))\r
979         {\r
980                 if(ConvertNameToPunycode(pa0, name))\r
981                         r = WSAAsyncGetHostByName(hWnd, wMsg, pa0, buf, buflen);\r
982         }\r
983         FreeDuplicatedString(pa0);\r
984         return r;\r
985 }\r
986 \r
987 HANDLE WSAAsyncGetHostByNameIPv6M(HWND hWnd, u_int wMsg, const char * name, char * buf, int buflen, short Family)\r
988 {\r
989         HANDLE r = NULL;\r
990         char* pa0 = NULL;\r
991         if(pa0 = AllocateStringA(strlen(name) * 4))\r
992         {\r
993                 if(ConvertNameToPunycode(pa0, name))\r
994                         r = WSAAsyncGetHostByNameIPv6(hWnd, wMsg, pa0, buf, buflen, Family);\r
995         }\r
996         FreeDuplicatedString(pa0);\r
997         return r;\r
998 }\r
999 \r
1000 // SFTP対応\r
1001 \r
1002 typedef void* (__cdecl* _SFTP_Create)();\r
1003 typedef void (__cdecl* _SFTP_Destroy)(void*);\r
1004 typedef BOOL (__cdecl* _SFTP_IsExited)(void*);\r
1005 typedef BOOL (__cdecl* _SFTP_SetTimeoutCallback)(void*, void*);\r
1006 typedef size_t (__cdecl* _SFTP_PeekStdOut)(void*, void*, size_t);\r
1007 typedef size_t (__cdecl* _SFTP_ReadStdOut)(void*, void*, size_t);\r
1008 typedef size_t (__cdecl* _SFTP_WriteStdIn)(void*, const void*, size_t);\r
1009 typedef size_t (__cdecl* _SFTP_PeekDataOut)(void*, void*, size_t);\r
1010 typedef size_t (__cdecl* _SFTP_ReadDataOut)(void*, void*, size_t);\r
1011 typedef size_t (__cdecl* _SFTP_WriteDataIn)(void*, const void*, size_t);\r
1012 typedef BOOL (__cdecl* _SFTP_SetFilePosition)(void*, LONGLONG);\r
1013 \r
1014 _SFTP_Create p_SFTP_Create;\r
1015 _SFTP_Destroy p_SFTP_Destroy;\r
1016 _SFTP_IsExited p_SFTP_IsExited;\r
1017 _SFTP_SetTimeoutCallback p_SFTP_SetTimeoutCallback;\r
1018 _SFTP_PeekStdOut p_SFTP_PeekStdOut;\r
1019 _SFTP_ReadStdOut p_SFTP_ReadStdOut;\r
1020 _SFTP_WriteStdIn p_SFTP_WriteStdIn;\r
1021 _SFTP_PeekDataOut p_SFTP_PeekDataOut;\r
1022 _SFTP_ReadDataOut p_SFTP_ReadDataOut;\r
1023 _SFTP_WriteDataIn p_SFTP_WriteDataIn;\r
1024 _SFTP_SetFilePosition p_SFTP_SetFilePosition;\r
1025 \r
1026 typedef struct\r
1027 {\r
1028         SOCKET Control;\r
1029         SOCKET Data;\r
1030         void* Handle;\r
1031         char Host[1024];\r
1032         int Port;\r
1033         char User[1024];\r
1034         char Password[1024];\r
1035 } SFTPDATA;\r
1036 \r
1037 #define MAX_SFTP_SOCKET 16\r
1038 \r
1039 BOOL g_bPuTTYLoaded;\r
1040 HMODULE g_hPuTTY;\r
1041 CRITICAL_SECTION g_PuTTYLock;\r
1042 SFTPDATA g_SFTPData[MAX_SFTP_SOCKET];\r
1043 \r
1044 // PuTTYを初期化\r
1045 BOOL LoadPuTTY()\r
1046 {\r
1047         int i;\r
1048         if(g_bPuTTYLoaded)\r
1049                 return FALSE;\r
1050 #ifdef ENABLE_PROCESS_PROTECTION\r
1051         // ビルドしたputty.dllに合わせてSHA1ハッシュ値を変更すること\r
1052         RegisterTrustedModuleSHA1Hash("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00");\r
1053 #endif\r
1054         // デバッグ用\r
1055 #ifdef _DEBUG\r
1056         {\r
1057                 char Path[MAX_PATH];\r
1058                 GetModuleFileName(NULL, Path, MAX_PATH);\r
1059                 strcpy(strrchr(Path, '\\'), "\\..\\putty\\Debug\\PuTTY.dll");\r
1060                 g_hPuTTY = LoadLibrary(Path);\r
1061         }\r
1062 #else\r
1063         g_hPuTTY = LoadLibrary("putty.dll");\r
1064 #endif\r
1065         if(!g_hPuTTY\r
1066                 || !(p_SFTP_Create = (_SFTP_Create)GetProcAddress(g_hPuTTY, "SFTP_Create"))\r
1067                 || !(p_SFTP_Destroy = (_SFTP_Destroy)GetProcAddress(g_hPuTTY, "SFTP_Destroy"))\r
1068                 || !(p_SFTP_IsExited = (_SFTP_IsExited)GetProcAddress(g_hPuTTY, "SFTP_IsExited"))\r
1069                 || !(p_SFTP_SetTimeoutCallback = (_SFTP_SetTimeoutCallback)GetProcAddress(g_hPuTTY, "SFTP_SetTimeoutCallback"))\r
1070                 || !(p_SFTP_PeekStdOut = (_SFTP_PeekStdOut)GetProcAddress(g_hPuTTY, "SFTP_PeekStdOut"))\r
1071                 || !(p_SFTP_ReadStdOut = (_SFTP_ReadStdOut)GetProcAddress(g_hPuTTY, "SFTP_ReadStdOut"))\r
1072                 || !(p_SFTP_WriteStdIn = (_SFTP_WriteStdIn)GetProcAddress(g_hPuTTY, "SFTP_WriteStdIn"))\r
1073                 || !(p_SFTP_PeekDataOut = (_SFTP_PeekDataOut)GetProcAddress(g_hPuTTY, "SFTP_PeekDataOut"))\r
1074                 || !(p_SFTP_ReadDataOut = (_SFTP_ReadDataOut)GetProcAddress(g_hPuTTY, "SFTP_ReadDataOut"))\r
1075                 || !(p_SFTP_WriteDataIn = (_SFTP_WriteDataIn)GetProcAddress(g_hPuTTY, "SFTP_WriteDataIn"))\r
1076                 || !(p_SFTP_SetFilePosition = (_SFTP_SetFilePosition)GetProcAddress(g_hPuTTY, "SFTP_SetFilePosition")))\r
1077         {\r
1078                 if(g_hPuTTY)\r
1079                         FreeLibrary(g_hPuTTY);\r
1080                 g_hPuTTY = NULL;\r
1081                 return FALSE;\r
1082         }\r
1083         for(i = 0; i < MAX_SFTP_SOCKET; i++)\r
1084         {\r
1085                 g_SFTPData[i].Control = INVALID_SOCKET;\r
1086                 g_SFTPData[i].Data = INVALID_SOCKET;\r
1087         }\r
1088         InitializeCriticalSection(&g_PuTTYLock);\r
1089         g_bPuTTYLoaded = TRUE;\r
1090         return TRUE;\r
1091 }\r
1092 \r
1093 // PuTTYを解放\r
1094 void FreePuTTY()\r
1095 {\r
1096         int i;\r
1097         if(!g_bPuTTYLoaded)\r
1098                 return;\r
1099         EnterCriticalSection(&g_PuTTYLock);\r
1100         for(i = 0; i < MAX_SFTP_SOCKET; i++)\r
1101         {\r
1102                 if(g_SFTPData[i].Control != INVALID_SOCKET)\r
1103                 {\r
1104                         closesocket(g_SFTPData[i].Control);\r
1105                         g_SFTPData[i].Control = INVALID_SOCKET;\r
1106                         p_SFTP_Destroy(g_SFTPData[i].Handle);\r
1107                 }\r
1108                 if(g_SFTPData[i].Data != INVALID_SOCKET)\r
1109                 {\r
1110                         closesocket(g_SFTPData[i].Data);\r
1111                         g_SFTPData[i].Data = INVALID_SOCKET;\r
1112                 }\r
1113         }\r
1114         FreeLibrary(g_hPuTTY);\r
1115         g_hPuTTY = NULL;\r
1116         LeaveCriticalSection(&g_PuTTYLock);\r
1117         DeleteCriticalSection(&g_PuTTYLock);\r
1118         g_bPuTTYLoaded = FALSE;\r
1119 }\r
1120 \r
1121 // PuTTYが使用可能かどうか確認\r
1122 BOOL IsPuTTYLoaded()\r
1123 {\r
1124         return g_bPuTTYLoaded;\r
1125 }\r
1126 \r
1127 SFTPDATA* GetUnusedSFTPData()\r
1128 {\r
1129         int i;\r
1130         for(i = 0; i < MAX_SFTP_SOCKET; i++)\r
1131         {\r
1132                 if(g_SFTPData[i].Control == INVALID_SOCKET)\r
1133                 {\r
1134                         memset(&g_SFTPData[i], 0, sizeof(SFTPDATA));\r
1135                         return &g_SFTPData[i];\r
1136                 }\r
1137         }\r
1138         return NULL;\r
1139 }\r
1140 \r
1141 SFTPDATA* FindSFTPDataFromSocket(SOCKET s)\r
1142 {\r
1143         int i;\r
1144         for(i = 0; i < MAX_SFTP_SOCKET; i++)\r
1145         {\r
1146                 if(g_SFTPData[i].Control == s || g_SFTPData[i].Data == s)\r
1147                         return &g_SFTPData[i];\r
1148         }\r
1149         return NULL;\r
1150 }\r
1151 \r
1152 // SFTPとしてマークされているか確認\r
1153 // マークされていればTRUEを返す\r
1154 BOOL IsSFTPAttached(SOCKET s)\r
1155 {\r
1156         SFTPDATA* pSFTPData;\r
1157         if(!g_bPuTTYLoaded)\r
1158                 return FALSE;\r
1159         EnterCriticalSection(&g_PuTTYLock);\r
1160         pSFTPData = FindSFTPDataFromSocket(s);\r
1161         LeaveCriticalSection(&g_PuTTYLock);\r
1162         if(!pSFTPData)\r
1163                 return FALSE;\r
1164         return TRUE;\r
1165 }\r
1166 \r
1167 // コントロール用の仮想的なソケットを取得\r
1168 // 識別子としてダミーのソケットを返す\r
1169 SOCKET SFTP_socket(int af, int type, int protocol)\r
1170 {\r
1171         SOCKET r;\r
1172         SFTPDATA* pSFTPData;\r
1173         if(!g_bPuTTYLoaded)\r
1174                 return INVALID_SOCKET;\r
1175         r = INVALID_SOCKET;\r
1176         EnterCriticalSection(&g_PuTTYLock);\r
1177         if(pSFTPData = GetUnusedSFTPData())\r
1178         {\r
1179                 r = socket(af, type, protocol);\r
1180                 pSFTPData->Control = r;\r
1181                 pSFTPData->Data = INVALID_SOCKET;\r
1182                 pSFTPData->Handle = p_SFTP_Create();\r
1183         }\r
1184         LeaveCriticalSection(&g_PuTTYLock);\r
1185         return r;\r
1186 }\r
1187 \r
1188 int SFTP_bind(SOCKET s, const struct sockaddr *addr, int namelen)\r
1189 {\r
1190         return SOCKET_ERROR;\r
1191 }\r
1192 \r
1193 int SFTP_listen(SOCKET s, int backlog)\r
1194 {\r
1195         return SOCKET_ERROR;\r
1196 }\r
1197 \r
1198 // accept相当の関数\r
1199 SOCKET SFTP_accept(SOCKET s, struct sockaddr *addr, int *addrlen)\r
1200 {\r
1201         return INVALID_SOCKET;\r
1202 }\r
1203 \r
1204 // connect相当の関数\r
1205 int SFTP_connect(SOCKET s, const struct sockaddr *name, int namelen)\r
1206 {\r
1207         SFTPDATA* pSFTPData;\r
1208         if(!g_bPuTTYLoaded)\r
1209                 return SOCKET_ERROR;\r
1210         EnterCriticalSection(&g_PuTTYLock);\r
1211         pSFTPData = FindSFTPDataFromSocket(s);\r
1212         LeaveCriticalSection(&g_PuTTYLock);\r
1213         if(!pSFTPData)\r
1214                 return SOCKET_ERROR;\r
1215         if(namelen == sizeof(struct sockaddr_in))\r
1216         {\r
1217         }\r
1218         else if(namelen == sizeof(struct sockaddr_in6))\r
1219         {\r
1220         }\r
1221         else\r
1222                 return SOCKET_ERROR;\r
1223         return 0;\r
1224 }\r
1225 \r
1226 // closesocket相当の関数\r
1227 int SFTP_closesocket(SOCKET s)\r
1228 {\r
1229         SFTPDATA* pSFTPData;\r
1230         if(!g_bPuTTYLoaded)\r
1231                 return SOCKET_ERROR;\r
1232         EnterCriticalSection(&g_PuTTYLock);\r
1233         if(pSFTPData = FindSFTPDataFromSocket(s))\r
1234         {\r
1235                 if(pSFTPData->Control == s)\r
1236                 {\r
1237                         pSFTPData->Control = INVALID_SOCKET;\r
1238                         p_SFTP_Destroy(pSFTPData->Handle);\r
1239                 }\r
1240                 if(pSFTPData->Data == s)\r
1241                         pSFTPData->Data = INVALID_SOCKET;\r
1242         }\r
1243         LeaveCriticalSection(&g_PuTTYLock);\r
1244         return closesocket(s);\r
1245 }\r
1246 \r
1247 // send相当の関数\r
1248 int SFTP_send(SOCKET s, const char * buf, int len, int flags)\r
1249 {\r
1250         int r;\r
1251         SFTPDATA* pSFTPData;\r
1252         if(!g_bPuTTYLoaded)\r
1253                 return SOCKET_ERROR;\r
1254         EnterCriticalSection(&g_PuTTYLock);\r
1255         pSFTPData = FindSFTPDataFromSocket(s);\r
1256         LeaveCriticalSection(&g_PuTTYLock);\r
1257         if(!pSFTPData)\r
1258                 return SOCKET_ERROR;\r
1259         if(p_SFTP_IsExited(pSFTPData->Handle))\r
1260                 return SOCKET_ERROR;\r
1261         r = SOCKET_ERROR;\r
1262         if(pSFTPData->Control == s)\r
1263                 r = (int)p_SFTP_WriteStdIn(pSFTPData->Handle, buf, len);\r
1264         else if(pSFTPData->Data == s)\r
1265                 r = (int)p_SFTP_WriteDataIn(pSFTPData->Handle, buf, len);\r
1266         return r;\r
1267 }\r
1268 \r
1269 // recv相当の関数\r
1270 int SFTP_recv(SOCKET s, char * buf, int len, int flags)\r
1271 {\r
1272         int r;\r
1273         SFTPDATA* pSFTPData;\r
1274         if(!g_bPuTTYLoaded)\r
1275                 return SOCKET_ERROR;\r
1276         EnterCriticalSection(&g_PuTTYLock);\r
1277         pSFTPData = FindSFTPDataFromSocket(s);\r
1278         LeaveCriticalSection(&g_PuTTYLock);\r
1279         if(!pSFTPData)\r
1280                 return SOCKET_ERROR;\r
1281         if(p_SFTP_IsExited(pSFTPData->Handle))\r
1282                 return SOCKET_ERROR;\r
1283         r = SOCKET_ERROR;\r
1284         if(pSFTPData->Control == s)\r
1285         {\r
1286                 if(flags & MSG_PEEK)\r
1287                         r = (int)p_SFTP_PeekStdOut(pSFTPData->Handle, buf, len);\r
1288                 else\r
1289                         r = (int)p_SFTP_ReadStdOut(pSFTPData->Handle, buf, len);\r
1290         }\r
1291         else if(pSFTPData->Data == s)\r
1292         {\r
1293                 if(flags & MSG_PEEK)\r
1294                         r = (int)p_SFTP_PeekDataOut(pSFTPData->Handle, buf, len);\r
1295                 else\r
1296                         r = (int)p_SFTP_ReadDataOut(pSFTPData->Handle, buf, len);\r
1297         }\r
1298         return r;\r
1299 }\r
1300 \r
1301 BOOL SFTP_SetTimeoutCallback(SOCKET s, void* pCallback)\r
1302 {\r
1303         SFTPDATA* pSFTPData;\r
1304         if(!g_bPuTTYLoaded)\r
1305                 return FALSE;\r
1306         EnterCriticalSection(&g_PuTTYLock);\r
1307         pSFTPData = FindSFTPDataFromSocket(s);\r
1308         LeaveCriticalSection(&g_PuTTYLock);\r
1309         if(!pSFTPData)\r
1310                 return FALSE;\r
1311         return p_SFTP_SetTimeoutCallback(pSFTPData->Handle, pCallback);\r
1312 }\r
1313 \r
1314 // データ用の仮想的なソケットを取得\r
1315 // 識別子としてダミーのソケットを返す\r
1316 SOCKET SFTP_GetDataHandle(SOCKET s, int af, int type, int protocol)\r
1317 {\r
1318         SOCKET r;\r
1319         SFTPDATA* pSFTPData;\r
1320         if(!g_bPuTTYLoaded)\r
1321                 return INVALID_SOCKET;\r
1322         r = INVALID_SOCKET;\r
1323         EnterCriticalSection(&g_PuTTYLock);\r
1324         if(pSFTPData = FindSFTPDataFromSocket(s))\r
1325         {\r
1326                 r = socket(af, type, protocol);\r
1327                 pSFTPData->Data = r;\r
1328         }\r
1329         LeaveCriticalSection(&g_PuTTYLock);\r
1330         return r;\r
1331 }\r
1332 \r
1333 BOOL SFTP_SetFilePosition(SOCKET s, LONGLONG Position)\r
1334 {\r
1335         SFTPDATA* pSFTPData;\r
1336         if(!g_bPuTTYLoaded)\r
1337                 return FALSE;\r
1338         EnterCriticalSection(&g_PuTTYLock);\r
1339         pSFTPData = FindSFTPDataFromSocket(s);\r
1340         LeaveCriticalSection(&g_PuTTYLock);\r
1341         if(!pSFTPData)\r
1342                 return FALSE;\r
1343         return p_SFTP_SetFilePosition(pSFTPData->Handle, Position);\r
1344 }\r
1345 \r