├── .gitignore
├── LICENSE
├── Makefile
├── README.md
├── common.h
├── handles.c
├── main.c
├── server.c
└── server.h
/.gitignore:
--------------------------------------------------------------------------------
1 | # Object files
2 | *.o
3 | *.ko
4 | *.obj
5 | *.elf
6 |
7 | # Precompiled Headers
8 | *.gch
9 | *.pch
10 |
11 | # Libraries
12 | *.lib
13 | *.a
14 | *.la
15 | *.lo
16 |
17 | # Shared objects (inc. Windows DLLs)
18 | *.dll
19 | *.so
20 | *.so.*
21 | *.dylib
22 |
23 | # Executables
24 | *.exe
25 | *.out
26 | *.app
27 | *.i*86
28 | *.x86_64
29 | *.hex
30 |
31 | # Debug files
32 | *.dSYM/
33 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
341 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | #makefile
2 | cc = gcc
3 | flag = -lpthread
4 | ftp_server : main.o server.o handles.o
5 | $(cc) main.o server.o handles.o $(flag) -o ftp_server
6 |
7 | main.o : main.c server.h
8 | $(cc) -c main.c $(flag)
9 |
10 | server.o : server.c server.h common.h
11 | $(cc) -c server.c $(flag)
12 |
13 | handles.o : handles.c common.h
14 | $(cc) -c handles.c
15 |
16 | clean :
17 | rm ftp_server *.o
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ftp server c version
2 |
3 | This is a ftp server program written in c .I modified from this version,using threads instead of processes.[original address](https://github.com/Siim/ftp).
4 | You can run it only on linux.
5 |
6 | # Compilation and Run
7 | ```c
8 | # cd to the ftp server dir
9 | make
10 | # execute with ./ftp_server
11 | ```
12 |
13 | # Function introduction
14 | 1. Please run as root.
15 | 2. Default binding port is 8021. You can change it to any port such as 21.
16 | 3. Only supports anonymous users.
17 | 4. Program directory for the FTP root directory
18 | 5. Supported ftp commands include:PASV LIST CWD PWD MKD RMD RETR STOR DELE SIZE ABOR QUIT TYPE NOOP
19 |
--------------------------------------------------------------------------------
/common.h:
--------------------------------------------------------------------------------
1 | #define _GNU_SOURCE
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include
15 |
16 | #ifndef BSIZE
17 | #define BSIZE 1024
18 | #endif
19 | //定义服务器根目录
20 | #define SERVERROOTPATH "/home/tom"
21 |
22 | typedef struct Port
23 | {
24 | int p1;
25 | int p2;
26 | } Port;
27 |
28 | typedef struct State
29 | {
30 | /* Connection mode: NORMAL, SERVER, CLIENT */
31 | int mode;
32 |
33 | /* Is user loggd in? */
34 | int logged_in;
35 |
36 | /* Is this username allowed? */
37 | int username_ok;
38 | char *username;
39 |
40 | /* Response message to client e.g. 220 Welcome */
41 | char *message;
42 |
43 | /* Commander connection */
44 | int connection;
45 |
46 | /* Socket for passive connection (must be accepted later) */
47 | int sock_pasv;
48 |
49 | /* Transfer process id */
50 | int tr_pid;
51 |
52 | } State;
53 |
54 |
55 | /* Command struct */
56 | typedef struct Command
57 | {
58 | char command[5];
59 | char arg[BSIZE];
60 | } Command;
61 |
62 | /**
63 | * Connection mode
64 | * NORMAL - normal connection mode, nothing to transfer
65 | * SERVER - passive connection (PASV command), server listens
66 | * CLIENT - server connects to client (PORT command)
67 | */
68 | typedef enum conn_mode{ NORMAL, SERVER, CLIENT }conn_mode;
69 |
70 | /* Commands enumeration */
71 | typedef enum cmdlist
72 | {
73 | ABOR, CWD, DELE, LIST, MDTM, MKD, NLST, PASS, PASV,
74 | PORT, PWD, QUIT, RETR, RMD, RNFR, RNTO, SITE, SIZE,
75 | STOR, TYPE, USER, NOOP
76 | } cmdlist;
77 |
78 | /* String mappings for cmdlist */
79 | static const char *cmdlist_str[] =
80 | {
81 | "ABOR", "CWD", "DELE", "LIST", "MDTM", "MKD", "NLST", "PASS", "PASV",
82 | "PORT", "PWD", "QUIT", "RETR", "RMD", "RNFR", "RNTO", "SITE", "SIZE",
83 | "STOR", "TYPE", "USER", "NOOP"
84 | };
85 |
86 | /* Valid usernames for anonymous ftp */
87 | static const char *usernames[] =
88 | {
89 | "ftp","anonymous","public","anon","test","foo","siim"
90 | };
91 |
92 | /* Welcome message */
93 | static char *welcome_message = "A very warm welcome!";
94 |
95 | /* Server functions */
96 | void gen_port(Port *);
97 | void parse_command(char *, Command *);
98 | int create_socket(int port);
99 | void write_state(State *);
100 | int accept_connection(int);
101 |
102 | /* Commands handle functions*/
103 | void response(Command *, State *);
104 | void ftp_user(Command *, State *);
105 | void ftp_pass(Command *, State *);
106 | void ftp_pwd(Command *, State *);
107 | void ftp_cwd(Command *, State *);
108 | void ftp_mkd(Command *, State *);
109 | void ftp_rmd(Command *, State *);
110 | void ftp_pasv(Command *, State *);
111 | void ftp_list(Command *, State *);
112 | void ftp_retr(Command *, State *);
113 | void ftp_stor(Command *, State *);
114 | void ftp_dele(Command *, State *);
115 | void ftp_size(Command *, State *);
116 | void ftp_quit(State *);
117 | void ftp_type(Command *, State *);
118 | void ftp_abor(State *);
119 |
120 | void str_perm(int, char *);
121 | void my_wait(int);
122 |
--------------------------------------------------------------------------------
/handles.c:
--------------------------------------------------------------------------------
1 | #include "common.h"
2 | /**
3 | * Generates response message for client
4 | * @param cmd Current command
5 | * @param state Current connection state
6 | */
7 | void response(Command *cmd, State *state)
8 | {
9 | switch(lookup_cmd(cmd->command)){
10 | case USER: ftp_user(cmd,state); break;
11 | case PASS: ftp_pass(cmd,state); break;
12 | case PASV: ftp_pasv(cmd,state); break;
13 | case LIST: ftp_list(cmd,state); break;
14 | case CWD: ftp_cwd(cmd,state); break;
15 | case PWD: ftp_pwd(cmd,state); break;
16 | case MKD: ftp_mkd(cmd,state); break;
17 | case RMD: ftp_rmd(cmd,state); break;
18 | case RETR: ftp_retr(cmd,state); break;
19 | case STOR: ftp_stor(cmd,state); break;
20 | case DELE: ftp_dele(cmd,state); break;
21 | case SIZE: ftp_size(cmd,state); break;
22 | case ABOR: ftp_abor(state); break;
23 | case QUIT: ftp_quit(state); break;
24 | case TYPE: ftp_type(cmd,state); break;
25 | case NOOP:
26 | if(state->logged_in){
27 | state->message = "200 Nice to NOOP you!\n";
28 | }else{
29 | state->message = "530 NOOB hehe.\n";
30 | }
31 | write_state(state);
32 | break;
33 | default:
34 | state->message = "500 Unknown command\n";
35 | write_state(state);
36 | break;
37 | }
38 | }
39 |
40 | /**
41 | * Handle USER command
42 | * @param cmd Command with args
43 | * @param state Current client connection state
44 | */
45 | void ftp_user(Command *cmd, State *state)
46 | {
47 | const int total_usernames = sizeof(usernames)/sizeof(char *);
48 | if(lookup(cmd->arg,usernames,total_usernames)>=0){
49 | state->username = malloc(32);
50 | memset(state->username,0,32);
51 | strcpy(state->username,cmd->arg);
52 | state->username_ok = 1;
53 | state->message = "331 User name okay, need password\n";
54 | }else{
55 | state->message = "530 Invalid username\n";
56 | }
57 | write_state(state);
58 | }
59 |
60 | /** PASS command */
61 | void ftp_pass(Command *cmd, State *state)
62 | {
63 | if(state->username_ok==1){
64 | state->logged_in = 1;
65 | state->message = "230 Login successful\n";
66 | }else{
67 | state->message = "500 Invalid username or password\n";
68 | }
69 | write_state(state);
70 | }
71 |
72 | /** PASV command */
73 | void ftp_pasv(Command *cmd, State *state)
74 | {
75 | if(state->logged_in){
76 | int ip[4];
77 | char buff[255];
78 | char *response = "227 Entering Passive Mode (%d,%d,%d,%d,%d,%d)\n";
79 | Port *port = malloc(sizeof(Port));
80 | gen_port(port);
81 | getip(state->connection,ip);
82 |
83 | /* Close previous passive socket? */
84 | //close(state->sock_pasv);
85 |
86 | /* Start listening here, but don't accept the connection */
87 | state->sock_pasv = create_socket((256*port->p1)+port->p2);
88 | printf("port: %d\n",256*port->p1+port->p2);
89 | sprintf(buff,response,ip[0],ip[1],ip[2],ip[3],port->p1,port->p2);
90 | state->message = buff;
91 | state->mode = SERVER;
92 | puts(state->message);
93 |
94 | }else{
95 | state->message = "530 Please login with USER and PASS.\n";
96 | printf("%s",state->message);
97 | }
98 | write_state(state);
99 | }
100 |
101 | /** LIST command */
102 | void ftp_list(Command *cmd, State *state)
103 | {
104 | if(state->logged_in==1){
105 | struct dirent *entry;
106 | struct stat statbuf;
107 | struct tm *time;
108 | char timebuff[80], current_dir[BSIZE];
109 | int connection;
110 | time_t rawtime;
111 |
112 | /* TODO: dynamic buffering maybe? */
113 | char cwd[BSIZE], cwd_orig[BSIZE];
114 | memset(cwd,0,BSIZE);
115 | memset(cwd_orig,0,BSIZE);
116 |
117 | /* Later we want to go to the original path */
118 | getcwd(cwd_orig,BSIZE);
119 |
120 | /* Just chdir to specified path */
121 | if(strlen(cmd->arg)>0&&cmd->arg[0]!='-'){
122 | chdir(cmd->arg);
123 | }
124 |
125 | getcwd(cwd,BSIZE);
126 | DIR *dp = opendir(cwd);
127 |
128 | if(!dp){
129 | state->message = "550 Failed to open directory.\n";
130 | }else{
131 | if(state->mode == SERVER){
132 |
133 | connection = accept_connection(state->sock_pasv);
134 | state->message = "150 Here comes the directory listing.\n";
135 | puts(state->message);
136 |
137 | while(entry=readdir(dp)){
138 | if(stat(entry->d_name,&statbuf)==-1){
139 | fprintf(stderr, "FTP: Error reading file stats...\n");
140 | }else{
141 | char *perms = malloc(9);
142 | memset(perms,0,9);
143 |
144 | /* Convert time_t to tm struct */
145 | rawtime = statbuf.st_mtime;
146 | time = localtime(&rawtime);
147 | strftime(timebuff,80,"%b %d %H:%M",time);
148 | str_perm((statbuf.st_mode & ALLPERMS), perms);
149 | dprintf(connection,
150 | "%c%s %5d %4d %4d %8d %s %s\r\n",
151 | (entry->d_type==DT_DIR)?'d':'-',
152 | perms,statbuf.st_nlink,
153 | statbuf.st_uid,
154 | statbuf.st_gid,
155 | statbuf.st_size,
156 | timebuff,
157 | entry->d_name);
158 | }
159 | }
160 | write_state(state);
161 | state->message = "226 Directory send OK.\n";
162 | state->mode = NORMAL;
163 | close(connection);
164 | close(state->sock_pasv);
165 |
166 | }else if(state->mode == CLIENT){
167 | state->message = "502 Command not implemented.\n";
168 | }else{
169 | state->message = "425 Use PASV or PORT first.\n";
170 | }
171 | }
172 | closedir(dp);
173 | chdir(cwd_orig);
174 | }else{
175 | state->message = "530 Please login with USER and PASS.\n";
176 | }
177 | state->mode = NORMAL;
178 | write_state(state);
179 | }
180 |
181 |
182 | /** QUIT command */
183 | void ftp_quit(State *state)
184 | {
185 | state->message = "221 Goodbye, friend. I never thought I'd die like this.\n";
186 | write_state(state);
187 | close(state->connection);
188 | exit(0);
189 | }
190 |
191 | /** PWD command */
192 | void ftp_pwd(Command *cmd, State *state)
193 | {
194 | if(state->logged_in){
195 | char cwd[BSIZE];
196 | char result[BSIZE];
197 | memset(result, 0, BSIZE);
198 | if(getcwd(cwd,BSIZE)!=NULL){
199 | strcat(result,"257 \"");
200 | strcat(result,cwd);
201 | strcat(result,"\"\n");
202 | state->message = result;
203 | }else{
204 | state->message = "550 Failed to get pwd.\n";
205 | }
206 | write_state(state);
207 | }
208 | }
209 |
210 | /** CWD command */
211 | void ftp_cwd(Command *cmd, State *state)
212 | {
213 | if(state->logged_in){
214 | // char cwd[BSIZE] = "";
215 | // if((cmd->arg[0] - '/') == 0){
216 | // strcpy(cwd,SERVERROOTPATH);
217 | // strcat(cwd,cmd->arg);
218 | // }else{
219 | // strcpy(cwd,cmd->arg);
220 | // }
221 |
222 | if(chdir(cmd->arg) == 0){
223 | state->message = "250 Directory successfully changed.\n";
224 | }else{
225 | state->message = "550 Failed to change directory.\n";
226 | }
227 | }else{
228 | state->message = "500 Login with USER and PASS.\n";
229 | }
230 | write_state(state);
231 |
232 | }
233 |
234 | /**
235 | * MKD command
236 | * TODO: full path directory creation
237 | */
238 | void ftp_mkd(Command *cmd, State *state)
239 | {
240 | if(state->logged_in){
241 | char cwd[BSIZE];
242 | char res[BSIZE];
243 | memset(cwd,0,BSIZE);
244 | memset(res,0,BSIZE);
245 | getcwd(cwd,BSIZE);
246 |
247 | /* TODO: check if directory already exists with chdir? */
248 |
249 | /* Absolute path */
250 | if(cmd->arg[0]=='/'){
251 | if(mkdir(cmd->arg,S_IRWXU)==0){
252 | strcat(res,"257 \"");
253 | strcat(res,cmd->arg);
254 | strcat(res,"\" new directory created.\n");
255 | state->message = res;
256 | }else{
257 | state->message = "550 Failed to create directory. Check path or permissions.\n";
258 | }
259 | }
260 | /* Relative path */
261 | else{
262 | if(mkdir(cmd->arg,S_IRWXU)==0){
263 | sprintf(res,"257 \"%s/%s\" new directory created.\n",cwd,cmd->arg);
264 | state->message = res;
265 | }else{
266 | state->message = "550 Failed to create directory.\n";
267 | }
268 | }
269 | }else{
270 | state->message = "500 Good news, everyone! There's a report on TV with some very bad news!\n";
271 | }
272 | write_state(state);
273 | }
274 |
275 | /** RETR command 下载文件*/
276 | void ftp_retr(Command *cmd, State *state)
277 | {
278 | int connection;
279 | int fd;
280 | struct stat stat_buf;
281 | off_t offset = 0;
282 | int sent_total = 0;
283 | if(state->logged_in){
284 |
285 | /* Passive mode */
286 | if(state->mode == SERVER){
287 | if(access(cmd->arg,R_OK)==0 && (fd = open(cmd->arg,O_RDONLY))){
288 | fstat(fd,&stat_buf);
289 |
290 | state->message = "150 Opening BINARY mode data connection.\n";
291 |
292 | write_state(state);
293 |
294 | connection = accept_connection(state->sock_pasv);
295 | close(state->sock_pasv);
296 | if(sent_total = sendfile(connection, fd, &offset, stat_buf.st_size)){
297 |
298 | if(sent_total != stat_buf.st_size){
299 | perror("ftp_retr:sendfile");
300 | exit(EXIT_SUCCESS);
301 | }
302 |
303 | state->message = "226 File send OK.\n";
304 | }else{
305 | state->message = "550 Failed to read file.\n";
306 | }
307 | }else{
308 | state->message = "550 Failed to get file\n";
309 | }
310 | }else{
311 | state->message = "550 Please use PASV instead of PORT.\n";
312 | }
313 | }else{
314 | state->message = "530 Please login with USER and PASS.\n";
315 | }
316 |
317 | close(fd);
318 | close(connection);
319 | write_state(state);
320 | }
321 |
322 | /** Handle STOR command. TODO: check permissions. 上传文件*/
323 | void ftp_stor(Command *cmd, State *state)
324 | {
325 | int connection, fd;
326 | off_t offset = 0;
327 | int pipefd[2];
328 | int res = 1;
329 | const int buff_size = 8192;
330 |
331 | FILE *fp = fopen(cmd->arg,"w");
332 |
333 | if(fp==NULL){
334 | /* TODO: write status message here! */
335 | perror("ftp_stor:fopen");
336 | }else if(state->logged_in){
337 | if(!(state->mode==SERVER)){
338 | state->message = "550 Please use PASV instead of PORT.\n";
339 | }
340 | /* Passive mode */
341 | else{
342 | fd = fileno(fp);
343 | connection = accept_connection(state->sock_pasv);
344 | close(state->sock_pasv);
345 | if(pipe(pipefd)==-1)perror("ftp_stor: pipe");
346 |
347 | state->message = "125 Data connection already open; transfer starting.\n";
348 | write_state(state);
349 |
350 | /* Using splice function for file receiving.
351 | * The splice() system call first appeared in Linux 2.6.17.
352 | */
353 |
354 | while ((res = splice(connection, 0, pipefd[1], NULL, buff_size, SPLICE_F_MORE | SPLICE_F_MOVE))>0){
355 | splice(pipefd[0], NULL, fd, 0, buff_size, SPLICE_F_MORE | SPLICE_F_MOVE);
356 | }
357 |
358 | /* TODO: signal with ABOR command to exit */
359 |
360 | /* Internal error */
361 | if(res==-1){
362 | perror("ftp_stor: splice");
363 | exit(EXIT_SUCCESS);
364 | }else{
365 | state->message = "226 File send OK.\n";
366 | }
367 | close(connection);
368 | close(fd);
369 | }
370 | }else{
371 | state->message = "530 Please login with USER and PASS.\n";
372 | }
373 | close(connection);
374 | write_state(state);
375 | }
376 |
377 | /** ABOR command */
378 | void ftp_abor(State *state)
379 | {
380 | if(state->logged_in){
381 | state->message = "226 Closing data connection.\n";
382 | state->message = "225 Data connection open; no transfer in progress.\n";
383 | }else{
384 | state->message = "530 Please login with USER and PASS.\n";
385 | }
386 | write_state(state);
387 |
388 | }
389 |
390 | /**
391 | * Handle TYPE command.
392 | * BINARY only at the moment.
393 | */
394 | void ftp_type(Command *cmd,State *state)
395 | {
396 | if(state->logged_in){
397 | if(cmd->arg[0]=='I'){
398 | state->message = "200 Switching to Binary mode.\n";
399 | }else if(cmd->arg[0]=='A'){
400 |
401 | /* Type A must be always accepted according to RFC */
402 | state->message = "200 Switching to ASCII mode.\n";
403 | }else{
404 | state->message = "504 Command not implemented for that parameter.\n";
405 | }
406 | }else{
407 | state->message = "530 Please login with USER and PASS.\n";
408 | }
409 | write_state(state);
410 | }
411 |
412 | /** Handle DELE command */
413 | void ftp_dele(Command *cmd,State *state)
414 | {
415 | if(state->logged_in){
416 | if(unlink(cmd->arg)==-1){
417 | state->message = "550 File unavailable.\n";
418 | }else{
419 | state->message = "250 Requested file action okay, completed.\n";
420 | }
421 | }else{
422 | state->message = "530 Please login with USER and PASS.\n";
423 | }
424 | write_state(state);
425 | }
426 |
427 | /** Handle RMD */
428 | void ftp_rmd(Command *cmd, State *state)
429 | {
430 | if(!state->logged_in){
431 | state->message = "530 Please login first.\n";
432 | }else{
433 | char cmd_rm[512];
434 | snprintf(cmd_rm,512,"rm -rf %s",cmd->arg);//change by zhaoyou
435 | if(system(cmd_rm)/*remove(cmd->arg)*/==0){
436 | state->message = "250 Requested file action okay, completed.\n";
437 | }else{
438 | state->message = "550 Cannot delete directory.\n";
439 | }
440 | }
441 | write_state(state);
442 | }
443 |
444 | /** Handle SIZE (RFC 3659) */
445 | void ftp_size(Command *cmd, State *state)
446 | {
447 | if(state->logged_in){
448 | struct stat statbuf;
449 | char filesize[128];
450 | memset(filesize,0,128);
451 | /* Success */
452 | if(stat(cmd->arg,&statbuf)==0){
453 | sprintf(filesize, "213 %d\n", statbuf.st_size);
454 | state->message = filesize;
455 | }else{
456 | state->message = "550 Could not get file size.\n";
457 | }
458 | }else{
459 | state->message = "530 Please login with USER and PASS.\n";
460 | }
461 | write_state(state);
462 | }
463 |
464 | /**
465 | * Converts permissions to string. e.g. rwxrwxrwx
466 | * @param perm Permissions mask
467 | * @param str_perm Pointer to string representation of permissions
468 | */
469 | void str_perm(int perm, char *str_perm)
470 | {
471 | int curperm = 0;
472 | int flag = 0;
473 | int read, write, exec;
474 |
475 | /* Flags buffer */
476 | char fbuff[3];
477 | read = write = exec = 0;
478 |
479 | int i;
480 | for(i = 6; i>=0; i-=3){
481 | /* Explode permissions of user, group, others; starting with users */
482 | curperm = ((perm & ALLPERMS) >> i ) & 0x7;
483 |
484 | memset(fbuff,0,3);
485 | /* Check rwx flags for each*/
486 | read = (curperm >> 2) & 0x1;
487 | write = (curperm >> 1) & 0x1;
488 | exec = (curperm >> 0) & 0x1;
489 |
490 | sprintf(fbuff,"%c%c%c",read?'r':'-' ,write?'w':'-', exec?'x':'-');
491 | strcat(str_perm,fbuff);
492 |
493 | }
494 | }
495 |
--------------------------------------------------------------------------------
/main.c:
--------------------------------------------------------------------------------
1 | #include "server.h"
2 | #define SERVERPORT 8021
3 | int main(int argc, char const *argv[])
4 | {
5 | server(SERVERPORT);
6 | return 0;
7 | }
--------------------------------------------------------------------------------
/server.c:
--------------------------------------------------------------------------------
1 | #include "common.h"
2 | #include "server.h"
3 | #include
4 | //Communication
5 | void* communication(void* _c) {
6 | chdir("/");
7 | int connection = *(int*)_c , bytes_read;
8 | char buffer[BSIZE];
9 | Command *cmd = malloc(sizeof(Command));
10 | State *state = malloc(sizeof(State));
11 | state->username = NULL; //add by zhaoyou
12 | memset(buffer,0,BSIZE);
13 | char welcome[BSIZE] = "220 ";
14 | if(strlen(welcome_message) 0){
26 | if(!(bytes_read>BSIZE) && bytes_read > 0){
27 | /* TODO: output this to log */
28 | printf("User %s sent command: %s\n",(state->username==0)?"unknown":state->username,buffer);
29 | parse_command(buffer,cmd);
30 | state->connection = connection;
31 |
32 | /* Ignore non-ascii char. Ignores telnet command */
33 | if(buffer[0]<=127 || buffer[0]>=0){
34 | response(cmd,state);
35 | }
36 | memset(buffer,0,BSIZE);
37 | memset(cmd,0,sizeof(cmd));
38 | }else{
39 | /* Read error */
40 | perror("server:read");
41 | }
42 | }
43 | close(connection);
44 | printf("Client disconnected.\n");
45 | return NULL ;
46 | }
47 |
48 | /**
49 | * Sets up server and handles incoming connections
50 | * @param port Server port
51 | */
52 | void server(int port)
53 | {
54 | //set defaul ftp server root work path.You can customize the path.
55 | if(chroot(SERVERROOTPATH) !=0 )
56 | {
57 | printf("%s","chroot erro:please run as root!\n");
58 | exit(0);
59 | }
60 | int sock = create_socket(port);
61 | struct sockaddr_in client_address;
62 | int len = sizeof(client_address);
63 | while(1){
64 | int *connection = (int*)malloc(sizeof(int));
65 | *connection = accept(sock, (struct sockaddr*) &client_address,&len);
66 |
67 | pthread_t pid;
68 | pthread_create(&pid, NULL, communication, (void*) (connection));
69 | }
70 | }
71 |
72 | /**
73 | * Creates socket on specified port and starts listening to this socket
74 | * @param port Listen on this port
75 | * @return int File descriptor for new socket
76 | */
77 | int create_socket(int port)
78 | {
79 | int sock;
80 | int reuse = 1;
81 | struct sockaddr_in server_address = (struct sockaddr_in){
82 | AF_INET,
83 | htons(port),
84 | (struct in_addr){INADDR_ANY}
85 | };
86 |
87 |
88 | if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
89 | fprintf(stderr, "Cannot open socket");
90 | exit(EXIT_FAILURE);
91 | }
92 |
93 | /* Address can be reused instantly after program exits */
94 | setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof reuse);
95 |
96 | /* Bind socket to server address */
97 | if(bind(sock,(struct sockaddr*) &server_address, sizeof(server_address)) < 0){
98 | fprintf(stderr, "Cannot bind socket to address");
99 | exit(EXIT_FAILURE);
100 | }
101 |
102 | listen(sock,5);
103 | return sock;
104 | }
105 |
106 | /**
107 | * Accept connection from client
108 | * @param socket Server listens this
109 | * @return int File descriptor to accepted connection
110 | */
111 | int accept_connection(int socket)
112 | {
113 | int addrlen = 0;
114 | struct sockaddr_in client_address;
115 | addrlen = sizeof(client_address);
116 | return accept(socket,(struct sockaddr*) &client_address,&addrlen);
117 | }
118 |
119 | /**
120 | * Get ip where client connected to
121 | * @param sock Commander socket connection
122 | * @param ip Result ip array (length must be 4 or greater)
123 | * result IP array e.g. {127,0,0,1}
124 | */
125 | void getip(int sock, int *ip)
126 | {
127 | socklen_t addr_size = sizeof(struct sockaddr_in);
128 | struct sockaddr_in addr;
129 | getsockname(sock, (struct sockaddr *)&addr, &addr_size);
130 | int host,i;
131 |
132 | host = (addr.sin_addr.s_addr);
133 | for(i=0; i<4; i++){
134 | ip[i] = (host>>i*8)&0xff;
135 | }
136 | }
137 |
138 | /**
139 | * Lookup enum value of string
140 | * @param cmd Command string
141 | * @return Enum index if command found otherwise -1
142 | */
143 |
144 | int lookup_cmd(char *cmd){
145 | const int cmdlist_count = sizeof(cmdlist_str)/sizeof(char *);
146 | return lookup(cmd, cmdlist_str, cmdlist_count);
147 | }
148 |
149 | /**
150 | * General lookup for string arrays
151 | * It is suitable for smaller arrays, for bigger ones trie is better
152 | * data structure for instance.
153 | * @param needle String to lookup
154 | * @param haystack Strign array
155 | * @param count Size of haystack
156 | */
157 | int lookup(char *needle, const char **haystack, int count)
158 | {
159 | int i;
160 | for(i=0;iconnection, state->message, strlen(state->message));
173 | }
174 |
175 | /**
176 | * Generate random port for passive mode
177 | * @param state Client state
178 | */
179 | void gen_port(Port *port)
180 | {
181 | srand(time(NULL));
182 | port->p1 = 128 + (rand() % 64);
183 | port->p2 = rand() % 0xff;
184 |
185 | }
186 |
187 | /**
188 | * Parses FTP command string into struct
189 | * @param cmdstring Command string (from ftp client)
190 | * @param cmd Command struct
191 | */
192 | void parse_command(char *cmdstring, Command *cmd)
193 | {
194 | sscanf(cmdstring,"%s %s",cmd->command,cmd->arg);
195 | }
196 |
197 | /**
198 | * Handles zombies
199 | * @param signum Signal number
200 | */
201 | void my_wait(int signum)
202 | {
203 | int status;
204 | wait(&status);
205 | }
206 |
207 |
--------------------------------------------------------------------------------
/server.h:
--------------------------------------------------------------------------------
1 | #ifndef SERVER_H
2 | #define SERVER_H
3 |
4 |
5 | extern void server(int port);
6 |
7 | #endif // SERVER_H
8 |
9 |
--------------------------------------------------------------------------------