ftpd.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442
  1. /*
  2. * Copyright (C) 2001-2005 by egnite Software GmbH. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. * 3. Neither the name of the copyright holders nor the names of
  14. * contributors may be used to endorse or promote products derived
  15. * from this software without specific prior written permission.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  20. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  21. * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  22. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  23. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  24. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  25. * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  26. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  27. * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  28. * SUCH DAMAGE.
  29. *
  30. * For additional information see http://www.ethernut.de/
  31. *
  32. */
  33. /*!
  34. * \file pro/ftpd.c
  35. * \brief FTP server.
  36. *
  37. * \verbatim
  38. *
  39. * By Malte Marwedel:
  40. * - Adding move command (RNFR, RNTO)
  41. * - (AVR) Moving strings from RAM to flash
  42. * - Add support for list with -la option
  43. * - Checks if file is a real file before accepting a GET
  44. * - Fixing GET if network is busy
  45. * - Fixing "cd foo", "cd ../bar" bug (path should be "/bar" was "//bar")
  46. * - Note: Passive mode is not implemented properly, try to use active instead
  47. *
  48. * $Log$
  49. * Revision 1.12 2009/02/13 14:52:05 haraldkipp
  50. * Include memdebug.h for heap management debugging support.
  51. *
  52. * Revision 1.11 2009/02/06 15:40:29 haraldkipp
  53. * Using newly available strdup() and calloc().
  54. * Replaced NutHeap routines by standard malloc/free.
  55. * Replaced pointer value 0 by NULL.
  56. *
  57. * Revision 1.10 2008/08/11 07:00:35 haraldkipp
  58. * BSD types replaced by stdint types (feature request #1282721).
  59. *
  60. * Revision 1.9 2008/04/01 10:16:35 haraldkipp
  61. * Added S_ISDIR and S_ISREG macro.
  62. *
  63. * Revision 1.8 2006/10/08 16:48:22 haraldkipp
  64. * Documentation fixed
  65. *
  66. * Revision 1.7 2006/03/16 15:25:38 haraldkipp
  67. * Changed human readable strings from u_char to char to stop GCC 4 from
  68. * nagging about signedness.
  69. *
  70. * Revision 1.6 2006/02/23 15:48:08 haraldkipp
  71. * Added missing file truncation flag for overriding existing files.
  72. *
  73. * Revision 1.5 2006/01/25 18:47:42 haraldkipp
  74. * Fixes wrong implementation of readdir() and simplifies the code.
  75. * Thanks to Jesper Hansen.
  76. *
  77. * Revision 1.4 2006/01/22 17:45:29 haraldkipp
  78. * CreateFullPathName() partly returned double slashes or empty paths.
  79. *
  80. * Revision 1.3 2005/08/02 17:47:04 haraldkipp
  81. * Major API documentation update.
  82. *
  83. * Revision 1.2 2005/02/07 18:57:51 haraldkipp
  84. * ICCAVR compile errors fixed
  85. *
  86. * Revision 1.1 2005/02/05 20:45:38 haraldkipp
  87. * First release.
  88. *
  89. *
  90. * \endverbatim
  91. */
  92. //#define FTPD_DEBUG
  93. #include <sys/version.h>
  94. #include <sys/socket.h>
  95. #include <netinet/tcp.h>
  96. #include <sys/timer.h>
  97. #include <string.h>
  98. #include <stdio.h>
  99. #include <stdlib.h>
  100. #include <io.h>
  101. #include <fcntl.h>
  102. #include <sys/stat.h>
  103. #include <dirent.h>
  104. #include <unistd.h>
  105. #include <memdebug.h>
  106. #include <pro/ftpd.h>
  107. #ifdef FTPD_DEBUG
  108. #include <sys/heap.h>
  109. #endif
  110. /*!
  111. * \addtogroup xgFTPD
  112. *
  113. * Internet File Transfer Protocol Server.
  114. */
  115. /*@{*/
  116. /*!
  117. * \name FTP Server Configuration
  118. *
  119. * The Nut/OS Configurator may be used to override the default values.
  120. */
  121. /*@{*/
  122. /*!
  123. * \brief Default FTP root path.
  124. *
  125. * \showinitializer
  126. */
  127. #ifndef FTP_ROOTPATH
  128. #define FTP_ROOTPATH "PNUT:"
  129. #endif
  130. /*!
  131. * \brief Default data port.
  132. *
  133. * \showinitializer
  134. */
  135. #ifndef FTP_DATA_PORT
  136. #define FTP_DATA_PORT 20
  137. #endif
  138. /*@}*/
  139. static char *ftp_root;
  140. static char *ftp_user;
  141. static char *ftp_pass;
  142. /*
  143. * On Harvard architectures constant strings are stored in ROM,
  144. * because RAM is usually a scarce resource on these platforms.
  145. */
  146. static const char cmd_cwd_P[] PROGMEM = "CWD";
  147. static const char cmd_dele_P[] PROGMEM = "DELE";
  148. static const char cmd_list_P[] PROGMEM = "LIST";
  149. static const char cmd_mkd_P[] PROGMEM = "MKD";
  150. static const char cmd_xmkd_P[] PROGMEM = "XMKD";
  151. static const char cmd_nlst_P[] PROGMEM = "NLST";
  152. static const char cmd_noop_P[] PROGMEM = "NOOP";
  153. static const char cmd_pass_P[] PROGMEM = "PASS";
  154. static const char cmd_pasv_P[] PROGMEM = "PASV";
  155. static const char cmd_port_P[] PROGMEM = "PORT";
  156. static const char cmd_pwd_P[] PROGMEM = "PWD";
  157. static const char cmd_xpwd_P[] PROGMEM = "XPWD";
  158. static const char cmd_quit_P[] PROGMEM = "QUIT";
  159. static const char cmd_retr_P[] PROGMEM = "RETR";
  160. static const char cmd_rmd_P[] PROGMEM = "RMD";
  161. static const char cmd_xrmd_P[] PROGMEM = "XRMD";
  162. static const char cmd_stor_P[] PROGMEM = "STOR";
  163. static const char cmd_syst_P[] PROGMEM = "SYST";
  164. static const char cmd_type_P[] PROGMEM = "TYPE";
  165. static const char cmd_user_P[] PROGMEM = "USER";
  166. static const char cmd_rename1_P[] PROGMEM = "RNFR";
  167. static const char cmd_rename2_P[] PROGMEM = "RNTO";
  168. static char *mon_name = "JanFebMarAprMayJunJulAugSepOctNovDec";
  169. static const char rep_banner[] PROGMEM = "220 Nut/OS FTP %s ready at %.3s%3d %02d:%02d:%02d\r\n";
  170. /*!
  171. * \brief Break a string into a command and an argument string.
  172. *
  173. * \param line Pointer to the buffer containing the string. Note, that
  174. * its contents is not preserved.
  175. * \param cmd Receives a pointer to the command word in the given
  176. * string. The routine will convert all lower case letters
  177. * into upper case.
  178. * \param args Receives a pointer to the list of arguments, if any.
  179. * Trailing carriage return or linefeed characters are
  180. * cut off.
  181. */
  182. static void SplitCmdArg(char * line, char ** cmd, char ** args)
  183. {
  184. /* Skip leading spaces. */
  185. while (*line && *line <= ' ') {
  186. line++;
  187. }
  188. /* The first word is the command. Convert it to upper case. */
  189. *cmd = line;
  190. while (*line > ' ') {
  191. if (*line >= (uint8_t) 'a' && *line <= (uint8_t) 'z') {
  192. *line -= (uint8_t) 'a' - 'A';
  193. }
  194. line++;
  195. }
  196. /* Mark end of the command word. */
  197. if (*line) {
  198. *line++ = '\0';
  199. }
  200. /* Skip spaces. */
  201. while (*line && *line <= ' ') {
  202. ++line;
  203. }
  204. /* Arguments start here. */
  205. *args = line;
  206. while (*line && *line != '\r' && *line != '\n') {
  207. line++;
  208. }
  209. /* Mark end of arguments. */
  210. *line = 0;
  211. }
  212. /*!
  213. * \brief Parses arguments of an FTP PORT command.
  214. *
  215. * FTP clients send a target port definition as a comma separated list
  216. * of 6 ASCII byte values. The first four bytes specify an IP address
  217. * and the remaining two a port number.
  218. *
  219. * \param arg Pointer to the argument string.
  220. * \param ip Pointer to an unsigned long, which receives the IP
  221. * address in network byte order.
  222. * \param port Pointer to an unsigned short, which receives the port
  223. * number in host byte order.
  224. *
  225. * \return The number of converted byte values. Should be 6.
  226. */
  227. static int ParseIpPort(const char * arg, uint32_t * ip, uint16_t * port)
  228. {
  229. int rc;
  230. *ip = 0;
  231. *port = 0;
  232. for (rc = 0; rc < 6; rc++) {
  233. if (*arg < '0' || *arg > '9') {
  234. break;
  235. }
  236. if (rc < 4) {
  237. *ip >>= 8;
  238. *ip += atol(arg) << 24;
  239. } else {
  240. *port <<= 8;
  241. *port += atoi(arg);
  242. }
  243. while (*arg && *arg != ',') {
  244. arg++;
  245. }
  246. if (*arg == ',') {
  247. arg++;
  248. }
  249. }
  250. return rc;
  251. }
  252. /*!
  253. * \brief Send a positive response.
  254. *
  255. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  256. * previous call to NutFtpOpenSession().
  257. * \param code Response code.
  258. *
  259. * \return -1 if the session ended. Otherwise 0 is returned.
  260. */
  261. int NutFtpRespondOk(FTPSESSION * session, int code)
  262. {
  263. static const char fmt_P[] PROGMEM = "%d OK\r\n";
  264. #ifdef FTPD_DEBUG
  265. printf("\n<'%d OK' ", code);
  266. #endif
  267. fprintf_P(session->ftp_stream, fmt_P, code);
  268. fflush(session->ftp_stream);
  269. return 0;
  270. }
  271. /*!
  272. * \brief Send a negative response.
  273. *
  274. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  275. * previous call to NutFtpOpenSession().
  276. * \param code Response code.
  277. *
  278. * \return -1 if the session ended. Otherwise 0 is returned.
  279. */
  280. int NutFtpRespondBad(FTPSESSION * session, int code)
  281. {
  282. static const char fmt_P[] PROGMEM = "%d Failed\r\n";
  283. #ifdef FTPD_DEBUG
  284. printf("\n<'%d Failed' ", code);
  285. #endif
  286. fprintf_P(session->ftp_stream, fmt_P, code);
  287. fflush(session->ftp_stream);
  288. return 0;
  289. }
  290. /*!
  291. * \brief Send a response including the specified transfer mode.
  292. *
  293. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  294. * previous call to NutFtpOpenSession().
  295. * \param binary 0 indicates ASCII transfer mode.
  296. *
  297. * \return -1 if the session ended. Otherwise 0 is returned.
  298. */
  299. int NutFtpSendMode(FTPSESSION * session, int binary)
  300. {
  301. static const char intro_P[] PROGMEM = "150 Opening ";
  302. static const char amode_P[] PROGMEM = "ASCII.\r\n";
  303. static const char bmode_P[] PROGMEM = "BINARY.\r\n";
  304. #ifdef FTPD_DEBUG
  305. printf("\n<'150 Opening %s' ", binary ? "BINARY" : "ASCII");
  306. #endif
  307. fputs_P(intro_P, session->ftp_stream);
  308. fputs_P(binary ? bmode_P : amode_P, session->ftp_stream);
  309. fflush(session->ftp_stream);
  310. return 0;
  311. }
  312. /*!
  313. * \brief Create an absolute path name.
  314. *
  315. * Combines an absolute directory path with a relative path name to a
  316. * full absolute path name. The absolute directory is split into two
  317. * parts, the root and the current work directory. The resulting path
  318. * will never be above the specified root.
  319. *
  320. * \param root Non-empty absolute root directory path including the
  321. * device name, but without a trailing slash.
  322. * \param work Absolute work directory path below root including a
  323. * leading, but without a trailing slash. This path is
  324. * ignored if the relative path starts with a slash.
  325. * \param path Relative path name of a file or directory without any
  326. * trailing slash.
  327. *
  328. * \return Pointer to the resulting path name. The buffer for this name
  329. * is allocated from heap memory. The caller is responsible for
  330. * freeing it. In case of an error, a NULL pointer is returned.
  331. */
  332. char *CreateFullPathName(char *root, char *work, char *path)
  333. {
  334. char *full;
  335. char *cp;
  336. size_t rl = root ? strlen(root) : 0;
  337. size_t wl = work ? strlen(work) : 0;
  338. size_t pl = path ? strlen(path) : 0;
  339. /* Ignore trailing slashes in root and work. */
  340. if (rl && *(root + rl - 1) == '/') {
  341. rl--;
  342. }
  343. if (wl && *(work + wl - 1) == '/') {
  344. wl--;
  345. }
  346. if ((full = malloc(rl + wl + pl + 3)) != NULL) {
  347. /* Put the root in front. */
  348. cp = full;
  349. if (rl) {
  350. cp = strcpy(full, root) + rl;
  351. }
  352. /* If path is relative, prepend the working directory. */
  353. if(pl == 0 || *path != '/') {
  354. if (wl) {
  355. if (*work != '/') {
  356. *cp++ = '/';
  357. }
  358. cp = strcpy(cp, work) + wl;
  359. }
  360. *cp++ = '/';
  361. rl++;
  362. }
  363. if (pl) {
  364. *cp = 0;
  365. work = full + rl;
  366. while (*path) {
  367. /* Ingore duplicate slashes. */
  368. if (*path == '/') {
  369. /* No double slash in target if we are at the root */
  370. if ((cp == full) || (*(cp-1) != '/')) {
  371. *cp++ = *path++;
  372. }
  373. while (*path == '/') {
  374. path++;
  375. }
  376. }
  377. /* Ignore single dots. */
  378. if (*path == '.') {
  379. path++;
  380. if (*path == '/') {
  381. path++;
  382. continue;
  383. }
  384. if (*path == 0) {
  385. break;
  386. }
  387. if (*path == '.') {
  388. path++;
  389. if (*path == '/' || *path == 0) {
  390. if (cp != work) {
  391. cp--;
  392. while (cp != work) {
  393. cp--;
  394. if (*cp == '/') {
  395. break;
  396. }
  397. }
  398. }
  399. continue;
  400. }
  401. path--;
  402. }
  403. path--;
  404. }
  405. /* Copy the current path component. */
  406. while (*path && *path != '/') {
  407. *cp++ = *path++;
  408. }
  409. }
  410. }
  411. *cp = 0;
  412. }
  413. return full;
  414. }
  415. /*!
  416. * \brief Establish an FTP connection for data transfer.
  417. *
  418. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  419. * previous call to NutFtpOpenSession().
  420. *
  421. * \return Socket descriptor of the newly created data connection or
  422. * 0 if we were unable to establish the connection.
  423. */
  424. TCPSOCKET *NutFtpDataConnect(FTPSESSION * session)
  425. {
  426. #ifdef FTPD_DEBUG
  427. static const char errorcode_P[] PROGMEM = "errorcode of active socket: %i\n";
  428. static const char socfailed_P[] PROGMEM = "Create socket failed";
  429. #endif
  430. TCPSOCKET *sock;
  431. int rc;
  432. uint32_t tmo;
  433. if ((sock = NutTcpCreateSocket()) != 0) {
  434. if (session->ftp_maxseg) {
  435. NutTcpSetSockOpt(sock, TCP_MAXSEG, &session->ftp_maxseg, sizeof(session->ftp_maxseg));
  436. }
  437. NutTcpGetSockOpt(session->ftp_sock, SO_RCVTIMEO, &tmo, sizeof(tmo));
  438. NutTcpSetSockOpt(sock, SO_RCVTIMEO, &tmo, sizeof(tmo));
  439. if (session->ftp_passive) {
  440. rc = NutTcpAccept(sock, session->ftp_data_port);
  441. } else {
  442. rc = NutTcpConnect(sock, session->ftp_data_ip, session->ftp_data_port);
  443. #ifdef FTPD_DEBUG
  444. if (rc) {
  445. int errorcode = NutTcpError(sock);
  446. printf_P(errorcode_P, errorcode);
  447. }
  448. #endif
  449. }
  450. if (rc) {
  451. NutTcpCloseSocket(sock);
  452. sock = 0;
  453. }
  454. }
  455. #ifdef FTPD_DEBUG
  456. else {
  457. puts_P(socfailed_P);
  458. }
  459. #endif
  460. return sock;
  461. }
  462. /*!
  463. * \brief Register the FTP server's root directory.
  464. *
  465. * Only one root directory is supported. Subsequent calls will
  466. * override previous settings.
  467. *
  468. * \param path Path name of the root directory. Must include the
  469. * device name followed by a colon followed by an
  470. * absolute directory path. May be set to NULL for
  471. * the default #FTP_ROOTPATH.
  472. *
  473. * \return 0 on success, -1 otherwise.
  474. */
  475. int NutRegisterFtpRoot(const char *path)
  476. {
  477. /* Reset path to default. */
  478. if (path == NULL || *path == 0) {
  479. /* Release previously allocate space. */
  480. if (ftp_root) {
  481. free(ftp_root);
  482. }
  483. if ((ftp_root = malloc(sizeof(FTP_ROOTPATH))) == 0) {
  484. return -1;
  485. }
  486. strcpy(ftp_root, FTP_ROOTPATH);
  487. }
  488. /* Set a specified path. */
  489. else {
  490. char *cp = strchr(path, ':');
  491. int len = strlen(path);
  492. /* Make sure that the path fulfills all requirements. */
  493. if (len < 2 || cp == 0 || (*++cp && *cp != '/')) {
  494. return -1;
  495. }
  496. /* Allocate space for new path, but preserve the current one. */
  497. if ((cp = malloc(len + 1)) == 0) {
  498. return -1;
  499. }
  500. /* Take over, releasing previously allocate space. */
  501. strcpy(cp, path);
  502. if (ftp_root) {
  503. free(ftp_root);
  504. }
  505. ftp_root = cp;
  506. /* Chop off an optional trailing slash. */
  507. cp = cp + strlen(cp) - 1;
  508. if (*cp == '/') {
  509. *cp = 0;
  510. }
  511. }
  512. return 0;
  513. }
  514. /*!
  515. * \brief Register an FTP user.
  516. *
  517. * Only one username/password pair is supported. Subsequent calls will
  518. * override previous settings.
  519. *
  520. * \warning Not successfully registering any will make file systems
  521. * accessible by anyone.
  522. *
  523. * \param user User's name.
  524. * \param pass Uncrypted password for the specified user.
  525. *
  526. * \return 0 on success. -1 is returned on failures, in which case
  527. * no protection may be assumed.
  528. */
  529. int NutRegisterFtpUser(const char *user, const char *pass)
  530. {
  531. if (ftp_user) {
  532. free(ftp_user);
  533. ftp_user = NULL;
  534. }
  535. if (user && *user) {
  536. if ((ftp_user = strdup(user)) == NULL) {
  537. return -1;
  538. }
  539. }
  540. if (ftp_pass) {
  541. free(ftp_pass);
  542. ftp_pass = NULL;
  543. }
  544. if (pass && *pass) {
  545. if ((ftp_pass = strdup(pass)) == NULL) {
  546. return -1;
  547. }
  548. }
  549. return 0;
  550. }
  551. /*!
  552. * \brief Open an FTP server session.
  553. *
  554. * \param sock Socket of an established TCP connection.
  555. *
  556. * \return Pointer to an \ref FTPSESSION structure, which can be used
  557. * in subsequent API calls. NULL is returned in case of any
  558. * error.
  559. */
  560. FTPSESSION *NutFtpOpenSession(TCPSOCKET * sock)
  561. {
  562. FTPSESSION *session;
  563. session = malloc(sizeof(FTPSESSION));
  564. if (session) {
  565. memset(session, 0, sizeof(FTPSESSION));
  566. session->ftp_data_port = FTP_DATA_PORT;
  567. session->ftp_maxseg = sock->so_mss;
  568. session->ftp_sock = sock;
  569. /* Set initial working directory. */
  570. if ((session->ftp_cwd = malloc(2)) == 0) {
  571. free(session);
  572. session = 0;
  573. } else {
  574. session->ftp_cwd[0] = '/';
  575. session->ftp_cwd[1] = 0;
  576. /*
  577. * Open a stream and associate it with the socket, so
  578. * we can use standard I/O. Note, that socket streams
  579. * currently do support text mode.
  580. */
  581. if ((session->ftp_stream = _fdopen((int) sock, "r+b")) == 0) {
  582. free(session->ftp_cwd);
  583. free(session);
  584. session = 0;
  585. }
  586. }
  587. }
  588. return session;
  589. }
  590. /*!
  591. * \brief Close an FTP server session.
  592. *
  593. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  594. * previous call to NutFtpOpenSession().
  595. */
  596. void NutFtpCloseSession(FTPSESSION * session)
  597. {
  598. if (session) {
  599. /* Close the stream. */
  600. fclose(session->ftp_stream);
  601. if (session->ftp_cwd) {
  602. free(session->ftp_cwd);
  603. }
  604. if (session->ftp_renamesource) {
  605. free(session->ftp_renamesource);
  606. }
  607. free(session);
  608. }
  609. }
  610. /*!
  611. * \brief Process an FTP client's CWD command.
  612. *
  613. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  614. * previous call to NutFtpOpenSession().
  615. * \param path Full absolute path name of the directory.
  616. *
  617. * \return 0 if the command has been processed or -1 if the
  618. * session has been aborted.
  619. */
  620. int NutFtpProcessCwd(FTPSESSION * session, char *path)
  621. {
  622. struct stat st;
  623. char *cp = path + strlen(ftp_root);
  624. if (*cp && strcmp(cp, "/")) {
  625. /*
  626. * Check, if the path exists and if this is a directory.
  627. */
  628. if (stat(path, &st) || !S_ISDIR(st.st_mode)) {
  629. return NutFtpRespondBad(session, 550);
  630. }
  631. }
  632. /*
  633. * Store the new working directory excluding our root part.
  634. */
  635. if (*cp == 0) {
  636. cp = "/";
  637. }
  638. if (session->ftp_cwd) {
  639. free(session->ftp_cwd);
  640. }
  641. if ((session->ftp_cwd = strdup(cp)) == NULL) {
  642. return NutFtpRespondBad(session, 550);
  643. }
  644. return NutFtpRespondOk(session, 250);
  645. }
  646. /*!
  647. * \brief Process an FTP client's DELE command.
  648. *
  649. * Causes the specified file to be deleted.
  650. *
  651. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  652. * previous call to NutFtpOpenSession().
  653. * \param path Full absolute path name of the file.
  654. *
  655. * \return 0 if the command has been processed or -1 if the
  656. * session has been aborted.
  657. */
  658. int NutFtpProcessDelete(FTPSESSION * session, char *path)
  659. {
  660. if (unlink(path)) {
  661. return NutFtpRespondBad(session, 550);
  662. }
  663. return NutFtpRespondOk(session, 250);
  664. }
  665. /*!
  666. * \brief Transfer a file to or from the FTP client.
  667. *
  668. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  669. * previous call to NutFtpOpenSession().
  670. * \param path Full absolute path name of the file.
  671. * \param mode If set to zero, the server will accept the data
  672. * transferred via the data connection and to store the
  673. * data as a file. If the file exists, then its contents
  674. * will be replaced by the data being transferred. A new
  675. * file is created, if the file does not already exist.
  676. * If this parameter is not equal zero, then the server
  677. * will transfer a copy of the specified file.
  678. *
  679. * \return 0 if the command has been processed or -1 if the
  680. * session has been aborted.
  681. */
  682. int NutFtpTransferFile(FTPSESSION * session, char *path, int mode)
  683. {
  684. #ifdef FTPD_DEBUG
  685. static const char dataconnectfailed_P[] PROGMEM = "NutFtpDataConnect failed";
  686. #endif
  687. TCPSOCKET *sock;
  688. int ec = 550;
  689. int fh = -1;
  690. /* Open the file to send. */
  691. if (mode) {
  692. /* Some clients open file as directorys. Giving them a direct failure */
  693. struct stat st;
  694. if (stat(path, &st) == 0) {
  695. if (S_ISREG(st.st_mode)) {
  696. fh = _open(path, _O_BINARY | _O_RDONLY);
  697. } else {
  698. #ifdef FTPD_DEBUG
  699. printf("Not a regular file\n");
  700. #endif
  701. }
  702. } else {
  703. #ifdef FTPD_DEBUG
  704. printf("'%s' stat() failed\n", path);
  705. #endif
  706. }
  707. }
  708. /* Open the file to receive. */
  709. else {
  710. fh = _open(path, _O_CREAT | _O_TRUNC);
  711. }
  712. if (fh != -1) {
  713. /* File status OK, opening data connection */
  714. NutFtpSendMode(session, session->ftp_tran_mode);
  715. if ((sock = NutFtpDataConnect(session)) != 0) {
  716. uint16_t mss = sock->so_mss;
  717. uint8_t *buf;
  718. if (mss < 256) {
  719. mss = 256;
  720. }
  721. if ((buf = malloc(mss)) != 0) {
  722. int got;
  723. ec = 0;
  724. /* Send a file. */
  725. if (mode) {
  726. while ((got = _read(fh, buf, mss)) > 0) {
  727. int send = 0;
  728. int retcode;
  729. uint8_t timeout = 0;
  730. /* Mentioned in inetq.c, NutTcpSend does not gurantee
  731. to send all bytes, so we use a loop and do a timeout if
  732. no byte has been send within two seconds. */
  733. do {
  734. retcode = NutTcpSend(sock, buf+send, got-send);
  735. send += retcode; //if < 0, we will leave the loop anyway
  736. if (send == 0) {
  737. timeout++;
  738. NutSleep(10);
  739. } else {
  740. timeout = 0;
  741. }
  742. } while ((send < got ) && (retcode >= 0) && (timeout < 200));
  743. if (retcode <= 0) {
  744. #ifdef FTPD_DEBUG
  745. printf("Error in NutTcpSend\n");
  746. #endif
  747. ec = 551;
  748. break;
  749. }
  750. }
  751. }
  752. /* Receive a file. */
  753. else {
  754. while ((got = NutTcpReceive(sock, buf, mss)) > 0) {
  755. int x;
  756. if ((x = _write(fh, buf, got)) != got) {
  757. ec = 552;
  758. break;
  759. }
  760. }
  761. }
  762. free(buf);
  763. }
  764. NutTcpCloseSocket(sock);
  765. }
  766. #ifdef FTPD_DEBUG
  767. else {
  768. puts_P(dataconnectfailed_P);
  769. }
  770. #endif
  771. _close(fh);
  772. /* Remove files received with an error. */
  773. if (mode == 0 && ec) {
  774. unlink(path);
  775. }
  776. }
  777. if (ec) {
  778. return NutFtpRespondBad(session, ec);
  779. }
  780. return NutFtpRespondOk(session, 226);
  781. }
  782. /*!
  783. * \brief Process an FTP client's LIST or NLST command.
  784. *
  785. * Causes a directory listing to be sent to the client.
  786. *
  787. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  788. * previous call to NutFtpOpenSession().
  789. * \param path Full absolute path name of the directory.
  790. *
  791. * \param options Set to 1 to incude filenames beginning with a "." (unix hidden files)
  792. * \return 0 if the command has been processed or -1 if the
  793. * session has been aborted.
  794. */
  795. int NutFtpTransferDirectoryOptions(FTPSESSION * session, char *path, int options)
  796. {
  797. static const char fileattributes_P[] PROGMEM = "rw-rw-rw- 1 0 0 %6lu ";
  798. static const char dateattribute_P[] PROGMEM = "%.3s %u ";
  799. static const char timeattribute_P[] PROGMEM = "%02u:%02u ";
  800. TCPSOCKET *sock;
  801. FILE *fp;
  802. struct stat st;
  803. DIR *dir;
  804. struct dirent *d_ent;
  805. tm *gmt;
  806. uint32_t size;
  807. int ec = 550;
  808. char *name;
  809. size_t pathlen;
  810. dir = opendir(path);
  811. if (dir) {
  812. NutFtpSendMode(session, 0);
  813. if ((sock = NutFtpDataConnect(session)) != 0) {
  814. if ((fp = _fdopen((int) sock, "r+b")) != 0) {
  815. ec = 0;
  816. pathlen = strlen(path);
  817. while ((d_ent = readdir(dir)) != 0) {
  818. if ((d_ent->d_name[0] == '.') && ((options & 1) == 0)) {
  819. continue;
  820. }
  821. if ((name = malloc(pathlen + strlen(d_ent->d_name) + 2)) != 0) {
  822. strcpy(name, path);
  823. if (pathlen == 0 || name[pathlen - 1] != '/') {
  824. strcat(name, "/");
  825. }
  826. strcat(name, d_ent->d_name);
  827. if (stat(name, &st) == 0) {
  828. if (S_ISDIR(st.st_mode)) {
  829. fputc('d', fp);
  830. size = 0;
  831. } else {
  832. fputc('-', fp);
  833. size = st.st_size;
  834. }
  835. fprintf_P(fp, fileattributes_P, size);
  836. gmt = gmtime(&st.st_mtime);
  837. //fprintf(fp, "%s %u %u ", mon_name[gmt->tm_mon], gmt->tm_mday, 1900 + gmt->tm_year);
  838. fprintf_P(fp, dateattribute_P, mon_name + gmt->tm_mon * 3, gmt->tm_mday);
  839. //fprintf(fp, "%02u:%02u:%02u ", gmt->tm_hour, gmt->tm_min, gmt->tm_sec);
  840. fprintf_P(fp, timeattribute_P, gmt->tm_hour, gmt->tm_min);
  841. fputs(d_ent->d_name, fp);
  842. fputs("\r\n", fp);
  843. }
  844. free(name);
  845. }
  846. }
  847. fclose(fp);
  848. }
  849. NutTcpCloseSocket(sock);
  850. }
  851. closedir(dir);
  852. }
  853. if (ec) {
  854. return NutFtpRespondBad(session, ec);
  855. }
  856. return NutFtpRespondOk(session, 226);
  857. }
  858. /*!
  859. * \brief Process an FTP client's LIST or NLST command.
  860. *
  861. * Causes a directory listing to be sent to the client.
  862. *
  863. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  864. * previous call to NutFtpOpenSession().
  865. * \param path Full absolute path name of the directory.
  866. *
  867. * \return 0 if the command has been processed or -1 if the
  868. * session has been aborted.
  869. */
  870. int NutFtpTransferDirectory(FTPSESSION * session, char *path)
  871. {
  872. return NutFtpTransferDirectoryOptions(session, path, 0);
  873. }
  874. /*!
  875. * \brief Process an FTP client's MKD command.
  876. *
  877. * Causes the specified directory to be created.
  878. *
  879. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  880. * previous call to NutFtpOpenSession().
  881. * \param path Full absolute path name of the directory.
  882. *
  883. * \return 0 if the command has been processed or -1 if the
  884. * session has been aborted.
  885. */
  886. int NutFtpProcessMkd(FTPSESSION * session, char *path)
  887. {
  888. if (mkdir(path, 0777)) {
  889. return NutFtpRespondBad(session, 550);
  890. }
  891. return NutFtpRespondOk(session, 257);
  892. }
  893. int NutFtpRenamePrepare(FTPSESSION * session, char *path)
  894. {
  895. if (session->ftp_renamesource) {
  896. free(session->ftp_renamesource);
  897. session->ftp_renamesource = NULL;
  898. }
  899. if (path) {
  900. struct stat st;
  901. if (stat(path, &st) == 0) {
  902. session->ftp_renamesource = strdup(path);
  903. if (session->ftp_renamesource) {
  904. return NutFtpRespondOk(session, 350);
  905. }
  906. } else {
  907. return NutFtpRespondBad(session, 450);
  908. }
  909. }
  910. return NutFtpRespondBad(session, 501);
  911. }
  912. int NutFtpRenameAction(FTPSESSION * session, char *path)
  913. {
  914. uint16_t responsebad;
  915. if (session->ftp_renamesource) {
  916. if (path) {
  917. int res = rename(session->ftp_renamesource, path);
  918. free(session->ftp_renamesource);
  919. session->ftp_renamesource = NULL;
  920. if (res == 0) {
  921. return NutFtpRespondOk(session, 250);
  922. } else {
  923. responsebad = 550;
  924. }
  925. } else {
  926. responsebad = 501;
  927. }
  928. } else {
  929. responsebad = 503;
  930. }
  931. return NutFtpRespondBad(session, responsebad);
  932. }
  933. /*!
  934. * \brief Process an FTP client's PASS command.
  935. *
  936. * Only one login per session is accepted.
  937. *
  938. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  939. * previous call to NutFtpOpenSession().
  940. * \param pass Password.
  941. *
  942. * \return 0 if the command has been processed or -1 if the
  943. * session has been aborted.
  944. */
  945. int NutFtpProcessPass(FTPSESSION * session, char *pass)
  946. {
  947. if (ftp_pass && *ftp_pass) {
  948. if (session->ftp_login != 1 || strcmp(ftp_pass, pass)) {
  949. session->ftp_login = 0;
  950. return NutFtpRespondBad(session, 550);
  951. }
  952. }
  953. session->ftp_login = 2;
  954. return NutFtpRespondOk(session, 230);
  955. }
  956. /*!
  957. * \brief Process an FTP client's PASV command.
  958. *
  959. * This command requests the server to listen on a data port and to wait
  960. * for a connection rather than initiate one upon receipt of a transfer
  961. * command.
  962. *
  963. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  964. * previous call to NutFtpOpenSession().
  965. *
  966. * \return 0 if the command has been processed or -1 if the
  967. * session has been aborted.
  968. */
  969. int NutFtpProcessPassiv(FTPSESSION * session)
  970. {
  971. static const char passiveprint_P[] PROGMEM = "227 Passive (%u,%u,%u,%u,%u,%u).\r\n";
  972. uint32_t ip = session->ftp_sock->so_local_addr;
  973. uint16_t port = 20;
  974. fprintf_P(session->ftp_stream, passiveprint_P, /* */
  975. (uint8_t) ip, (uint8_t) (ip >> 8), (uint8_t) (ip >> 16), (uint8_t) (ip >> 24), /* */
  976. (uint8_t) (port >> 8), (uint8_t) port);
  977. fflush(session->ftp_stream);
  978. session->ftp_passive = 1;
  979. return 0;
  980. }
  981. /*!
  982. * \brief Process an FTP client's PORT command.
  983. *
  984. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  985. * previous call to NutFtpOpenSession().
  986. * \param args Command argument, which is the concatenation of the
  987. * 32-bit internet host address and a 16-bit TCP port
  988. * address. This address information is broken into 8-bit
  989. * fields and the value of each field is transmitted as
  990. * a decimal number.
  991. *
  992. * \return 0 if the command has been processed or -1 if the
  993. * session has been aborted.
  994. */
  995. int NutFtpProcessPort(FTPSESSION * session, char *args)
  996. {
  997. if (ParseIpPort(args, &session->ftp_data_ip, &session->ftp_data_port) == 6) {
  998. if (session->ftp_sock->so_remote_addr == session->ftp_data_ip) {
  999. return NutFtpRespondOk(session, 200);
  1000. }
  1001. return NutFtpRespondBad(session, 425);
  1002. }
  1003. return NutFtpRespondBad(session, 501);;
  1004. }
  1005. /*!
  1006. * \brief Process an FTP client's PWD command.
  1007. *
  1008. * Causes the name of the current working directory to be
  1009. * returned in the reply.
  1010. *
  1011. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  1012. * previous call to NutFtpOpenSession().
  1013. *
  1014. * \return 0 if the command has been processed or -1 if the
  1015. * session has been aborted.
  1016. */
  1017. int NutFtpProcessPwd(FTPSESSION * session)
  1018. {
  1019. static const char pwdanswer_P[] PROGMEM = "257 \"%s\"\r\n";
  1020. #ifdef FTPD_DEBUG
  1021. printf("\n<'257 \"%s\"' ", session->ftp_cwd);
  1022. #endif
  1023. fprintf_P(session->ftp_stream, pwdanswer_P, session->ftp_cwd);
  1024. return 0;
  1025. }
  1026. /*!
  1027. * \brief Process an FTP client's RMD command.
  1028. *
  1029. * Causes the specified directory to be removed.
  1030. *
  1031. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  1032. * previous call to NutFtpOpenSession().
  1033. * \param path Full absolute path name of the directory.
  1034. *
  1035. * \return 0 if the command has been processed or -1 if the
  1036. * session has been aborted.
  1037. */
  1038. int NutFtpProcessRmd(FTPSESSION * session, char *path)
  1039. {
  1040. if (rmdir(path)) {
  1041. return NutFtpRespondBad(session, 451);
  1042. }
  1043. return NutFtpRespondOk(session, 257);
  1044. }
  1045. /*!
  1046. * \brief Process an FTP client's SYST command.
  1047. *
  1048. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  1049. * previous call to NutFtpOpenSession().
  1050. *
  1051. * \return 0 if the command has been processed or -1 if the
  1052. * session has been aborted.
  1053. */
  1054. int NutFtpProcessSystem(FTPSESSION * session)
  1055. {
  1056. static const char unixtype_P[] PROGMEM = "215 UNIX Type: L8\r\n";
  1057. #ifdef FTPD_DEBUG
  1058. printf("\n<'215 UNIX Type: L8' ");
  1059. #endif
  1060. fputs_P(unixtype_P, session->ftp_stream);
  1061. return 0;
  1062. }
  1063. /*!
  1064. * \brief Process an FTP client's TYPE command.
  1065. *
  1066. * The type is not fully checked. Any argument starting with
  1067. * the letters 'A' or 'a' will switch the transfer mode to
  1068. * ASCII. Otherwise binary mode is set.
  1069. *
  1070. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  1071. * previous call to NutFtpOpenSession().
  1072. * \param typecode Command arguments.
  1073. *
  1074. * \return 0 if the command has been processed or -1 if the
  1075. * session has been aborted.
  1076. */
  1077. int NutFtpProcessType(FTPSESSION * session, char *typecode)
  1078. {
  1079. session->ftp_tran_mode = (*typecode != 'A') && (*typecode != 'a');
  1080. return NutFtpRespondOk(session, 200);
  1081. }
  1082. /*!
  1083. * \brief Process an FTP client's USER command.
  1084. *
  1085. * Only one login per session is accepted.
  1086. *
  1087. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  1088. * previous call to NutFtpOpenSession().
  1089. * \param user User name.
  1090. *
  1091. * \return 0 if the command has been processed or -1 if the
  1092. * session has been aborted.
  1093. */
  1094. int NutFtpProcessUser(FTPSESSION * session, char *user)
  1095. {
  1096. if (ftp_user && *ftp_user) {
  1097. if (session->ftp_login && strcmp(ftp_user, user)) {
  1098. session->ftp_login = 0;
  1099. return NutFtpRespondBad(session, 550);
  1100. }
  1101. }
  1102. /* Need a password too. */
  1103. if (ftp_pass && *ftp_pass) {
  1104. session->ftp_login = 1;
  1105. return NutFtpRespondOk(session, 331);
  1106. }
  1107. /* No password required. */
  1108. session->ftp_login = 2;
  1109. return NutFtpRespondOk(session, 230);
  1110. }
  1111. /*!
  1112. * \brief Process an FTP request.
  1113. *
  1114. * This routine implements the protocol interpreter of the FTP server.
  1115. *
  1116. * \param session Pointer to an \ref FTPSESSION structure, obtained by a
  1117. * previous call to NutFtpOpenSession().
  1118. * \param request Request string.
  1119. *
  1120. * \return -1 if the session ended. Otherwise 0 is returned.
  1121. */
  1122. int NutFtpProcessRequest(FTPSESSION * session, char *request)
  1123. {
  1124. int rc = 0;
  1125. char *cmd;
  1126. char *args;
  1127. /* Split the line into command and argument part. */
  1128. SplitCmdArg(request, &cmd, &args);
  1129. #ifdef FTPD_DEBUG
  1130. printf("\n>'%s %s' ", cmd, args);
  1131. #endif
  1132. /* Clean-up if rename request is incomplete */
  1133. if ((session->ftp_renamesource) && (strcmp_P(cmd, cmd_rename2_P))) {
  1134. free(session->ftp_renamesource);
  1135. session->ftp_renamesource = NULL;
  1136. }
  1137. /* QUIT - Terminate session. */
  1138. if (strcmp_P(cmd, cmd_quit_P) == 0) {
  1139. NutFtpRespondOk(session, 221);
  1140. rc = -1;
  1141. }
  1142. /* USER <username> - Check user name. */
  1143. else if (strcmp_P(cmd, cmd_user_P) == 0) {
  1144. rc = NutFtpProcessUser(session, args);
  1145. }
  1146. /* PASS <password> - Check user password. */
  1147. else if (strcmp_P(cmd, cmd_pass_P) == 0) {
  1148. rc = NutFtpProcessPass(session, args);
  1149. } else if (strcmp_P(cmd, cmd_noop_P) == 0) {
  1150. NutFtpRespondOk(session, 200);
  1151. }
  1152. /* Anything else requires a successful login. */
  1153. else if (session->ftp_login < 2) {
  1154. rc = NutFtpRespondBad(session, 530);
  1155. }
  1156. /* Valid login. */
  1157. else {
  1158. /* PASV - Prepare passive transfer. */
  1159. if (strcmp_P(cmd, cmd_pasv_P) == 0) {
  1160. rc = NutFtpProcessPassiv(session);
  1161. }
  1162. /* PORT <host-port> - Set data connection. */
  1163. else if (strcmp_P(cmd, cmd_port_P) == 0) {
  1164. rc = NutFtpProcessPort(session, args);
  1165. }
  1166. /* [X]PWD - Send name of current working directory. */
  1167. else if (strcmp_P(cmd, cmd_pwd_P) == 0 || strcmp_P(cmd, cmd_xpwd_P) == 0) {
  1168. rc = NutFtpProcessPwd(session);
  1169. }
  1170. /* SYST - Send system identifier. */
  1171. else if (strcmp_P(cmd, cmd_syst_P) == 0) {
  1172. rc = NutFtpProcessSystem(session);
  1173. }
  1174. /* TYPE <type-code> - Receive transfer mode. */
  1175. else if (strcmp_P(cmd, cmd_type_P) == 0) {
  1176. rc = NutFtpProcessType(session, args);
  1177. }
  1178. /* Commands with path name argument. */
  1179. else {
  1180. char *path;
  1181. char *argsredux = args;
  1182. int options = 0;
  1183. if (args[0] == '-') {
  1184. if (strchr(args, 'a')) {
  1185. options = 1;
  1186. }
  1187. argsredux = strchr(args, ' ');
  1188. if ((argsredux) && (strlen(argsredux) > 0)) {
  1189. argsredux++; //remove space
  1190. } else {
  1191. argsredux = "";
  1192. }
  1193. }
  1194. if ((path = CreateFullPathName(ftp_root, session->ftp_cwd, argsredux)) == 0) {
  1195. rc = NutFtpRespondBad(session, 451);
  1196. }
  1197. /* CWD <pathname> - Change working directory. */
  1198. else if (strcmp_P(cmd, cmd_cwd_P) == 0) {
  1199. rc = NutFtpProcessCwd(session, path);
  1200. }
  1201. /* DELE <pathname> - Delete a file. */
  1202. else if (strcmp_P(cmd, cmd_dele_P) == 0) {
  1203. rc = NutFtpProcessDelete(session, path);
  1204. }
  1205. /* LIST | NLST [<pathname>] - Send list of files in a directory. */
  1206. else if (strcmp_P(cmd, cmd_list_P) == 0 || strcmp_P(cmd, cmd_nlst_P) == 0) {
  1207. rc = NutFtpTransferDirectoryOptions(session, path, options);
  1208. }
  1209. /* MKD <pathname> - Make a directory. */
  1210. else if (strcmp_P(cmd, cmd_mkd_P) == 0 || strcmp_P(cmd, cmd_xmkd_P) == 0) {
  1211. rc = NutFtpProcessMkd(session, path);
  1212. }
  1213. /* RETR <pathname> - Send a file to the client. */
  1214. else if (strcmp_P(cmd, cmd_retr_P) == 0) {
  1215. rc = NutFtpTransferFile(session, path, 1);
  1216. }
  1217. /* RMD <pathname> - Remove a directory. */
  1218. else if (strcmp_P(cmd, cmd_rmd_P) == 0 || strcmp_P(cmd, cmd_xrmd_P) == 0) {
  1219. rc = NutFtpProcessRmd(session, path);
  1220. }
  1221. /* STOR <pathname> - Receive a file from the client. */
  1222. else if (strcmp_P(cmd, cmd_stor_P) == 0) {
  1223. rc = NutFtpTransferFile(session, path, 0);
  1224. }
  1225. /* RNFR <pathname> from - Rename a file on the client. */
  1226. else if (strcmp_P(cmd, cmd_rename1_P) == 0) {
  1227. rc = NutFtpRenamePrepare(session, path);
  1228. }
  1229. /* RNTO <pathname> to - Rename a file on the client. */
  1230. else if (strcmp_P(cmd, cmd_rename2_P) == 0) {
  1231. rc = NutFtpRenameAction(session, path);
  1232. }
  1233. /* Anything else is an unknown command. */
  1234. else {
  1235. rc = NutFtpRespondBad(session, 502);
  1236. }
  1237. if (path) {
  1238. free(path);
  1239. }
  1240. }
  1241. }
  1242. return rc;
  1243. }
  1244. /*!
  1245. * \brief Process an FTP sever session.
  1246. *
  1247. * Processes FTP requests on an established connection with an FTP client.
  1248. * This routine completely implements an FTP server except TCP connect
  1249. * and disconnect.
  1250. *
  1251. * For file transfers, the same maximum segment size and timeouts as set
  1252. * for this socket will be used for the data connection.
  1253. *
  1254. * \param sock Socket of an established TCP connection.
  1255. *
  1256. * \return 0 if the session ended successfully or -1 if the session
  1257. * has been aborted.
  1258. */
  1259. int NutFtpServerSession(TCPSOCKET * sock)
  1260. {
  1261. int rc = 0;
  1262. FTPSESSION *session;
  1263. char *buff;
  1264. time_t now;
  1265. struct _tm *tip;
  1266. char ch;
  1267. /* Set the root path if not yet done. */
  1268. if (NutRegisterFtpRoot(ftp_root)) {
  1269. return -1;
  1270. }
  1271. /* Allocate the command line buffer. */
  1272. if ((buff = malloc(FTP_MAX_CMDBUF)) == 0) {
  1273. return -1;
  1274. }
  1275. /* Create a session structure and open a stream. */
  1276. if ((session = NutFtpOpenSession(sock)) == 0) {
  1277. free(buff);
  1278. return -1;
  1279. }
  1280. /* Send a welcome banner including system time. */
  1281. time(&now);
  1282. tip = localtime(&now);
  1283. #ifdef FTPD_DEBUG
  1284. printf("\n<'");
  1285. printf_P(rep_banner, NutVersionString(), &mon_name[tip->tm_mon * 3], /* */
  1286. tip->tm_mday, tip->tm_hour, tip->tm_min, tip->tm_sec);
  1287. #endif
  1288. fprintf_P(session->ftp_stream, rep_banner, NutVersionString(), /* */
  1289. &mon_name[tip->tm_mon * 3], /* */
  1290. tip->tm_mday, tip->tm_hour, tip->tm_min, tip->tm_sec);
  1291. /*
  1292. * Loop for requests.
  1293. */
  1294. while (rc == 0) {
  1295. /* Flush any previous output and read a new command line. */
  1296. fflush(session->ftp_stream);
  1297. if (fgets(buff, FTP_MAX_CMDBUF, session->ftp_stream) == 0) {
  1298. rc = -1;
  1299. break;
  1300. }
  1301. /* Skip command lines, which are too long. */
  1302. if ((ch = *(buff + strlen(buff) - 1)) != '\n' && ch != '\r') {
  1303. do {
  1304. if (fgets(buff, FTP_MAX_CMDBUF, session->ftp_stream) == 0) {
  1305. rc = -1;
  1306. break;
  1307. }
  1308. } while ((ch = *(buff + strlen(buff) - 1)) != '\n' && ch != '\r');
  1309. if (rc == 0) {
  1310. rc = NutFtpRespondBad(session, 500);
  1311. }
  1312. }
  1313. /* Process the request. */
  1314. else {
  1315. rc = NutFtpProcessRequest(session, buff);
  1316. }
  1317. }
  1318. /* Cleanup and return. */
  1319. NutFtpCloseSession(session);
  1320. free(buff);
  1321. return rc;
  1322. }
  1323. /*@}*/