Debian Codegraph @

netcon/inetfile/CFtp.cpp

raw symbols SCIP
1 /*
2 * Descent 3
3 * Copyright (C) 2024 Parallax Software
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 --- HISTORICAL COMMENTS FOLLOW ---
19
20 * $Logfile: /DescentIII/Main/inetfile/CFtp.cpp $
21 * $Revision: 1.3 $
22 * $Date: 2001/01/13 21:48:46 $
23 * $Author: icculus $
24 *
25 * FTP Client class (get only)
26 *
27 * $Log: CFtp.cpp,v $
28 * Revision 1.3 2001/01/13 21:48:46 icculus
29 * patched to (re)compile on win32.
30 *
31 * Revision 1.2 2000/06/03 14:30:21 icculus
32 * 1.4 code merge and pthread->SDL thread conversion.
33 *
34 * Revision 1.1.1.1 2000/04/18 00:00:38 icculus
35 * initial checkin
36 *
37 *
38 * 8 10/21/99 9:27p Jeff
39 * B.A. Macintosh code merge
40 *
41 * 7 9/08/99 6:37p Jeff
42 * fixed http/ftp downloading for Linux, should all work fine now.
43 *
44 * 6 8/22/99 12:32a Jeff
45 * fixed select calls for Linux. Ported Kevin's new http stuff to Linux
46 *
47 * 5 8/21/99 6:48a Jeff
48 * Linux port
49 *
50 * 4 4/14/99 1:20a Jeff
51 * fixed case mismatched #includes
52 *
53 * 3 7/31/98 11:40a Kevin
54 *
55 * 2 6/01/98 10:10a Kevin
56 * Added DLL connection interface and auto update DLL
57 *
58 * 1 5/27/98 9:52a Kevin
59 *
60 * 1 5/25/98 5:31p Kevin
61 * Initial version
62 *
63 * $NoKeywords: $
64 */
65
66 #ifdef WIN32
67 #include <windows.h>
68 #include <winsock.h>
69 #include <process.h>
70 typedef int socklen_t;
71 #endif
72
73 #include <string.h>
74 #include <stdio.h>
75 #include <stdlib.h>
76
77 #if defined(POSIX)
78 // sorry, I'm lazy, I guess we could copy the defines
79 // that we need to transalte winsock->linux into this header...but no need to now
80 #include "SDL_thread.h"
81 #include "inetgetfile.h"
82 #endif
83
84 #include "CFtp.h"
85
86 // MTS: only used in this file?
87 #if defined(POSIX)
88 int FTPObjThread(void *obj)
89 #else
90 void FTPObjThread(void *obj)
91 #endif
92 {
93 ((CFtpGet *)obj)->WorkerThread();
94 #if defined(POSIX)
95 return 0;
96 #endif
97 }
98
99 void CFtpGet::AbortGet() {
100 m_Aborting = true;
101 while (!m_Aborted)
102 ; // Wait for the thread to end
103 fclose(LOCALFILE);
104 }
105
106 CFtpGet::CFtpGet(char *URL, char *localfile, char *Username, char *Password) {
107 SOCKADDR_IN listensockaddr;
108 m_State = FTP_STATE_STARTUP;
109
110 m_ListenSock = INVALID_SOCKET;
111 m_DataSock = INVALID_SOCKET;
112 m_ControlSock = INVALID_SOCKET;
113 m_iBytesIn = 0;
114 m_iBytesTotal = 0;
115 m_Aborting = false;
116 m_Aborted = false;
117
118 LOCALFILE = fopen(localfile, "wb");
119 if (NULL == LOCALFILE) {
120 m_State = FTP_STATE_CANT_WRITE_FILE;
121 return;
122 }
123
124 if (Username) {
125 strcpy(m_szUserName, Username);
126 } else {
127 strcpy(m_szUserName, "anonymous");
128 }
129 if (Password) {
130 strcpy(m_szPassword, Password);
131 } else {
132 strcpy(m_szPassword, "[email protected]");
133 }
134 m_ListenSock = socket(AF_INET, SOCK_STREAM, 0);
135 if (INVALID_SOCKET == m_ListenSock) {
136 int iWinsockErr = WSAGetLastError();
137 m_State = FTP_STATE_SOCKET_ERROR;
138 return;
139 } else {
140 listensockaddr.sin_family = AF_INET;
141 listensockaddr.sin_port = 0;
142 listensockaddr.sin_addr.s_addr = INADDR_ANY;
143
144 // Bind the listen socket
145 if (bind(m_ListenSock, (SOCKADDR *)&listensockaddr, sizeof(SOCKADDR))) {
146 // Couldn't bind the socket
147 int iWinsockErr = WSAGetLastError();
148 m_State = FTP_STATE_SOCKET_ERROR;
149 return;
150 }
151
152 // Listen for the server connection
153 if (listen(m_ListenSock, 1)) {
154 // Couldn't listen on the socket
155 int iWinsockErr = WSAGetLastError();
156 m_State = FTP_STATE_SOCKET_ERROR;
157 return;
158 }
159 }
160 m_ControlSock = socket(AF_INET, SOCK_STREAM, 0);
161 if (INVALID_SOCKET == m_ControlSock) {
162 m_State = FTP_STATE_SOCKET_ERROR;
163 return;
164 }
165 // Parse the URL
166 // Get rid of any extra ftp:// stuff
167 char *pURL = URL;
168 if (strnicmp(URL, "ftp:", 4) == 0) {
169 pURL += 4;
170 while (*pURL == '/') {
171 pURL++;
172 }
173 }
174 // There shouldn't be any : in this string
175 if (strchr(pURL, ':')) {
176 m_State = FTP_STATE_URL_PARSING_ERROR;
177 return;
178 }
179 // read the filename by searching backwards for a /
180 // then keep reading until you find the first /
181 // when you found it, you have the host and dir
182 char *filestart = NULL;
183 char *dirstart = NULL;
184 for (int i = strlen(pURL); i >= 0; i--) {
185 if (pURL[i] == '/') {
186 if (!filestart) {
187 filestart = pURL + i + 1;
188 dirstart = pURL + i + 1;
189 strcpy(m_szFilename, filestart);
190 } else {
191 dirstart = pURL + i + 1;
192 }
193 }
194 }
195 if ((dirstart == NULL) || (filestart == NULL)) {
196 m_State = FTP_STATE_URL_PARSING_ERROR;
197 return;
198 } else {
199 strncpy(m_szDir, dirstart, (filestart - dirstart));
200 m_szDir[(filestart - dirstart)] = '\0';
201 strncpy(m_szHost, pURL, (dirstart - pURL));
202 m_szHost[(dirstart - pURL) - 1] = '\0';
203 }
204 // At this point we should have a nice host,dir and filename
205
206 #ifdef WIN32
207 if (NULL == _beginthread(FTPObjThread, 0, this)) {
208 m_State = FTP_STATE_INTERNAL_ERROR;
209 return;
210 }
211 #elif defined(POSIX)
212 // pthread_t thread;
213
214 SDL_Thread *thread;
215
216 if (!inet_LoadThreadLib()) {
217 m_State = FTP_STATE_INTERNAL_ERROR;
218 return;
219 }
220
221 // if(df_pthread_create(&thread,NULL,FTPObjThread,this)!=0)
222 thread = SDL_CreateThread(FTPObjThread, "ftpget", this);
223 if (thread == NULL) {
224 m_State = FTP_STATE_INTERNAL_ERROR;
225 return;
226 }
227 #endif
228 m_State = FTP_STATE_CONNECTING;
229 }
230
231 CFtpGet::~CFtpGet() {
232 if (m_ListenSock != INVALID_SOCKET) {
233 shutdown(m_ListenSock, 2);
234 #if !defined(POSIX)
235 closesocket(m_ListenSock);
236 #else
237 close(m_ListenSock);
238 #endif
239 }
240 if (m_DataSock != INVALID_SOCKET) {
241 shutdown(m_DataSock, 2);
242 #if !defined(POSIX)
243 closesocket(m_DataSock);
244 #else
245 close(m_DataSock);
246 #endif
247 }
248 if (m_ControlSock != INVALID_SOCKET) {
249 shutdown(m_ControlSock, 2);
250 #if !defined(POSIX)
251 closesocket(m_ControlSock);
252 #else
253 close(m_ControlSock);
254 #endif
255 }
256 }
257
258 // Returns a value to specify the status (ie. connecting/connected/transferring/done)
259 int CFtpGet::GetStatus() { return m_State; }
260
261 uint32_t CFtpGet::GetBytesIn() { return m_iBytesIn; }
262
263 uint32_t CFtpGet::GetTotalBytes() { return m_iBytesTotal; }
264
265 // This function does all the work -- connects on a blocking socket
266 // then sends the appropriate user and password commands
267 // and then the cwd command, the port command then get and finally the quit
268 void CFtpGet::WorkerThread() {
269 ConnectControlSocket();
270 if (m_State != FTP_STATE_LOGGING_IN) {
271 return;
272 }
273 LoginHost();
274 if (m_State != FTP_STATE_LOGGED_IN) {
275 return;
276 }
277 GetFile();
278
279 // We are all done now, and state has the current state.
280 m_Aborted = true;
281 }
282
283 uint32_t CFtpGet::GetFile() {
284
285 // Start off by changing into the proper dir.
286 char szCommandString[256];
287 int rcode;
288
289 snprintf(szCommandString, sizeof(szCommandString), "TYPE I\r\n");
290 rcode = SendFTPCommand(szCommandString);
291 if (rcode >= 400) {
292 m_State = FTP_STATE_UNKNOWN_ERROR;
293 return 0;
294 }
295 if (m_Aborting)
296 return 0;
297 if (m_szDir[0]) {
298 snprintf(szCommandString, sizeof(szCommandString), "CWD %s\r\n", m_szDir);
299 rcode = SendFTPCommand(szCommandString);
300 if (rcode >= 400) {
301 m_State = FTP_STATE_DIRECTORY_INVALID;
302 return 0;
303 }
304 }
305 if (m_Aborting)
306 return 0;
307 if (!IssuePort()) {
308 m_State = FTP_STATE_UNKNOWN_ERROR;
309 return 0;
310 }
311 if (m_Aborting)
312 return 0;
313 snprintf(szCommandString, sizeof(szCommandString), "RETR %s\r\n", m_szFilename);
314 rcode = SendFTPCommand(szCommandString);
315 if (rcode >= 400) {
316 m_State = FTP_STATE_FILE_NOT_FOUND;
317 return 0;
318 }
319 if (m_Aborting)
320 return 0;
321 // Now we will try to determine the file size...
322 char *p, *s;
323 p = strchr(recv_buffer, '(');
324 if (p) {
325 p++;
326 s = strchr(p, ' ');
327 *s = '\0';
328 m_iBytesTotal = atoi(p);
329 }
330 if (m_Aborting)
331 return 0;
332
333 m_DataSock = accept(m_ListenSock, NULL, NULL); //(SOCKADDR *)&sockaddr,&iAddrLength);
334 // Close the listen socket
335 #if !defined(POSIX)
336 closesocket(m_ListenSock);
337 #else
338 close(m_ListenSock);
339 #endif
340 if (m_DataSock == INVALID_SOCKET) {
341 int iWinsockErr = WSAGetLastError();
342 m_State = FTP_STATE_SOCKET_ERROR;
343 return 0;
344 }
345 if (m_Aborting)
346 return 0;
347
348 ReadDataChannel();
349
350 m_State = FTP_STATE_FILE_RECEIVED;
351 return 1;
352 }
353
354 uint32_t CFtpGet::IssuePort() {
355
356 char szCommandString[200];
357 SOCKADDR_IN listenaddr; // Socket address structure
358 socklen_t iLength; // Length of the address structure
359 uint32_t nLocalPort; // Local port for listening
360 uint32_t nReplyCode; // FTP server reply code
361
362 // Get the address for the hListenSocket
363 iLength = sizeof(listenaddr);
364 if (getsockname(m_ListenSock, (SOCKADDR *)&listenaddr, &iLength) == SOCKET_ERROR) {
365 int iWinsockErr = WSAGetLastError();
366 m_State = FTP_STATE_SOCKET_ERROR;
367 return 0;
368 }
369
370 // Extract the local port from the hListenSocket
371 nLocalPort = listenaddr.sin_port;
372
373 // Now, reuse the socket address structure to
374 // get the IP address from the control socket.
375 if (getsockname(m_ControlSock, (SOCKADDR *)&listenaddr, &iLength) == SOCKET_ERROR) {
376 int iWinsockErr = WSAGetLastError();
377 m_State = FTP_STATE_SOCKET_ERROR;
378 return 0;
379 }
380
381 #ifdef WIN32
382 // Format the PORT command with the correct numbers.
383 sprintf(szCommandString, "PORT %d,%d,%d,%d,%d,%d\r\n", listenaddr.sin_addr.S_un.S_un_b.s_b1,
384 listenaddr.sin_addr.S_un.S_un_b.s_b2, listenaddr.sin_addr.S_un.S_un_b.s_b3,
385 listenaddr.sin_addr.S_un.S_un_b.s_b4, nLocalPort & 0xFF, nLocalPort >> 8);
386 #else
387 union {
388 struct {
389 uint8_t s_b1, s_b2, s_b3, s_b4;
390 } S_un_b;
391 struct {
392 uint16_t s_w1, s_w2;
393 } S_un_w;
394 uint32_t S_addr;
395 } S_un;
396
397 S_un.S_addr = (uint32_t)listenaddr.sin_addr.s_addr;
398 // Format the PORT command with the correct numbers.
399 snprintf(szCommandString, sizeof(szCommandString), "PORT %d,%d,%d,%d,%d,%d\r\n", S_un.S_un_b.s_b1, S_un.S_un_b.s_b2,
400 S_un.S_un_b.s_b3, S_un.S_un_b.s_b4, nLocalPort & 0xFF, nLocalPort >> 8);
401 #endif
402
403 // Tell the server which port to use for data.
404 nReplyCode = SendFTPCommand(szCommandString);
405 if (nReplyCode != 200) {
406 #if defined(POSIX)
407 // I don't know if this is just Linux or do to a bug I fixed while porting to linux
408 // for some reason I kept getting reply 250 here and have to read again to get the
409 // "200 PORT Command OK" or whatever
410 if (nReplyCode != 250 || (ReadFTPServerReply() != 200)) // ummmmmmmm
411 #endif
412 {
413 int iWinsockErr = WSAGetLastError();
414 m_State = FTP_STATE_SOCKET_ERROR;
415 return 0;
416 }
417 }
418
419 return 1;
420 }
421
422 int CFtpGet::ConnectControlSocket() {
423 HOSTENT *he;
424 SERVENT *se;
425 SOCKADDR_IN hostaddr;
426 he = gethostbyname(m_szHost);
427 if (he == NULL) {
428 m_State = FTP_STATE_HOST_NOT_FOUND;
429 return 0;
430 }
431 // m_ControlSock
432 if (m_Aborting)
433 return 0;
434 se = getservbyname("ftp", NULL);
435
436 if (se == NULL) {
437 hostaddr.sin_port = htons(21);
438 } else {
439 hostaddr.sin_port = se->s_port;
440 }
441 hostaddr.sin_family = AF_INET;
442 memcpy(&hostaddr.sin_addr, he->h_addr_list[0], 4);
443 if (m_Aborting)
444 return 0;
445 // Now we will connect to the host
446 if (connect(m_ControlSock, (SOCKADDR *)&hostaddr, sizeof(SOCKADDR))) {
447 int iWinsockErr = WSAGetLastError();
448 m_State = FTP_STATE_CANT_CONNECT;
449 return 0;
450 }
451 m_State = FTP_STATE_LOGGING_IN;
452 return 1;
453 }
454
455 int CFtpGet::LoginHost() {
456 char szLoginString[200];
457 int rcode;
458
459 snprintf(szLoginString, sizeof(szLoginString), "USER %s\r\n", m_szUserName);
460 rcode = SendFTPCommand(szLoginString);
461 if (rcode >= 400) {
462 m_State = FTP_STATE_LOGIN_ERROR;
463 return 0;
464 }
465 snprintf(szLoginString, sizeof(szLoginString), "PASS %s\r\n", m_szPassword);
466 rcode = SendFTPCommand(szLoginString);
467 if (rcode >= 400) {
468 m_State = FTP_STATE_LOGIN_ERROR;
469 return 0;
470 }
471
472 m_State = FTP_STATE_LOGGED_IN;
473 return 1;
474 }
475
476 uint32_t CFtpGet::SendFTPCommand(char *command) {
477
478 FlushControlChannel();
479 // Send the FTP command
480 if (SOCKET_ERROR == (send(m_ControlSock, command, strlen(command), 0))) {
481 int iWinsockErr = WSAGetLastError();
482 // Return 999 to indicate an error has occurred
483 return (999);
484 }
485
486 // Read the server's reply and return the reply code as an integer
487 return (ReadFTPServerReply());
488 }
489
490 uint32_t CFtpGet::ReadFTPServerReply() {
491 uint32_t rcode;
492 uint32_t iBytesRead;
493 char chunk[2];
494 char szcode[5];
495 uint32_t igotcrlf = 0;
496 memset(recv_buffer, 0, 1000);
497 do {
498 chunk[0] = '\0';
499 iBytesRead = recv(m_ControlSock, chunk, 1, 0);
500
501 if (iBytesRead == SOCKET_ERROR) {
502 int iWinsockErr = WSAGetLastError();
503 #if defined(POSIX)
504 if (0 == iWinsockErr) {
505 continue;
506 }
507 #endif
508 // Return 999 to indicate an error has occurred
509 return (999);
510 }
511
512 if ((chunk[0] == 0x0a) || (chunk[0] == 0x0d)) {
513 if (recv_buffer[0] != '\0') {
514 igotcrlf = 1;
515 }
516 } else {
517 chunk[1] = '\0';
518 strcat(recv_buffer, chunk);
519 }
520
521 } while (igotcrlf == 0);
522
523 if (recv_buffer[3] == '-') {
524 // Hack -- must be a MOTD
525 return ReadFTPServerReply();
526 }
527 if (recv_buffer[3] != ' ') {
528 // We should have 3 numbers then a space
529 return 999;
530 }
531 memcpy(szcode, recv_buffer, 3);
532 szcode[3] = '\0';
533 rcode = atoi(szcode);
534 // Extract the reply code from the server reply and return as an integer
535 return (rcode);
536 }
537
538 uint32_t CFtpGet::ReadDataChannel() {
539 char sDataBuffer[4096]; // Data-storage buffer for the data channel
540 int nBytesRecv; // Bytes received from the data channel
541 m_State = FTP_STATE_RECEIVING;
542 if (m_Aborting)
543 return 0;
544 do {
545 if (m_Aborting)
546 return 0;
547 nBytesRecv = recv(m_DataSock, (char *)&sDataBuffer, sizeof(sDataBuffer), 0);
548
549 #if defined(POSIX)
550 if (nBytesRecv == -1) {
551 int iWinsockErr = WSAGetLastError();
552 if (iWinsockErr == 0) {
553 nBytesRecv = 1;
554 continue;
555 }
556 }
557 #endif
558
559 m_iBytesIn += nBytesRecv;
560 if (nBytesRecv > 0) {
561 fwrite(sDataBuffer, nBytesRecv, 1, LOCALFILE);
562 // Write sDataBuffer, nBytesRecv
563 }
564 } while (nBytesRecv > 0);
565 fclose(LOCALFILE);
566 // Close the file and check for error returns.
567 if (nBytesRecv == SOCKET_ERROR) {
568 // Ok, we got a socket error -- xfer aborted?
569 m_State = FTP_STATE_RECV_FAILED;
570 return 0;
571 } else {
572 // done!
573 m_State = FTP_STATE_FILE_RECEIVED;
574 return 1;
575 }
576 }
577
578 void CFtpGet::FlushControlChannel() {
579 fd_set read_fds;
580 TIMEVAL timeout;
581 int bytesin = 0;
582 char flushbuff[3];
583
584 timeout.tv_sec = 0;
585 timeout.tv_usec = 0;
586
587 FD_ZERO(&read_fds);
588 FD_SET(m_ControlSock, &read_fds);
589
590 while (select(m_ControlSock + 1, &read_fds, NULL, NULL, &timeout)) {
591 recv(m_ControlSock, flushbuff, 1, 0);
592 }
593 }