├── .clang-format
├── .gitignore
├── .vscode
├── c_cpp_properties.json
├── settings.json
└── tasks.json
├── LICENSE
├── Makefile
├── README.md
├── sd_card
├── atmosphere
│ └── contents
│ │ └── 420000000000000E
│ │ └── toolbox.json
└── config
│ └── sys-ftpd
│ └── config.ini
├── source
├── console.c
├── console.h
├── ftp.c
├── ftp.h
├── led.c
├── led.h
├── main.c
├── minIni.c
├── minIni.h
├── minIni
│ ├── minGlue-FatFs.h
│ ├── minGlue-ccs.h
│ ├── minGlue-efsl.h
│ ├── minGlue-ffs.h
│ ├── minGlue-mdd.h
│ ├── minGlue-stdio.h
│ ├── minGlue.h
│ └── wxMinIni.h
├── util.c
└── util.h
└── sys-ftpd.json
/.clang-format:
--------------------------------------------------------------------------------
1 | UseTab: Never
2 | IndentWidth: 4
3 | BreakBeforeBraces: Allman
4 | AllowShortIfStatementsOnASingleLine: false
5 | IndentCaseLabels: false
6 | ColumnLimit: 0
7 | NamespaceIndentation: All
8 | AccessModifierOffset: -4
9 | PointerAlignment: Left
10 | IndentPPDirectives: AfterHash
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | build
2 | *.elf
3 | *.npdm
4 | *.nso
5 | *.nsp
6 | *.zip
7 | out/
--------------------------------------------------------------------------------
/.vscode/c_cpp_properties.json:
--------------------------------------------------------------------------------
1 | {
2 | "configurations": [
3 | {
4 | "name": "AArch64 libnx",
5 | "includePath": [
6 | "${workspaceFolder}/build",
7 | "${DEVKITPRO}/devkitA64/lib/gcc/aarch64-none-elf/10.1.0/include",
8 | "${DEVKITPRO}/devkitA64/aarch64-none-elf/include",
9 | "${DEVKITPRO}/portlibs/switch/include/**",
10 | "${DEVKITPRO}/libnx/include"
11 | ],
12 | "defines": [
13 | "SWITCH",
14 | "__SWITCH__"
15 | ],
16 | "compilerPath": "${DEVKITPRO}/devkitA64/bin/aarch64-none-elf-g++",
17 | "cStandard": "gnu18",
18 | "cppStandard": "gnu++20",
19 | "intelliSenseMode": "gcc-x64"
20 | }
21 | ],
22 | "version": 4
23 | }
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "editor.formatOnSave": true,
3 | "editor.formatOnType": true,
4 | "C_Cpp.clang_format_style": "file",
5 | "C_Cpp.clang_format_fallbackStyle": "Visual Studio",
6 | "C_Cpp.default.cStandard": "c11",
7 | "C_Cpp.default.intelliSenseMode": "gcc-x64",
8 | "files.associations": {
9 | "__locale": "c",
10 | "stdlib.h": "c",
11 | "inet.h": "c",
12 | "__bit_reference": "c",
13 | "bitset": "c",
14 | "chrono": "c",
15 | "dirent.h": "c",
16 | "stdio.h": "c",
17 | "string.h": "c",
18 | "mp3.h": "c",
19 | "__string": "c",
20 | "string": "c",
21 | "string_view": "c",
22 | "ios": "c",
23 | "ftp.h": "c",
24 | "util.h": "c",
25 | "typeinfo": "c"
26 | }
27 | }
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "Build",
6 | "type": "shell",
7 | "promptOnClose": true,
8 | "command": "make -j3",
9 | "presentation": {
10 | "reveal": "always",
11 | "panel": "shared"
12 | },
13 | "problemMatcher": {
14 | "owner": "cpp",
15 | "pattern": {
16 | "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
17 | "file": 1,
18 | "line": 2,
19 | "column": 3,
20 | "severity": 4,
21 | "message": 5
22 | }
23 | },
24 | "group": {
25 | "kind": "build",
26 | "isDefault": true
27 | }
28 | },
29 | {
30 | "label": "Clean",
31 | "type": "shell",
32 | "promptOnClose": true,
33 | "command": "make clean",
34 | "presentation": {
35 | "reveal": "always",
36 | "panel": "new"
37 | },
38 | "problemMatcher": {
39 | "owner": "cpp",
40 | "pattern": {
41 | "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
42 | "file": 1,
43 | "line": 2,
44 | "column": 3,
45 | "severity": 4,
46 | "message": 5
47 | }
48 | }
49 | },
50 | ]
51 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | #---------------------------------------------------------------------------------
2 | .SUFFIXES:
3 | #---------------------------------------------------------------------------------
4 |
5 | ifeq ($(strip $(DEVKITPRO)),)
6 | $(error "Please set DEVKITPRO in your environment. export DEVKITPRO=/devkitpro")
7 | endif
8 |
9 | TOPDIR ?= $(CURDIR)
10 | include $(DEVKITPRO)/libnx/switch_rules
11 |
12 | #---------------------------------------------------------------------------------
13 | # TARGET is the name of the output
14 | # BUILD is the directory where object files & intermediate files will be placed
15 | # SOURCES is a list of directories containing source code
16 | # DATA is a list of directories containing data files
17 | # INCLUDES is a list of directories containing header files
18 | # EXEFS_SRC is the optional input directory containing data copied into exefs, if anything this normally should only contain "main.npdm".
19 | #---------------------------------------------------------------------------------
20 | TARGET := sys-ftpd
21 | BUILD := build
22 | SOURCES := source
23 | DATA := data
24 | INCLUDES := include
25 | EXEFS_SRC := exefs_src
26 | ROMFS := romfs
27 |
28 | #---------------------------------------------------------------------------------
29 | # options for code generation
30 | #---------------------------------------------------------------------------------
31 | ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIE
32 |
33 | CFLAGS := -g -Wall -O2 -ffunction-sections \
34 | $(ARCH) $(DEFINES)
35 |
36 | CFLAGS += $(INCLUDE) -D__SWITCH__
37 |
38 | CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions -std=gnu++20
39 |
40 | ASFLAGS := -g $(ARCH)
41 | LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
42 |
43 | LIBS := -lnx -lm
44 |
45 | #---------------------------------------------------------------------------------
46 | # list of directories containing libraries, this must be the top level containing
47 | # include and lib
48 | #---------------------------------------------------------------------------------
49 | LIBDIRS := $(PORTLIBS) $(LIBNX)
50 |
51 |
52 | #---------------------------------------------------------------------------------
53 | # no real need to edit anything past this point unless you need to add additional
54 | # rules for different file extensions
55 | #---------------------------------------------------------------------------------
56 | ifneq ($(BUILD),$(notdir $(CURDIR)))
57 | #---------------------------------------------------------------------------------
58 |
59 | export OUTPUT := $(CURDIR)/$(TARGET)
60 | export TOPDIR := $(CURDIR)
61 |
62 | export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
63 | $(foreach dir,$(DATA),$(CURDIR)/$(dir))
64 |
65 | export DEPSDIR := $(CURDIR)/$(BUILD)
66 |
67 | CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
68 | CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
69 | SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
70 | BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
71 |
72 | #---------------------------------------------------------------------------------
73 | # use CXX for linking C++ projects, CC for standard C
74 | #---------------------------------------------------------------------------------
75 | ifeq ($(strip $(CPPFILES)),)
76 | #---------------------------------------------------------------------------------
77 | export LD := $(CC)
78 | #---------------------------------------------------------------------------------
79 | else
80 | #---------------------------------------------------------------------------------
81 | export LD := $(CXX)
82 | #---------------------------------------------------------------------------------
83 | endif
84 | #---------------------------------------------------------------------------------
85 |
86 | export OFILES_BIN := $(addsuffix .o,$(BINFILES))
87 | export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
88 | export OFILES := $(OFILES_BIN) $(OFILES_SRC)
89 | export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES)))
90 |
91 | export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
92 | $(foreach dir,$(LIBDIRS),-I$(dir)/include) \
93 | -I$(CURDIR)/$(BUILD)
94 |
95 | export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)
96 |
97 | export BUILD_EXEFS_SRC := $(TOPDIR)/$(EXEFS_SRC)
98 |
99 | ifeq ($(strip $(CONFIG_JSON)),)
100 | jsons := $(wildcard *.json)
101 | ifneq (,$(findstring $(TARGET).json,$(jsons)))
102 | export APP_JSON := $(TOPDIR)/$(TARGET).json
103 | else
104 | ifneq (,$(findstring config.json,$(jsons)))
105 | export APP_JSON := $(TOPDIR)/config.json
106 | endif
107 | endif
108 | else
109 | export APP_JSON := $(TOPDIR)/$(CONFIG_JSON)
110 | endif
111 |
112 | .PHONY: $(BUILD) clean all
113 |
114 | #---------------------------------------------------------------------------------
115 | all: $(BUILD)
116 |
117 | $(BUILD):
118 | @[ -d $@ ] || mkdir -p $@
119 | @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
120 | @rm -rf out
121 | @mkdir -p out/atmosphere/contents/420000000000000E/flags
122 | @mkdir -p out/config/$(TARGET)
123 | @touch out/atmosphere/contents/420000000000000E/flags/boot2.flag
124 | @cp $(TARGET).nsp out/atmosphere/contents/420000000000000E/exefs.nsp
125 | @cp -r sd_card/. out/
126 | @echo [DONE] $(TARGET) compiled successfully. All files have been placed in out/
127 |
128 | #---------------------------------------------------------------------------------
129 | clean:
130 | @echo clean ...
131 | @rm -fr $(BUILD) $(TARGET).nsp $(TARGET).npdm $(TARGET).nso $(TARGET).elf out
132 |
133 | #---------------------------------------------------------------------------------
134 | else
135 | .PHONY: all
136 |
137 | DEPENDS := $(OFILES:.o=.d)
138 |
139 | #---------------------------------------------------------------------------------
140 | # main targets
141 | #---------------------------------------------------------------------------------
142 | all : $(OUTPUT).nsp
143 |
144 | ifeq ($(strip $(APP_JSON)),)
145 | $(OUTPUT).nsp : $(OUTPUT).nso
146 | else
147 | $(OUTPUT).nsp : $(OUTPUT).nso $(OUTPUT).npdm
148 | endif
149 |
150 | $(OUTPUT).nso : $(OUTPUT).elf
151 |
152 | $(OUTPUT).elf : $(OFILES)
153 |
154 | $(OFILES_SRC) : $(HFILES_BIN)
155 |
156 | #---------------------------------------------------------------------------------
157 | # you need a rule like this for each extension you use as binary data
158 | #---------------------------------------------------------------------------------
159 | %.bin.o : %.bin
160 | #---------------------------------------------------------------------------------
161 | @echo $(notdir $<)
162 | @$(bin2o)
163 |
164 | -include $(DEPENDS)
165 |
166 | #---------------------------------------------------------------------------------------
167 | endif
168 | #---------------------------------------------------------------------------------------
169 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # sys-ftpd
2 |
3 | #### Previously sys-ftpd-light
4 |
5 | This is a lightweight FTP server that runs in the background on your Nintendo Switch.
6 |
7 | - It's a lightweight version of mtheall's [ftpd](https://github.com/mtheall/ftpd) app run as a background service (sysmodule).
8 | - Originally forked from jakibaki's [sys-ftpd](https://github.com/jakibaki/sys-ftpd) in an attempt to improve peformance and stability.
9 |
10 | Since it's lightweight, it occupies less memory on your console at the cost of transferring files a bit slower. If you want to transfer large files, I would suggest you install mtheall's [ftpd](https://github.com/mtheall/ftpd) separately and run it whenever you need to make a large file transfer.
11 |
12 | ## How to use
13 | 1. Go to the [latest release](https://github.com/cathery/sys-ftpd/releases/latest) and download the sys-ftpd zip folder. (not the source code)
14 | 2. Extract the contents of the folder to the root of your Nintendo Switch's SD card. (it should overlap with your existing atmosphere and config folders)
15 | 3. Go to config/sys-ftpd/config.ini and set your username and password for the FTP server. (otherwise it won't let you connect)
16 | - Alternatively you can enable anonymous mode, which will let anyone in the network connect to your FTP server without credentials. (unsafe)
17 | 4. Boot/reboot your Nintendo Switch into CFW as usual.
18 | 5. Once your console is connected to a network, you can connect to your server with any FTP client (you can find them online) from any computer within the same network.
19 | - The IP address of your Nintendo Switch can be found in your console's System Settings -> Internet -> Connection Status -> IP address. (it usually looks like 192.168.X.X)
20 | - The port can be found and modified in the config.ini mentioned above. (it's 5000 by default)
21 | - The resulting address should look something like `192.168.X.X:5000`, where your username and password are your `user` and `password` from config.ini respectively.
22 | 6. You should now be able to enjoy accessing your Nintendo Switch files remotely.
23 |
24 | ## Other
25 |
26 | Hotkeys: To help with security while there is are no login credentials, debugging, or otherwise, you can pause/resume running the server using the PLUS+MINUS+X button combination.
27 |
28 | Sysmodule program ID: **420000000000000E**
29 |
30 | ---
31 |
32 | Config Example (Located on your sd in `sdmc:/config/sys-ftpd/config.ini`):
33 |
34 | ```
35 | [User]
36 | user:=jeremy
37 |
38 | # user:= -> Login username
39 |
40 | [Password]
41 | password:=ilovecars
42 |
43 | # password:= -> Login password
44 |
45 | [Port]
46 | port:=5000
47 |
48 | # port:=5000 -> opens the server on port 5000 (using the console's IP address).
49 |
50 | [Anonymous]
51 | anonymous:=0
52 |
53 | # anonymous:=1 -> Anyone can connect to the server. (dangerous!)
54 | # anonymous:=0 -> Only allows logging into the ftpd server with the correct username and password. user and password (in fields above) must be set.
55 |
56 | [Pause]
57 | disabled:=0
58 | keycombo:=PLUS+MINUS+X
59 |
60 | # disabled:=1 -> Disables allowing sys-ftpd to be paused by pressing the key combination.
61 | # disabled:=0 -> Allows sys-ftpd to be paused by pressing the key combination.
62 | # keycombo:= -> The key combination used to pause sys-ftpd. Each key is separated by either a plus '+' or a space ' '. Up to 8 keys are allowed.
63 | # The list of valid keys is as follows:
64 | # A, B, X, Y, LS, RS, L, R, ZL, ZR, PLUS, MINUS, DLEFT, DUP, DRIGHT, DDOWN
65 |
66 | [LED]
67 | led:=1
68 |
69 | # led:=1 -> LED flashes on connect (default)
70 | # led:=0 -> LED does not flash on connect
71 | ```
72 |
--------------------------------------------------------------------------------
/sd_card/atmosphere/contents/420000000000000E/toolbox.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "sys-ftpd",
3 | "tid": "420000000000000E",
4 | "requires_reboot": false
5 | }
--------------------------------------------------------------------------------
/sd_card/config/sys-ftpd/config.ini:
--------------------------------------------------------------------------------
1 | [User]
2 | user:=
3 |
4 | # user:=abcd -> Login username
5 |
6 | [Password]
7 | password:=
8 |
9 | # password:=xyz123 -> Login password
10 |
11 | [Port]
12 | port:=5000
13 |
14 | # port:=5000 -> opens the server on port 5000 (using the console's IP address).
15 |
16 | [Anonymous]
17 | anonymous:=0
18 |
19 | # anonymous:=1 -> Anyone can connect to the server. (dangerous!)
20 | # anonymous:=0 -> Only allows logging into the ftpd server with the correct username and password. user and password (in fields above) must be set.
21 |
22 | [Pause]
23 | disabled:=0
24 | keycombo:=PLUS+MINUS+X
25 |
26 | # disabled:=1 -> Disables allowing sys-ftpd to be paused by pressing the key combination.
27 | # disabled:=0 -> Allows sys-ftpd to be paused by pressing the key combination.
28 | # keycombo:= -> The key combination used to pause sys-ftpd. Each key is separated by either a plus '+' or a space ' '. Up to 8 keys are allowed.
29 | # The list of valid keys is as follows:
30 | # A, B, X, Y, LS, RS, L, R, ZL, ZR, PLUS, MINUS, DLEFT, DUP, DRIGHT, DDOWN
31 |
32 | [LED]
33 | led:=1
34 |
35 | # led:=1 -> LED flashes on connect (default)
36 | # led:=0 -> LED does not flash on connect
37 |
--------------------------------------------------------------------------------
/source/console.c:
--------------------------------------------------------------------------------
1 | // This file is under the terms of the unlicense (https://github.com/DavidBuchanan314/ftpd/blob/master/LICENSE)
2 |
3 | #define ENABLE_LOGGING 1
4 | #include "console.h"
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 |
12 | /* this is a lot easier when you have a real console */
13 |
14 | int should_log = 0;
15 |
16 | void console_init(void)
17 | {
18 | }
19 |
20 | void console_set_status(const char* fmt, ...)
21 | {
22 | }
23 |
24 | void console_print(const char* fmt, ...)
25 | {
26 | if (should_log)
27 | {
28 | stdout = stderr = fopen("/config/sys-ftpd/logs/ftpd.log", "a");
29 | va_list ap;
30 | va_start(ap, fmt);
31 | vprintf(fmt, ap);
32 | va_end(ap);
33 | fclose(stdout);
34 | }
35 | }
36 |
37 | void debug_print(const char* fmt, ...)
38 | {
39 | if (should_log)
40 | {
41 | stdout = stderr = fopen("/config/sys-ftpd/logs/ftpd.log", "a");
42 | #ifdef ENABLE_LOGGING
43 | va_list ap;
44 | va_start(ap, fmt);
45 | vfprintf(stderr, fmt, ap);
46 | va_end(ap);
47 | #endif
48 | fclose(stdout);
49 | }
50 | }
51 |
52 | void console_render(void)
53 | {
54 | }
55 |
--------------------------------------------------------------------------------
/source/console.h:
--------------------------------------------------------------------------------
1 | // This file is under the terms of the unlicense (https://github.com/DavidBuchanan314/ftpd/blob/master/LICENSE)
2 |
3 | #pragma once
4 |
5 | #ifdef _3DS
6 | # include <3ds.h>
7 | # define ESC(x) "\x1b[" # x
8 | # define RESET ESC(0m)
9 | # define BLACK ESC(30m)
10 | # define RED ESC(31; 1m)
11 | # define GREEN ESC(32; 1m)
12 | # define YELLOW ESC(33; 1m)
13 | # define BLUE ESC(34; 1m)
14 | # define MAGENTA ESC(35; 1m)
15 | # define CYAN ESC(36; 1m)
16 | # define WHITE ESC(37; 1m)
17 | #else
18 | # define ESC(x)
19 | # define RESET
20 | # define BLACK
21 | # define RED
22 | # define GREEN
23 | # define YELLOW
24 | # define BLUE
25 | # define MAGENTA
26 | # define CYAN
27 | # define WHITE
28 | #endif
29 |
30 | extern int should_log;
31 |
32 | void console_init(void);
33 |
34 | __attribute__((format(printf, 1, 2))) void console_set_status(const char* fmt, ...);
35 |
36 | __attribute__((format(printf, 1, 2))) void console_print(const char* fmt, ...);
37 |
38 | __attribute__((format(printf, 1, 2))) void debug_print(const char* fmt, ...);
39 |
40 | void console_render(void);
--------------------------------------------------------------------------------
/source/ftp.h:
--------------------------------------------------------------------------------
1 | // This file is under the terms of the unlicense (https://github.com/DavidBuchanan314/ftpd/blob/master/LICENSE)
2 |
3 | #pragma once
4 |
5 | /*! Loop status */
6 | typedef enum
7 | {
8 | LOOP_CONTINUE, /*!< Continue looping */
9 | LOOP_RESTART, /*!< Reinitialize */
10 | LOOP_EXIT, /*!< Terminate looping */
11 | } loop_status_t;
12 |
13 | typedef struct ftp_session_t ftp_session_t;
14 |
15 | void ftp_pre_init(void);
16 | int ftp_init(void);
17 | loop_status_t ftp_loop(void);
18 | void ftp_exit(void);
19 | void ftp_post_exit(void);
20 |
--------------------------------------------------------------------------------
/source/led.c:
--------------------------------------------------------------------------------
1 | #include "led.h"
2 | #include
3 | #include
4 |
5 | #include "util.h"
6 |
7 | // Breathing effect LED pattern
8 | static const HidsysNotificationLedPattern breathing_pattern = {
9 | .baseMiniCycleDuration = 0x8, // 100ms.
10 | .totalMiniCycles = 0x2, // 3 mini cycles. Last one 12.5ms.
11 | .totalFullCycles = 0x5, // 5 full cycles.
12 | .startIntensity = 0x2, // 13%.
13 | .miniCycles = {
14 | // First cycle
15 | {
16 | .ledIntensity = 0xF, // 100%.
17 | .transitionSteps = 0xF, // 15 steps. Transition time 1.5s.
18 | .finalStepDuration = 0x0, // 12.5ms.
19 | },
20 | // Second cycle
21 | {
22 | .ledIntensity = 0x2, // 13%.
23 | .transitionSteps = 0xF, // 15 steps. Transition time 1.5s.
24 | .finalStepDuration = 0x0, // 12.5ms.
25 | },
26 | },
27 | };
28 |
29 | // Double click LED pattern.
30 | static const HidsysNotificationLedPattern double_click_pattern = {
31 | .baseMiniCycleDuration = 0x6, // 75ms.
32 | .totalMiniCycles = 0x2, // 3 mini cycles. Last one 12.5ms.
33 | .totalFullCycles = 0x1, // 1 full cycle.
34 | .startIntensity = 0xF, // 100%.
35 | .miniCycles = {
36 | // First cycle
37 | {
38 | .ledIntensity = 0x0, // 0%.
39 | .transitionSteps = 0x0, // Instant transition time.
40 | .finalStepDuration = 0x0, // 12.5ms.
41 | },
42 | // Second cycle
43 | {
44 | .ledIntensity = 0xF, // 100%.
45 | .transitionSteps = 0x0, // Instant transition time.
46 | .finalStepDuration = 0x1, // 75ms.
47 | },
48 | },
49 | };
50 |
51 | // Single click LED pattern.
52 | static const HidsysNotificationLedPattern single_click_pattern = {
53 | .baseMiniCycleDuration = 0x8, // 100ms.
54 | .totalMiniCycles = 0x1, // 2 mini cycles. Last one 12.5ms.
55 | .totalFullCycles = 0x1, // 1 full cycle.
56 | .startIntensity = 0xF, // 100%.
57 | .miniCycles = {
58 | // First cycle
59 | {
60 | .ledIntensity = 0x0, // 0%.
61 | .transitionSteps = 0x5, // 3 steps. Transition time 0.5s.
62 | .finalStepDuration = 0x0, // 12.5ms.
63 | },
64 | },
65 | };
66 |
67 | static void send_led_pattern(const HidsysNotificationLedPattern* pattern)
68 | {
69 | s32 total_entries;
70 | HidsysUniquePadId uniquePadIds[2];
71 |
72 | const Result rc = hidsysGetUniquePadsFromNpad(isHidHandheld() ? HidNpadIdType_Handheld : HidNpadIdType_No1, uniquePadIds, 2, &total_entries);
73 | if (R_FAILED(rc) && rc != MAKERESULT(Module_Libnx, LibnxError_IncompatSysVer))
74 | fatalThrow(rc);
75 |
76 | for (int i = 0; i < total_entries; i++)
77 | hidsysSetNotificationLedPattern(pattern, uniquePadIds[i]);
78 | }
79 |
80 | void flash_led_connect()
81 | {
82 | send_led_pattern(&breathing_pattern);
83 | }
84 |
85 | void flash_led_disconnect()
86 | {
87 | HidsysNotificationLedPattern pattern;
88 | memset(&pattern, 0, sizeof(pattern));
89 |
90 | send_led_pattern(&pattern);
91 | }
92 |
93 | void flash_led_pause()
94 | {
95 | send_led_pattern(&double_click_pattern);
96 | }
97 |
98 | void flash_led_unpause()
99 | {
100 | send_led_pattern(&single_click_pattern);
101 | }
102 |
--------------------------------------------------------------------------------
/source/led.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | // Flash LED on FTP connect
4 | void flash_led_connect();
5 |
6 | // Flash LED on FTP disconnect
7 | void flash_led_disconnect();
8 |
9 | // Flash LED on FTP server pause
10 | void flash_led_pause();
11 |
12 | // Flash LED on FTP server unpause
13 | void flash_led_unpause();
--------------------------------------------------------------------------------
/source/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #include "console.h"
6 | #include "ftp.h"
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 |
13 | // only for mkdir, used when creating the "logs" directory
14 | #include
15 |
16 | #include
17 |
18 | #include "util.h"
19 |
20 | #include "minIni.h"
21 |
22 | #define HEAP_SIZE 0xA7000
23 |
24 | // We aren't an applet.
25 | u32 __nx_applet_type = AppletType_None;
26 | // We're a sysmodule and don't need multithreaded FS. Use 1 session instead of default 3.
27 | u32 __nx_fs_num_sessions = 1;
28 |
29 | // setup a fake heap
30 | char fake_heap[HEAP_SIZE];
31 |
32 | // we override libnx internals to do a minimal init
33 | void __libnx_initheap(void)
34 | {
35 | extern char* fake_heap_start;
36 | extern char* fake_heap_end;
37 |
38 | // setup newlib fake heap
39 | fake_heap_start = fake_heap;
40 | fake_heap_end = fake_heap + HEAP_SIZE;
41 | }
42 |
43 | void __appInit(void)
44 | {
45 | R_ASSERT(smInitialize());
46 | R_ASSERT(fsInitialize());
47 | R_ASSERT(fsdevMountSdmc());
48 | R_ASSERT(timeInitialize());
49 | R_ASSERT(hidInitialize());
50 | R_ASSERT(hidsysInitialize());
51 | R_ASSERT(setsysInitialize());
52 | SetSysFirmwareVersion fw;
53 | if (R_SUCCEEDED(setsysGetFirmwareVersion(&fw)))
54 | hosversionSet(MAKEHOSVERSION(fw.major, fw.minor, fw.micro));
55 | setsysExit();
56 |
57 | static const SocketInitConfig socketInitConfig = {
58 | .tcp_tx_buf_size = 0x800,
59 | .tcp_rx_buf_size = 0x800,
60 | .tcp_tx_buf_max_size = 0x25000,
61 | .tcp_rx_buf_max_size = 0x25000,
62 |
63 | //We don't use UDP, set all UDP buffers to 0
64 | .udp_tx_buf_size = 0,
65 | .udp_rx_buf_size = 0,
66 |
67 | .sb_efficiency = 1,
68 | };
69 | R_ASSERT(socketInitialize(&socketInitConfig));
70 | smExit();
71 | }
72 |
73 | void __appExit(void)
74 | {
75 | socketExit();
76 | hidsysExit();
77 | hidExit();
78 | timeExit();
79 | fsdevUnmountAll();
80 | fsExit();
81 | }
82 |
83 | static loop_status_t loop(loop_status_t (*callback)(void))
84 | {
85 | loop_status_t status = LOOP_CONTINUE;
86 |
87 | while (true)
88 | {
89 | svcSleepThread(1e+7);
90 | status = callback();
91 | console_render();
92 | if (status != LOOP_CONTINUE)
93 | return status;
94 | if (isPaused())
95 | return LOOP_RESTART;
96 | }
97 | return LOOP_EXIT;
98 | }
99 |
100 | int main(int argc, char** argv)
101 | {
102 | (void)argc;
103 | (void)argv;
104 |
105 | FILE* should_log_file = fopen("/config/sys-ftpd/logs/ftpd_log_enabled", "r");
106 | if (should_log_file != NULL)
107 | {
108 | should_log = true;
109 | fclose(should_log_file);
110 |
111 | mkdir("/config/sys-ftpd/logs", 0700);
112 | unlink("/config/sys-ftpd/logs/ftpd.log");
113 | }
114 |
115 | char buffer[100];
116 | ini_gets("Pause", "disabled:", "0", buffer, 100, CONFIGPATH);
117 |
118 | initPads();
119 |
120 | //Checks if pausing is disabled in the config file, in which case it skips the entire pause initialization
121 | if (strncmp(buffer, "1", 4) != 0)
122 | {
123 | Result rc = pauseInit();
124 | if (R_FAILED(rc))
125 | fatalThrow(rc);
126 | }
127 |
128 | loop_status_t status = LOOP_RESTART;
129 |
130 | ftp_pre_init();
131 | while (status == LOOP_RESTART)
132 | {
133 | while (isPaused())
134 | {
135 | svcSleepThread(1e+9);
136 | }
137 |
138 | /* initialize ftp subsystem */
139 | if (ftp_init() == 0)
140 | {
141 | /* ftp loop */
142 | status = loop(ftp_loop);
143 |
144 | /* done with ftp */
145 | ftp_exit();
146 | }
147 | else
148 | status = LOOP_EXIT;
149 | }
150 | ftp_post_exit();
151 |
152 | pauseExit();
153 |
154 | return 0;
155 | }
156 |
--------------------------------------------------------------------------------
/source/minIni.c:
--------------------------------------------------------------------------------
1 | /* minIni - Multi-Platform INI file parser, suitable for embedded systems
2 | *
3 | * These routines are in part based on the article "Multiplatform .INI Files"
4 | * by Joseph J. Graf in the March 1994 issue of Dr. Dobb's Journal.
5 | *
6 | * Copyright (c) CompuPhase, 2008-2017
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
9 | * use this file except in compliance with the License. You may obtain a copy
10 | * of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17 | * License for the specific language governing permissions and limitations
18 | * under the License.
19 | *
20 | * Version: $Id: minIni.c 53 2015-01-18 13:35:11Z thiadmer.riemersma@gmail.com $
21 | */
22 |
23 | #if (defined _UNICODE || defined __UNICODE__ || defined UNICODE) && !defined INI_ANSIONLY
24 | # if !defined UNICODE /* for Windows */
25 | # define UNICODE
26 | # endif
27 | # if !defined _UNICODE /* for C library */
28 | # define _UNICODE
29 | # endif
30 | #endif
31 |
32 | #define MININI_IMPLEMENTATION
33 | #include "minIni.h"
34 | #if defined NDEBUG
35 | # define assert(e)
36 | #else
37 | # include
38 | #endif
39 |
40 | #if !defined __T || defined INI_ANSIONLY
41 | # include
42 | # include
43 | # include
44 | # define TCHAR char
45 | # define __T(s) s
46 | # define _tcscat strcat
47 | # define _tcschr strchr
48 | # define _tcscmp strcmp
49 | # define _tcscpy strcpy
50 | # define _tcsicmp stricmp
51 | # define _tcslen strlen
52 | # define _tcsncmp strncmp
53 | # define _tcsncmp strncmp
54 | # define _tcsrchr strrchr
55 | # define _tcstol strtol
56 | # define _tcstod strtod
57 | # define _totupper toupper
58 | # define _stprintf sprintf
59 | # define _tfgets fgets
60 | # define _tfputs fputs
61 | # define _tfopen fopen
62 | # define _tremove remove
63 | # define _trename rename
64 | #endif
65 |
66 | #if defined __linux || defined __linux__
67 | # define __LINUX__
68 | #elif defined FREEBSD && !defined __FreeBSD__
69 | # define __FreeBSD__
70 | #elif defined(_MSC_VER)
71 | # pragma warning(disable : 4996) /* for Microsoft Visual C/C++ */
72 | #endif
73 | #if !defined strncmp && !defined PORTABLE_strncmp
74 | # if defined __LINUX__ || defined __FreeBSD__ || defined __OpenBSD__ || defined __APPLE__
75 | # define strncmp strncasecmp
76 | # endif
77 | #endif
78 | #if !defined _totupper
79 | # define _totupper toupper
80 | #endif
81 |
82 | #if !defined INI_LINETERM
83 | # if defined __LINUX__ || defined __FreeBSD__ || defined __OpenBSD__ || defined __APPLE__
84 | # define INI_LINETERM __T("\n")
85 | # else
86 | # define INI_LINETERM __T("\r\n")
87 | # endif
88 | #endif
89 | #if !defined INI_FILETYPE
90 | # error Missing definition for INI_FILETYPE.
91 | #endif
92 |
93 | #if !defined sizearray
94 | # define sizearray(a) (sizeof(a) / sizeof((a)[0]))
95 | #endif
96 |
97 | enum quote_option
98 | {
99 | QUOTE_NONE,
100 | QUOTE_ENQUOTE,
101 | QUOTE_DEQUOTE,
102 | };
103 |
104 | #if defined PORTABLE_strncmp
105 | int strncmp(const TCHAR* s1, const TCHAR* s2, size_t n)
106 | {
107 | while (n-- != 0 && (*s1 || *s2))
108 | {
109 | register int c1, c2;
110 | c1 = *s1++;
111 | if ('a' <= c1 && c1 <= 'z')
112 | c1 += ('A' - 'a');
113 | c2 = *s2++;
114 | if ('a' <= c2 && c2 <= 'z')
115 | c2 += ('A' - 'a');
116 | if (c1 != c2)
117 | return c1 - c2;
118 | } /* while */
119 | return 0;
120 | }
121 | #endif /* PORTABLE_strncmp */
122 |
123 | static TCHAR* skipleading(const TCHAR* str)
124 | {
125 | assert(str != NULL);
126 | while ('\0' < *str && *str <= ' ')
127 | str++;
128 | return (TCHAR*)str;
129 | }
130 |
131 | static TCHAR* skiptrailing(const TCHAR* str, const TCHAR* base)
132 | {
133 | assert(str != NULL);
134 | assert(base != NULL);
135 | while (str > base && '\0' < *(str - 1) && *(str - 1) <= ' ')
136 | str--;
137 | return (TCHAR*)str;
138 | }
139 |
140 | static TCHAR* striptrailing(TCHAR* str)
141 | {
142 | TCHAR* ptr = skiptrailing(_tcschr(str, '\0'), str);
143 | assert(ptr != NULL);
144 | *ptr = '\0';
145 | return str;
146 | }
147 |
148 | static TCHAR* ini_strncpy(TCHAR* dest, const TCHAR* source, size_t maxlen, enum quote_option option)
149 | {
150 | size_t d, s;
151 |
152 | assert(maxlen > 0);
153 | assert(source != NULL && dest != NULL);
154 | assert((dest < source || (dest == source && option != QUOTE_ENQUOTE)) || dest > source + strlen(source));
155 | if (option == QUOTE_ENQUOTE && maxlen < 3)
156 | option = QUOTE_NONE; /* cannot store two quotes and a terminating zero in less than 3 characters */
157 |
158 | switch (option)
159 | {
160 | case QUOTE_NONE:
161 | for (d = 0; d < maxlen - 1 && source[d] != '\0'; d++)
162 | dest[d] = source[d];
163 | assert(d < maxlen);
164 | dest[d] = '\0';
165 | break;
166 | case QUOTE_ENQUOTE:
167 | d = 0;
168 | dest[d++] = '"';
169 | for (s = 0; source[s] != '\0' && d < maxlen - 2; s++, d++)
170 | {
171 | if (source[s] == '"')
172 | {
173 | if (d >= maxlen - 3)
174 | break; /* no space to store the escape character plus the one that follows it */
175 | dest[d++] = '\\';
176 | } /* if */
177 | dest[d] = source[s];
178 | } /* for */
179 | dest[d++] = '"';
180 | dest[d] = '\0';
181 | break;
182 | case QUOTE_DEQUOTE:
183 | for (d = s = 0; source[s] != '\0' && d < maxlen - 1; s++, d++)
184 | {
185 | if ((source[s] == '"' || source[s] == '\\') && source[s + 1] == '"')
186 | s++;
187 | dest[d] = source[s];
188 | } /* for */
189 | dest[d] = '\0';
190 | break;
191 | default:
192 | assert(0);
193 | } /* switch */
194 |
195 | return dest;
196 | }
197 |
198 | static TCHAR* cleanstring(TCHAR* string, enum quote_option* quotes)
199 | {
200 | int isstring;
201 | TCHAR* ep;
202 |
203 | assert(string != NULL);
204 | assert(quotes != NULL);
205 |
206 | /* Remove a trailing comment */
207 | isstring = 0;
208 | for (ep = string; *ep != '\0' && ((*ep != ';' && *ep != '#') || isstring); ep++)
209 | {
210 | if (*ep == '"')
211 | {
212 | if (*(ep + 1) == '"')
213 | ep++; /* skip "" (both quotes) */
214 | else
215 | isstring = !isstring; /* single quote, toggle isstring */
216 | }
217 | else if (*ep == '\\' && *(ep + 1) == '"')
218 | {
219 | ep++; /* skip \" (both quotes */
220 | } /* if */
221 | } /* for */
222 | assert(ep != NULL && (*ep == '\0' || *ep == ';' || *ep == '#'));
223 | *ep = '\0'; /* terminate at a comment */
224 | striptrailing(string);
225 | /* Remove double quotes surrounding a value */
226 | *quotes = QUOTE_NONE;
227 | if (*string == '"' && (ep = _tcschr(string, '\0')) != NULL && *(ep - 1) == '"')
228 | {
229 | string++;
230 | *--ep = '\0';
231 | *quotes = QUOTE_DEQUOTE; /* this is a string, so remove escaped characters */
232 | } /* if */
233 | return string;
234 | }
235 |
236 | static int getkeystring(INI_FILETYPE* fp, const TCHAR* Section, const TCHAR* Key,
237 | int idxSection, int idxKey, TCHAR* Buffer, int BufferSize,
238 | INI_FILEPOS* mark)
239 | {
240 | TCHAR *sp, *ep;
241 | int len, idx;
242 | enum quote_option quotes;
243 | TCHAR LocalBuffer[INI_BUFFERSIZE];
244 |
245 | assert(fp != NULL);
246 | /* Move through file 1 line at a time until a section is matched or EOF. If
247 | * parameter Section is NULL, only look at keys above the first section. If
248 | * idxSection is positive, copy the relevant section name.
249 | */
250 | len = (Section != NULL) ? (int)_tcslen(Section) : 0;
251 | if (len > 0 || idxSection >= 0)
252 | {
253 | assert(idxSection >= 0 || Section != NULL);
254 | idx = -1;
255 | do
256 | {
257 | if (!ini_read(LocalBuffer, INI_BUFFERSIZE, fp))
258 | return 0;
259 | sp = skipleading(LocalBuffer);
260 | ep = _tcsrchr(sp, ']');
261 | } while (*sp != '[' || ep == NULL ||
262 | (((int)(ep - sp - 1) != len || Section == NULL || _tcsncmp(sp + 1, Section, len) != 0) && ++idx != idxSection));
263 | if (idxSection >= 0)
264 | {
265 | if (idx == idxSection)
266 | {
267 | assert(ep != NULL);
268 | assert(*ep == ']');
269 | *ep = '\0';
270 | ini_strncpy(Buffer, sp + 1, BufferSize, QUOTE_NONE);
271 | return 1;
272 | } /* if */
273 | return 0; /* no more section found */
274 | } /* if */
275 | } /* if */
276 |
277 | /* Now that the section has been found, find the entry.
278 | * Stop searching upon leaving the section's area.
279 | */
280 | assert(Key != NULL || idxKey >= 0);
281 | len = (Key != NULL) ? (int)_tcslen(Key) : 0;
282 | idx = -1;
283 | do
284 | {
285 | if (mark != NULL)
286 | ini_tell(fp, mark); /* optionally keep the mark to the start of the line */
287 | if (!ini_read(LocalBuffer, INI_BUFFERSIZE, fp) || *(sp = skipleading(LocalBuffer)) == '[')
288 | return 0;
289 | sp = skipleading(LocalBuffer);
290 | ep = _tcschr(sp, '='); /* Parse out the equal sign */
291 | if (ep == NULL)
292 | ep = _tcschr(sp, ':');
293 | } while (*sp == ';' || *sp == '#' || ep == NULL || ((len == 0 || (int)(skiptrailing(ep, sp) - sp) != len || _tcsncmp(sp, Key, len) != 0) && ++idx != idxKey));
294 | if (idxKey >= 0)
295 | {
296 | if (idx == idxKey)
297 | {
298 | assert(ep != NULL);
299 | assert(*ep == '=' || *ep == ':');
300 | *ep = '\0';
301 | striptrailing(sp);
302 | ini_strncpy(Buffer, sp, BufferSize, QUOTE_NONE);
303 | return 1;
304 | } /* if */
305 | return 0; /* no more key found (in this section) */
306 | } /* if */
307 |
308 | /* Copy up to BufferSize chars to buffer */
309 | assert(ep != NULL);
310 | assert(*ep == '=' || *ep == ':');
311 | sp = skipleading(ep + 1);
312 | sp = cleanstring(sp, "es); /* Remove a trailing comment */
313 | ini_strncpy(Buffer, sp, BufferSize, quotes);
314 | return 1;
315 | }
316 |
317 | /** ini_gets()
318 | * \param Section the name of the section to search for
319 | * \param Key the name of the entry to find the value of
320 | * \param DefValue default string in the event of a failed read
321 | * \param Buffer a pointer to the buffer to copy into
322 | * \param BufferSize the maximum number of characters to copy
323 | * \param Filename the name and full path of the .ini file to read from
324 | *
325 | * \return the number of characters copied into the supplied buffer
326 | */
327 | int ini_gets(const TCHAR* Section, const TCHAR* Key, const TCHAR* DefValue,
328 | TCHAR* Buffer, int BufferSize, const TCHAR* Filename)
329 | {
330 | INI_FILETYPE fp;
331 | int ok = 0;
332 |
333 | if (Buffer == NULL || BufferSize <= 0 || Key == NULL)
334 | return 0;
335 | if (ini_openread(Filename, &fp))
336 | {
337 | ok = getkeystring(&fp, Section, Key, -1, -1, Buffer, BufferSize, NULL);
338 | (void)ini_close(&fp);
339 | } /* if */
340 | if (!ok)
341 | ini_strncpy(Buffer, (DefValue != NULL) ? DefValue : __T(""), BufferSize, QUOTE_NONE);
342 | return (int)_tcslen(Buffer);
343 | }
344 |
345 | /** ini_getl()
346 | * \param Section the name of the section to search for
347 | * \param Key the name of the entry to find the value of
348 | * \param DefValue the default value in the event of a failed read
349 | * \param Filename the name of the .ini file to read from
350 | *
351 | * \return the value located at Key
352 | */
353 | long ini_getl(const TCHAR* Section, const TCHAR* Key, long DefValue, const TCHAR* Filename)
354 | {
355 | TCHAR LocalBuffer[64];
356 | int len = ini_gets(Section, Key, __T(""), LocalBuffer, sizearray(LocalBuffer), Filename);
357 | return (len == 0) ? DefValue
358 | : ((len >= 2 && _totupper((int)LocalBuffer[1]) == 'X') ? _tcstol(LocalBuffer, NULL, 16)
359 | : _tcstol(LocalBuffer, NULL, 10));
360 | }
361 |
362 | #if defined INI_REAL
363 | /** ini_getf()
364 | * \param Section the name of the section to search for
365 | * \param Key the name of the entry to find the value of
366 | * \param DefValue the default value in the event of a failed read
367 | * \param Filename the name of the .ini file to read from
368 | *
369 | * \return the value located at Key
370 | */
371 | INI_REAL ini_getf(const TCHAR* Section, const TCHAR* Key, INI_REAL DefValue, const TCHAR* Filename)
372 | {
373 | TCHAR LocalBuffer[64];
374 | int len = ini_gets(Section, Key, __T(""), LocalBuffer, sizearray(LocalBuffer), Filename);
375 | return (len == 0) ? DefValue : ini_atof(LocalBuffer);
376 | }
377 | #endif
378 |
379 | /** ini_getbool()
380 | * \param Section the name of the section to search for
381 | * \param Key the name of the entry to find the value of
382 | * \param DefValue default value in the event of a failed read; it should
383 | * zero (0) or one (1).
384 | * \param Filename the name and full path of the .ini file to read from
385 | *
386 | * A true boolean is found if one of the following is matched:
387 | * - A string starting with 'y' or 'Y'
388 | * - A string starting with 't' or 'T'
389 | * - A string starting with '1'
390 | *
391 | * A false boolean is found if one of the following is matched:
392 | * - A string starting with 'n' or 'N'
393 | * - A string starting with 'f' or 'F'
394 | * - A string starting with '0'
395 | *
396 | * \return the true/false flag as interpreted at Key
397 | */
398 | int ini_getbool(const TCHAR* Section, const TCHAR* Key, int DefValue, const TCHAR* Filename)
399 | {
400 | TCHAR LocalBuffer[2] = __T("");
401 | int ret;
402 |
403 | ini_gets(Section, Key, __T(""), LocalBuffer, sizearray(LocalBuffer), Filename);
404 | LocalBuffer[0] = (TCHAR)_totupper((int)LocalBuffer[0]);
405 | if (LocalBuffer[0] == 'Y' || LocalBuffer[0] == '1' || LocalBuffer[0] == 'T')
406 | ret = 1;
407 | else if (LocalBuffer[0] == 'N' || LocalBuffer[0] == '0' || LocalBuffer[0] == 'F')
408 | ret = 0;
409 | else
410 | ret = DefValue;
411 |
412 | return (ret);
413 | }
414 |
415 | /** ini_getsection()
416 | * \param idx the zero-based sequence number of the section to return
417 | * \param Buffer a pointer to the buffer to copy into
418 | * \param BufferSize the maximum number of characters to copy
419 | * \param Filename the name and full path of the .ini file to read from
420 | *
421 | * \return the number of characters copied into the supplied buffer
422 | */
423 | int ini_getsection(int idx, TCHAR* Buffer, int BufferSize, const TCHAR* Filename)
424 | {
425 | INI_FILETYPE fp;
426 | int ok = 0;
427 |
428 | if (Buffer == NULL || BufferSize <= 0 || idx < 0)
429 | return 0;
430 | if (ini_openread(Filename, &fp))
431 | {
432 | ok = getkeystring(&fp, NULL, NULL, idx, -1, Buffer, BufferSize, NULL);
433 | (void)ini_close(&fp);
434 | } /* if */
435 | if (!ok)
436 | *Buffer = '\0';
437 | return (int)_tcslen(Buffer);
438 | }
439 |
440 | /** ini_getkey()
441 | * \param Section the name of the section to browse through, or NULL to
442 | * browse through the keys outside any section
443 | * \param idx the zero-based sequence number of the key to return
444 | * \param Buffer a pointer to the buffer to copy into
445 | * \param BufferSize the maximum number of characters to copy
446 | * \param Filename the name and full path of the .ini file to read from
447 | *
448 | * \return the number of characters copied into the supplied buffer
449 | */
450 | int ini_getkey(const TCHAR* Section, int idx, TCHAR* Buffer, int BufferSize, const TCHAR* Filename)
451 | {
452 | INI_FILETYPE fp;
453 | int ok = 0;
454 |
455 | if (Buffer == NULL || BufferSize <= 0 || idx < 0)
456 | return 0;
457 | if (ini_openread(Filename, &fp))
458 | {
459 | ok = getkeystring(&fp, Section, NULL, -1, idx, Buffer, BufferSize, NULL);
460 | (void)ini_close(&fp);
461 | } /* if */
462 | if (!ok)
463 | *Buffer = '\0';
464 | return (int)_tcslen(Buffer);
465 | }
466 |
467 | #if !defined INI_NOBROWSE
468 | /** ini_browse()
469 | * \param Callback a pointer to a function that will be called for every
470 | * setting in the INI file.
471 | * \param UserData arbitrary data, which the function passes on the
472 | * \c Callback function
473 | * \param Filename the name and full path of the .ini file to read from
474 | *
475 | * \return 1 on success, 0 on failure (INI file not found)
476 | *
477 | * \note The \c Callback function must return 1 to continue
478 | * browsing through the INI file, or 0 to stop. Even when the
479 | * callback stops the browsing, this function will return 1
480 | * (for success).
481 | */
482 | int ini_browse(INI_CALLBACK Callback, void* UserData, const TCHAR* Filename)
483 | {
484 | TCHAR LocalBuffer[INI_BUFFERSIZE];
485 | int lenSec, lenKey;
486 | enum quote_option quotes;
487 | INI_FILETYPE fp;
488 |
489 | if (Callback == NULL)
490 | return 0;
491 | if (!ini_openread(Filename, &fp))
492 | return 0;
493 |
494 | LocalBuffer[0] = '\0'; /* copy an empty section in the buffer */
495 | lenSec = (int)_tcslen(LocalBuffer) + 1;
496 | for (;;)
497 | {
498 | TCHAR *sp, *ep;
499 | if (!ini_read(LocalBuffer + lenSec, INI_BUFFERSIZE - lenSec, &fp))
500 | break;
501 | sp = skipleading(LocalBuffer + lenSec);
502 | /* ignore empty strings and comments */
503 | if (*sp == '\0' || *sp == ';' || *sp == '#')
504 | continue;
505 | /* see whether we reached a new section */
506 | ep = _tcsrchr(sp, ']');
507 | if (*sp == '[' && ep != NULL)
508 | {
509 | *ep = '\0';
510 | ini_strncpy(LocalBuffer, sp + 1, INI_BUFFERSIZE, QUOTE_NONE);
511 | lenSec = (int)_tcslen(LocalBuffer) + 1;
512 | continue;
513 | } /* if */
514 | /* not a new section, test for a key/value pair */
515 | ep = _tcschr(sp, '='); /* test for the equal sign or colon */
516 | if (ep == NULL)
517 | ep = _tcschr(sp, ':');
518 | if (ep == NULL)
519 | continue; /* invalid line, ignore */
520 | *ep++ = '\0'; /* split the key from the value */
521 | striptrailing(sp);
522 | ini_strncpy(LocalBuffer + lenSec, sp, INI_BUFFERSIZE - lenSec, QUOTE_NONE);
523 | lenKey = (int)_tcslen(LocalBuffer + lenSec) + 1;
524 | /* clean up the value */
525 | sp = skipleading(ep);
526 | sp = cleanstring(sp, "es); /* Remove a trailing comment */
527 | ini_strncpy(LocalBuffer + lenSec + lenKey, sp, INI_BUFFERSIZE - lenSec - lenKey, quotes);
528 | /* call the callback */
529 | if (!Callback(LocalBuffer, LocalBuffer + lenSec, LocalBuffer + lenSec + lenKey, UserData))
530 | break;
531 | } /* for */
532 |
533 | (void)ini_close(&fp);
534 | return 1;
535 | }
536 | #endif /* INI_NOBROWSE */
537 |
538 | #if !defined INI_READONLY
539 | static void ini_tempname(TCHAR* dest, const TCHAR* source, int maxlength)
540 | {
541 | TCHAR* p;
542 |
543 | ini_strncpy(dest, source, maxlength, QUOTE_NONE);
544 | p = _tcsrchr(dest, '\0');
545 | assert(p != NULL);
546 | *(p - 1) = '~';
547 | }
548 |
549 | static enum quote_option check_enquote(const TCHAR* Value)
550 | {
551 | const TCHAR* p;
552 |
553 | /* run through the value, if it has trailing spaces, or '"', ';' or '#'
554 | * characters, enquote it
555 | */
556 | assert(Value != NULL);
557 | for (p = Value; *p != '\0' && *p != '"' && *p != ';' && *p != '#'; p++)
558 | /* nothing */;
559 | return (*p != '\0' || (p > Value && *(p - 1) == ' ')) ? QUOTE_ENQUOTE : QUOTE_NONE;
560 | }
561 |
562 | static void writesection(TCHAR* LocalBuffer, const TCHAR* Section, INI_FILETYPE* fp)
563 | {
564 | if (Section != NULL && _tcslen(Section) > 0)
565 | {
566 | TCHAR* p;
567 | LocalBuffer[0] = '[';
568 | ini_strncpy(LocalBuffer + 1, Section, INI_BUFFERSIZE - 4, QUOTE_NONE); /* -1 for '[', -1 for ']', -2 for '\r\n' */
569 | p = _tcsrchr(LocalBuffer, '\0');
570 | assert(p != NULL);
571 | *p++ = ']';
572 | _tcscpy(p, INI_LINETERM); /* copy line terminator (typically "\n") */
573 | if (fp != NULL)
574 | (void)ini_write(LocalBuffer, fp);
575 | } /* if */
576 | }
577 |
578 | static void writekey(TCHAR* LocalBuffer, const TCHAR* Key, const TCHAR* Value, INI_FILETYPE* fp)
579 | {
580 | TCHAR* p;
581 | enum quote_option option = check_enquote(Value);
582 | ini_strncpy(LocalBuffer, Key, INI_BUFFERSIZE - 3, QUOTE_NONE); /* -1 for '=', -2 for '\r\n' */
583 | p = _tcsrchr(LocalBuffer, '\0');
584 | assert(p != NULL);
585 | *p++ = '=';
586 | ini_strncpy(p, Value, INI_BUFFERSIZE - (p - LocalBuffer) - 2, option); /* -2 for '\r\n' */
587 | p = _tcsrchr(LocalBuffer, '\0');
588 | assert(p != NULL);
589 | _tcscpy(p, INI_LINETERM); /* copy line terminator (typically "\n") */
590 | if (fp != NULL)
591 | (void)ini_write(LocalBuffer, fp);
592 | }
593 |
594 | static int cache_accum(const TCHAR* string, int* size, int max)
595 | {
596 | int len = (int)_tcslen(string);
597 | if (*size + len >= max)
598 | return 0;
599 | *size += len;
600 | return 1;
601 | }
602 |
603 | static int cache_flush(TCHAR* buffer, int* size,
604 | INI_FILETYPE* rfp, INI_FILETYPE* wfp, INI_FILEPOS* mark)
605 | {
606 | int terminator_len = (int)_tcslen(INI_LINETERM);
607 | int pos = 0;
608 |
609 | (void)ini_seek(rfp, mark);
610 | assert(buffer != NULL);
611 | buffer[0] = '\0';
612 | assert(size != NULL);
613 | assert(*size <= INI_BUFFERSIZE);
614 | while (pos < *size)
615 | {
616 | (void)ini_read(buffer + pos, INI_BUFFERSIZE - pos, rfp);
617 | while (pos < *size && buffer[pos] != '\0')
618 | pos++; /* cannot use _tcslen() because buffer may not be zero-terminated */
619 | } /* while */
620 | if (buffer[0] != '\0')
621 | {
622 | assert(pos > 0 && pos <= INI_BUFFERSIZE);
623 | if (pos == INI_BUFFERSIZE)
624 | pos--;
625 | buffer[pos] = '\0'; /* force zero-termination (may be left unterminated in the above while loop) */
626 | (void)ini_write(buffer, wfp);
627 | }
628 | ini_tell(rfp, mark); /* update mark */
629 | *size = 0;
630 | /* return whether the buffer ended with a line termination */
631 | return (pos > terminator_len) && (_tcscmp(buffer + pos - terminator_len, INI_LINETERM) == 0);
632 | }
633 |
634 | static int close_rename(INI_FILETYPE* rfp, INI_FILETYPE* wfp, const TCHAR* filename, TCHAR* buffer)
635 | {
636 | (void)ini_close(rfp);
637 | (void)ini_close(wfp);
638 | (void)ini_remove(filename);
639 | (void)ini_tempname(buffer, filename, INI_BUFFERSIZE);
640 | (void)ini_rename(buffer, filename);
641 | return 1;
642 | }
643 |
644 | /** ini_puts()
645 | * \param Section the name of the section to write the string in
646 | * \param Key the name of the entry to write, or NULL to erase all keys in the section
647 | * \param Value a pointer to the buffer the string, or NULL to erase the key
648 | * \param Filename the name and full path of the .ini file to write to
649 | *
650 | * \return 1 if successful, otherwise 0
651 | */
652 | int ini_puts(const TCHAR* Section, const TCHAR* Key, const TCHAR* Value, const TCHAR* Filename)
653 | {
654 | INI_FILETYPE rfp;
655 | INI_FILETYPE wfp;
656 | INI_FILEPOS mark;
657 | INI_FILEPOS head, tail;
658 | TCHAR *sp, *ep;
659 | TCHAR LocalBuffer[INI_BUFFERSIZE];
660 | int len, match, flag, cachelen;
661 |
662 | assert(Filename != NULL);
663 | if (!ini_openread(Filename, &rfp))
664 | {
665 | /* If the .ini file doesn't exist, make a new file */
666 | if (Key != NULL && Value != NULL)
667 | {
668 | if (!ini_openwrite(Filename, &wfp))
669 | return 0;
670 | writesection(LocalBuffer, Section, &wfp);
671 | writekey(LocalBuffer, Key, Value, &wfp);
672 | (void)ini_close(&wfp);
673 | } /* if */
674 | return 1;
675 | } /* if */
676 |
677 | /* If parameters Key and Value are valid (so this is not an "erase" request)
678 | * and the setting already exists, there are two short-cuts to avoid rewriting
679 | * the INI file.
680 | */
681 | if (Key != NULL && Value != NULL)
682 | {
683 | ini_tell(&rfp, &mark);
684 | match = getkeystring(&rfp, Section, Key, -1, -1, LocalBuffer, sizearray(LocalBuffer), &head);
685 | if (match)
686 | {
687 | /* if the current setting is identical to the one to write, there is
688 | * nothing to do.
689 | */
690 | if (_tcscmp(LocalBuffer, Value) == 0)
691 | {
692 | (void)ini_close(&rfp);
693 | return 1;
694 | } /* if */
695 | /* if the new setting has the same length as the current setting, and the
696 | * glue file permits file read/write access, we can modify in place.
697 | */
698 | # if defined ini_openrewrite
699 | /* we already have the start of the (raw) line, get the end too */
700 | ini_tell(&rfp, &tail);
701 | /* create new buffer (without writing it to file) */
702 | writekey(LocalBuffer, Key, Value, NULL);
703 | if (_tcslen(LocalBuffer) == (size_t)(tail - head))
704 | {
705 | /* length matches, close the file & re-open for read/write, then
706 | * write at the correct position
707 | */
708 | (void)ini_close(&rfp);
709 | if (!ini_openrewrite(Filename, &wfp))
710 | return 0;
711 | (void)ini_seek(&wfp, &head);
712 | (void)ini_write(LocalBuffer, &wfp);
713 | (void)ini_close(&wfp);
714 | return 1;
715 | } /* if */
716 | # endif
717 | } /* if */
718 | /* key not found, or different value & length -> proceed (but rewind the
719 | * input file first)
720 | */
721 | (void)ini_seek(&rfp, &mark);
722 | } /* if */
723 |
724 | /* Get a temporary file name to copy to. Use the existing name, but with
725 | * the last character set to a '~'.
726 | */
727 | ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE);
728 | if (!ini_openwrite(LocalBuffer, &wfp))
729 | {
730 | (void)ini_close(&rfp);
731 | return 0;
732 | } /* if */
733 | (void)ini_tell(&rfp, &mark);
734 | cachelen = 0;
735 |
736 | /* Move through the file one line at a time until a section is
737 | * matched or until EOF. Copy to temp file as it is read.
738 | */
739 | len = (Section != NULL) ? (int)_tcslen(Section) : 0;
740 | if (len > 0)
741 | {
742 | do
743 | {
744 | if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp))
745 | {
746 | /* Failed to find section, so add one to the end */
747 | flag = cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
748 | if (Key != NULL && Value != NULL)
749 | {
750 | if (!flag)
751 | (void)ini_write(INI_LINETERM, &wfp); /* force a new line behind the last line of the INI file */
752 | writesection(LocalBuffer, Section, &wfp);
753 | writekey(LocalBuffer, Key, Value, &wfp);
754 | } /* if */
755 | return close_rename(&rfp, &wfp, Filename, LocalBuffer); /* clean up and rename */
756 | } /* if */
757 | /* Copy the line from source to dest, but not if this is the section that
758 | * we are looking for and this section must be removed
759 | */
760 | sp = skipleading(LocalBuffer);
761 | ep = _tcsrchr(sp, ']');
762 | match = (*sp == '[' && ep != NULL && (int)(ep - sp - 1) == len && _tcsncmp(sp + 1, Section, len) == 0);
763 | if (!match || Key != NULL)
764 | {
765 | if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE))
766 | {
767 | cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
768 | (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
769 | cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
770 | } /* if */
771 | } /* if */
772 | } while (!match);
773 | } /* if */
774 | cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
775 | /* when deleting a section, the section head that was just found has not been
776 | * copied to the output file, but because this line was not "accumulated" in
777 | * the cache, the position in the input file was reset to the point just
778 | * before the section; this must now be skipped (again)
779 | */
780 | if (Key == NULL)
781 | {
782 | (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
783 | (void)ini_tell(&rfp, &mark);
784 | } /* if */
785 |
786 | /* Now that the section has been found, find the entry. Stop searching
787 | * upon leaving the section's area. Copy the file as it is read
788 | * and create an entry if one is not found.
789 | */
790 | len = (Key != NULL) ? (int)_tcslen(Key) : 0;
791 | for (;;)
792 | {
793 | if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp))
794 | {
795 | /* EOF without an entry so make one */
796 | flag = cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
797 | if (Key != NULL && Value != NULL)
798 | {
799 | if (!flag)
800 | (void)ini_write(INI_LINETERM, &wfp); /* force a new line behind the last line of the INI file */
801 | writekey(LocalBuffer, Key, Value, &wfp);
802 | } /* if */
803 | return close_rename(&rfp, &wfp, Filename, LocalBuffer); /* clean up and rename */
804 | } /* if */
805 | sp = skipleading(LocalBuffer);
806 | ep = _tcschr(sp, '='); /* Parse out the equal sign */
807 | if (ep == NULL)
808 | ep = _tcschr(sp, ':');
809 | match = (ep != NULL && len > 0 && (int)(skiptrailing(ep, sp) - sp) == len && _tcsncmp(sp, Key, len) == 0);
810 | if ((Key != NULL && match) || *sp == '[')
811 | break; /* found the key, or found a new section */
812 | /* copy other keys in the section */
813 | if (Key == NULL)
814 | {
815 | (void)ini_tell(&rfp, &mark); /* we are deleting the entire section, so update the read position */
816 | }
817 | else
818 | {
819 | if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE))
820 | {
821 | cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
822 | (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
823 | cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
824 | } /* if */
825 | } /* if */
826 | } /* for */
827 | /* the key was found, or we just dropped on the next section (meaning that it
828 | * wasn't found); in both cases we need to write the key, but in the latter
829 | * case, we also need to write the line starting the new section after writing
830 | * the key
831 | */
832 | flag = (*sp == '[');
833 | cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
834 | if (Key != NULL && Value != NULL)
835 | writekey(LocalBuffer, Key, Value, &wfp);
836 | /* cache_flush() reset the "read pointer" to the start of the line with the
837 | * previous key or the new section; read it again (because writekey() destroyed
838 | * the buffer)
839 | */
840 | (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
841 | if (flag)
842 | {
843 | /* the new section heading needs to be copied to the output file */
844 | cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
845 | }
846 | else
847 | {
848 | /* forget the old key line */
849 | (void)ini_tell(&rfp, &mark);
850 | } /* if */
851 | /* Copy the rest of the INI file */
852 | while (ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp))
853 | {
854 | if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE))
855 | {
856 | cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
857 | (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
858 | cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
859 | } /* if */
860 | } /* while */
861 | cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
862 | return close_rename(&rfp, &wfp, Filename, LocalBuffer); /* clean up and rename */
863 | }
864 |
865 | /* Ansi C "itoa" based on Kernighan & Ritchie's "Ansi C" book. */
866 | # define ABS(v) ((v) < 0 ? -(v) : (v))
867 |
868 | static void strreverse(TCHAR* str)
869 | {
870 | int i, j;
871 | for (i = 0, j = (int)_tcslen(str) - 1; i < j; i++, j--)
872 | {
873 | TCHAR t = str[i];
874 | str[i] = str[j];
875 | str[j] = t;
876 | } /* for */
877 | }
878 |
879 | static void long2str(long value, TCHAR* str)
880 | {
881 | int i = 0;
882 | long sign = value;
883 |
884 | /* generate digits in reverse order */
885 | do
886 | {
887 | int n = (int)(value % 10); /* get next lowest digit */
888 | str[i++] = (TCHAR)(ABS(n) + '0'); /* handle case of negative digit */
889 | } while (value /= 10); /* delete the lowest digit */
890 | if (sign < 0)
891 | str[i++] = '-';
892 | str[i] = '\0';
893 |
894 | strreverse(str);
895 | }
896 |
897 | /** ini_putl()
898 | * \param Section the name of the section to write the value in
899 | * \param Key the name of the entry to write
900 | * \param Value the value to write
901 | * \param Filename the name and full path of the .ini file to write to
902 | *
903 | * \return 1 if successful, otherwise 0
904 | */
905 | int ini_putl(const TCHAR* Section, const TCHAR* Key, long Value, const TCHAR* Filename)
906 | {
907 | TCHAR LocalBuffer[32];
908 | long2str(Value, LocalBuffer);
909 | return ini_puts(Section, Key, LocalBuffer, Filename);
910 | }
911 |
912 | # if defined INI_REAL
913 | /** ini_putf()
914 | * \param Section the name of the section to write the value in
915 | * \param Key the name of the entry to write
916 | * \param Value the value to write
917 | * \param Filename the name and full path of the .ini file to write to
918 | *
919 | * \return 1 if successful, otherwise 0
920 | */
921 | int ini_putf(const TCHAR* Section, const TCHAR* Key, INI_REAL Value, const TCHAR* Filename)
922 | {
923 | TCHAR LocalBuffer[64];
924 | ini_ftoa(LocalBuffer, Value);
925 | return ini_puts(Section, Key, LocalBuffer, Filename);
926 | }
927 | # endif /* INI_REAL */
928 | #endif /* !INI_READONLY */
929 |
--------------------------------------------------------------------------------
/source/minIni.h:
--------------------------------------------------------------------------------
1 | /* minIni - Multi-Platform INI file parser, suitable for embedded systems
2 | *
3 | * Copyright (c) CompuPhase, 2008-2017
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
6 | * use this file except in compliance with the License. You may obtain a copy
7 | * of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 | * License for the specific language governing permissions and limitations
15 | * under the License.
16 | *
17 | * Version: $Id: minIni.h 53 2015-01-18 13:35:11Z thiadmer.riemersma@gmail.com $
18 | */
19 | #ifndef MININI_H
20 | #define MININI_H
21 |
22 | #include "minIni/minGlue.h"
23 |
24 | #if (defined _UNICODE || defined __UNICODE__ || defined UNICODE) && !defined INI_ANSIONLY
25 | # include
26 | # define mTCHAR TCHAR
27 | #else
28 | /* force TCHAR to be "char", but only for minIni */
29 | # define mTCHAR char
30 | #endif
31 |
32 | #if !defined INI_BUFFERSIZE
33 | # define INI_BUFFERSIZE 512
34 | #endif
35 |
36 | #if defined __cplusplus
37 | extern "C"
38 | {
39 | #endif
40 |
41 | int ini_getbool(const mTCHAR* Section, const mTCHAR* Key, int DefValue, const mTCHAR* Filename);
42 | long ini_getl(const mTCHAR* Section, const mTCHAR* Key, long DefValue, const mTCHAR* Filename);
43 | int ini_gets(const mTCHAR* Section, const mTCHAR* Key, const mTCHAR* DefValue, mTCHAR* Buffer, int BufferSize, const mTCHAR* Filename);
44 | int ini_getsection(int idx, mTCHAR* Buffer, int BufferSize, const mTCHAR* Filename);
45 | int ini_getkey(const mTCHAR* Section, int idx, mTCHAR* Buffer, int BufferSize, const mTCHAR* Filename);
46 |
47 | #if defined INI_REAL
48 | INI_REAL ini_getf(const mTCHAR* Section, const mTCHAR* Key, INI_REAL DefValue, const mTCHAR* Filename);
49 | #endif
50 |
51 | #if !defined INI_READONLY
52 | int ini_putl(const mTCHAR* Section, const mTCHAR* Key, long Value, const mTCHAR* Filename);
53 | int ini_puts(const mTCHAR* Section, const mTCHAR* Key, const mTCHAR* Value, const mTCHAR* Filename);
54 | # if defined INI_REAL
55 | int ini_putf(const mTCHAR* Section, const mTCHAR* Key, INI_REAL Value, const mTCHAR* Filename);
56 | # endif
57 | #endif /* INI_READONLY */
58 |
59 | #if !defined INI_NOBROWSE
60 | typedef int (*INI_CALLBACK)(const mTCHAR* Section, const mTCHAR* Key, const mTCHAR* Value, void* UserData);
61 | int ini_browse(INI_CALLBACK Callback, void* UserData, const mTCHAR* Filename);
62 | #endif /* INI_NOBROWSE */
63 |
64 | #if defined __cplusplus
65 | }
66 | #endif
67 |
68 | #if defined __cplusplus
69 |
70 | # if defined __WXWINDOWS__
71 | # include "wxMinIni.h"
72 | # else
73 | # include
74 |
75 | /* The C++ class in minIni.h was contributed by Steven Van Ingelgem. */
76 | class minIni
77 | {
78 | public:
79 | minIni(const std::string& filename) : iniFilename(filename)
80 | {
81 | }
82 |
83 | bool getbool(const std::string& Section, const std::string& Key, bool DefValue = false) const
84 | {
85 | return ini_getbool(Section.c_str(), Key.c_str(), int(DefValue), iniFilename.c_str()) != 0;
86 | }
87 |
88 | long getl(const std::string& Section, const std::string& Key, long DefValue = 0) const
89 | {
90 | return ini_getl(Section.c_str(), Key.c_str(), DefValue, iniFilename.c_str());
91 | }
92 |
93 | int geti(const std::string& Section, const std::string& Key, int DefValue = 0) const
94 | {
95 | return static_cast(this->getl(Section, Key, long(DefValue)));
96 | }
97 |
98 | std::string gets(const std::string& Section, const std::string& Key, const std::string& DefValue = "") const
99 | {
100 | char buffer[INI_BUFFERSIZE];
101 | ini_gets(Section.c_str(), Key.c_str(), DefValue.c_str(), buffer, INI_BUFFERSIZE, iniFilename.c_str());
102 | return buffer;
103 | }
104 |
105 | std::string getsection(int idx) const
106 | {
107 | char buffer[INI_BUFFERSIZE];
108 | ini_getsection(idx, buffer, INI_BUFFERSIZE, iniFilename.c_str());
109 | return buffer;
110 | }
111 |
112 | std::string getkey(const std::string& Section, int idx) const
113 | {
114 | char buffer[INI_BUFFERSIZE];
115 | ini_getkey(Section.c_str(), idx, buffer, INI_BUFFERSIZE, iniFilename.c_str());
116 | return buffer;
117 | }
118 |
119 | # if defined INI_REAL
120 | INI_REAL getf(const std::string& Section, const std::string& Key, INI_REAL DefValue = 0) const
121 | {
122 | return ini_getf(Section.c_str(), Key.c_str(), DefValue, iniFilename.c_str());
123 | }
124 | # endif
125 |
126 | # if !defined INI_READONLY
127 | bool put(const std::string& Section, const std::string& Key, long Value)
128 | {
129 | return ini_putl(Section.c_str(), Key.c_str(), Value, iniFilename.c_str()) != 0;
130 | }
131 |
132 | bool put(const std::string& Section, const std::string& Key, int Value)
133 | {
134 | return ini_putl(Section.c_str(), Key.c_str(), (long)Value, iniFilename.c_str()) != 0;
135 | }
136 |
137 | bool put(const std::string& Section, const std::string& Key, bool Value)
138 | {
139 | return ini_putl(Section.c_str(), Key.c_str(), (long)Value, iniFilename.c_str()) != 0;
140 | }
141 |
142 | bool put(const std::string& Section, const std::string& Key, const std::string& Value)
143 | {
144 | return ini_puts(Section.c_str(), Key.c_str(), Value.c_str(), iniFilename.c_str()) != 0;
145 | }
146 |
147 | bool put(const std::string& Section, const std::string& Key, const char* Value)
148 | {
149 | return ini_puts(Section.c_str(), Key.c_str(), Value, iniFilename.c_str()) != 0;
150 | }
151 |
152 | # if defined INI_REAL
153 | bool put(const std::string& Section, const std::string& Key, INI_REAL Value)
154 | {
155 | return ini_putf(Section.c_str(), Key.c_str(), Value, iniFilename.c_str()) != 0;
156 | }
157 | # endif
158 |
159 | bool del(const std::string& Section, const std::string& Key)
160 | {
161 | return ini_puts(Section.c_str(), Key.c_str(), 0, iniFilename.c_str()) != 0;
162 | }
163 |
164 | bool del(const std::string& Section)
165 | {
166 | return ini_puts(Section.c_str(), 0, 0, iniFilename.c_str()) != 0;
167 | }
168 | # endif
169 |
170 | # if !defined INI_NOBROWSE
171 | bool browse(INI_CALLBACK Callback, void* UserData) const
172 | {
173 | return ini_browse(Callback, UserData, iniFilename.c_str()) != 0;
174 | }
175 | # endif
176 |
177 | private:
178 | std::string iniFilename;
179 | };
180 |
181 | # endif /* __WXWINDOWS__ */
182 | #endif /* __cplusplus */
183 |
184 | #endif /* MININI_H */
185 |
--------------------------------------------------------------------------------
/source/minIni/minGlue-FatFs.h:
--------------------------------------------------------------------------------
1 | /* Glue functions for the minIni library, based on the FatFs and Petit-FatFs
2 | * libraries, see http://elm-chan.org/fsw/ff/00index_e.html
3 | *
4 | * By CompuPhase, 2008-2012
5 | * This "glue file" is in the public domain. It is distributed without
6 | * warranties or conditions of any kind, either express or implied.
7 | *
8 | * (The FatFs and Petit-FatFs libraries are copyright by ChaN and licensed at
9 | * its own terms.)
10 | */
11 |
12 | #define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */
13 |
14 | /* You must set _USE_STRFUNC to 1 or 2 in the include file ff.h (or tff.h)
15 | * to enable the "string functions" fgets() and fputs().
16 | */
17 | #include "ff.h" /* include tff.h for Tiny-FatFs */
18 |
19 | #define INI_FILETYPE FIL
20 | #define ini_openread(filename, file) (f_open((file), (filename), FA_READ + FA_OPEN_EXISTING) == FR_OK)
21 | #define ini_openwrite(filename, file) (f_open((file), (filename), FA_WRITE + FA_CREATE_ALWAYS) == FR_OK)
22 | #define ini_close(file) (f_close(file) == FR_OK)
23 | #define ini_read(buffer, size, file) f_gets((buffer), (size), (file))
24 | #define ini_write(buffer, file) f_puts((buffer), (file))
25 | #define ini_remove(filename) (f_unlink(filename) == FR_OK)
26 |
27 | #define INI_FILEPOS DWORD
28 | #define ini_tell(file, pos) (*(pos) = f_tell((file)))
29 | #define ini_seek(file, pos) (f_lseek((file), *(pos)) == FR_OK)
30 |
31 | static int ini_rename(TCHAR* source, const TCHAR* dest)
32 | {
33 | /* Function f_rename() does not allow drive letters in the destination file */
34 | char* drive = strchr(dest, ':');
35 | drive = (drive == NULL) ? dest : drive + 1;
36 | return (f_rename(source, drive) == FR_OK);
37 | }
38 |
--------------------------------------------------------------------------------
/source/minIni/minGlue-ccs.h:
--------------------------------------------------------------------------------
1 | /* minIni glue functions for FAT library by CCS, Inc. (as provided with their
2 | * PIC MCU compiler)
3 | *
4 | * By CompuPhase, 2011-2012
5 | * This "glue file" is in the public domain. It is distributed without
6 | * warranties or conditions of any kind, either express or implied.
7 | *
8 | * (The FAT library is copyright (c) 2007 Custom Computer Services, and
9 | * licensed at its own terms.)
10 | */
11 |
12 | #define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */
13 |
14 | #ifndef FAT_PIC_C
15 | # error FAT library must be included before this module
16 | #endif
17 | #define const /* keyword not supported by CCS */
18 |
19 | #define INI_FILETYPE FILE
20 | #define ini_openread(filename, file) (fatopen((filename), "r", (file)) == GOODEC)
21 | #define ini_openwrite(filename, file) (fatopen((filename), "w", (file)) == GOODEC)
22 | #define ini_close(file) (fatclose((file)) == 0)
23 | #define ini_read(buffer, size, file) (fatgets((buffer), (size), (file)) != NULL)
24 | #define ini_write(buffer, file) (fatputs((buffer), (file)) == GOODEC)
25 | #define ini_remove(filename) (rm_file((filename)) == 0)
26 |
27 | #define INI_FILEPOS fatpos_t
28 | #define ini_tell(file, pos) (fatgetpos((file), (pos)) == 0)
29 | #define ini_seek(file, pos) (fatsetpos((file), (pos)) == 0)
30 |
31 | #ifndef INI_READONLY
32 | /* CCS FAT library lacks a rename function, so instead we copy the file to the
33 | * new name and delete the old file
34 | */
35 | static int ini_rename(char* source, char* dest)
36 | {
37 | FILE fr, fw;
38 | int n;
39 |
40 | if (fatopen(source, "r", &fr) != GOODEC)
41 | return 0;
42 | if (rm_file(dest) != 0)
43 | return 0;
44 | if (fatopen(dest, "w", &fw) != GOODEC)
45 | return 0;
46 |
47 | /* With some "insider knowledge", we can save some memory: the "source"
48 | * parameter holds a filename that was built from the "dest" parameter. It
49 | * was built in a local buffer with the size INI_BUFFERSIZE. We can reuse
50 | * this buffer for copying the file.
51 | */
52 | while (n = fatread(source, 1, INI_BUFFERSIZE, &fr))
53 | fatwrite(source, 1, n, &fw);
54 |
55 | fatclose(&fr);
56 | fatclose(&fw);
57 |
58 | /* Now we need to delete the source file. However, we have garbled the buffer
59 | * that held the filename of the source. So we need to build it again.
60 | */
61 | ini_tempname(source, dest, INI_BUFFERSIZE);
62 | return rm_file(source) == 0;
63 | }
64 | #endif
65 |
--------------------------------------------------------------------------------
/source/minIni/minGlue-efsl.h:
--------------------------------------------------------------------------------
1 | /* Glue functions for the minIni library, based on the EFS Library, see
2 | * http://www.efsl.be/
3 | *
4 | * By CompuPhase, 2008-2012
5 | * This "glue file" is in the public domain. It is distributed without
6 | * warranties or conditions of any kind, either express or implied.
7 | *
8 | * (EFSL is copyright 2005-2006 Lennart Ysboodt and Michael De Nil, and
9 | * licensed under the GPL with an exception clause for static linking.)
10 | */
11 |
12 | #define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */
13 | #define INI_LINETERM "\r\n" /* set line termination explicitly */
14 |
15 | #include "efs.h"
16 | extern EmbeddedFileSystem g_efs;
17 |
18 | #define INI_FILETYPE EmbeddedFile
19 | #define ini_openread(filename, file) (file_fopen((file), &g_efs.myFs, (char*)(filename), 'r') == 0)
20 | #define ini_openwrite(filename, file) (file_fopen((file), &g_efs.myFs, (char*)(filename), 'w') == 0)
21 | #define ini_close(file) file_fclose(file)
22 | #define ini_read(buffer, size, file) (file_read((file), (size), (buffer)) > 0)
23 | #define ini_write(buffer, file) (file_write((file), strlen(buffer), (char*)(buffer)) > 0)
24 | #define ini_remove(filename) rmfile(&g_efs.myFs, (char*)(filename))
25 |
26 | #define INI_FILEPOS euint32
27 | #define ini_tell(file, pos) (*(pos) = (file)->FilePtr))
28 | #define ini_seek(file, pos) file_setpos((file), (*pos))
29 |
30 | #if !defined INI_READONLY
31 | /* EFSL lacks a rename function, so instead we copy the file to the new name
32 | * and delete the old file
33 | */
34 | static int ini_rename(char* source, const char* dest)
35 | {
36 | EmbeddedFile fr, fw;
37 | int n;
38 |
39 | if (file_fopen(&fr, &g_efs.myFs, source, 'r') != 0)
40 | return 0;
41 | if (rmfile(&g_efs.myFs, (char*)dest) != 0)
42 | return 0;
43 | if (file_fopen(&fw, &g_efs.myFs, (char*)dest, 'w') != 0)
44 | return 0;
45 |
46 | /* With some "insider knowledge", we can save some memory: the "source"
47 | * parameter holds a filename that was built from the "dest" parameter. It
48 | * was built in buffer and this buffer has the size INI_BUFFERSIZE. We can
49 | * reuse this buffer for copying the file.
50 | */
51 | while (n = file_read(&fr, INI_BUFFERSIZE, source))
52 | file_write(&fw, n, source);
53 |
54 | file_fclose(&fr);
55 | file_fclose(&fw);
56 |
57 | /* Now we need to delete the source file. However, we have garbled the buffer
58 | * that held the filename of the source. So we need to build it again.
59 | */
60 | ini_tempname(source, dest, INI_BUFFERSIZE);
61 | return rmfile(&g_efs.myFs, source) == 0;
62 | }
63 | #endif
64 |
--------------------------------------------------------------------------------
/source/minIni/minGlue-ffs.h:
--------------------------------------------------------------------------------
1 | /* Glue functions for the minIni library, based on the "FAT Filing System"
2 | * library by embedded-code.com
3 | *
4 | * By CompuPhase, 2008-2012
5 | * This "glue file" is in the public domain. It is distributed without
6 | * warranties or conditions of any kind, either express or implied.
7 | *
8 | * (The "FAT Filing System" library itself is copyright embedded-code.com, and
9 | * licensed at its own terms.)
10 | */
11 |
12 | #define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */
13 | #include
14 |
15 | #define INI_FILETYPE FFS_FILE*
16 | #define ini_openread(filename, file) ((*(file) = ffs_fopen((filename), "r")) != NULL)
17 | #define ini_openwrite(filename, file) ((*(file) = ffs_fopen((filename), "w")) != NULL)
18 | #define ini_close(file) (ffs_fclose(*(file)) == 0)
19 | #define ini_read(buffer, size, file) (ffs_fgets((buffer), (size), *(file)) != NULL)
20 | #define ini_write(buffer, file) (ffs_fputs((buffer), *(file)) >= 0)
21 | #define ini_rename(source, dest) (ffs_rename((source), (dest)) == 0)
22 | #define ini_remove(filename) (ffs_remove(filename) == 0)
23 |
24 | #define INI_FILEPOS long
25 | #define ini_tell(file, pos) (ffs_fgetpos(*(file), (pos)) == 0)
26 | #define ini_seek(file, pos) (ffs_fsetpos(*(file), (pos)) == 0)
27 |
--------------------------------------------------------------------------------
/source/minIni/minGlue-mdd.h:
--------------------------------------------------------------------------------
1 | /* minIni glue functions for Microchip's "Memory Disk Drive" file system
2 | * library, as presented in Microchip application note AN1045.
3 | *
4 | * By CompuPhase, 2011-2014
5 | * This "glue file" is in the public domain. It is distributed without
6 | * warranties or conditions of any kind, either express or implied.
7 | *
8 | * (The "Microchip Memory Disk Drive File System" is copyright (c) Microchip
9 | * Technology Incorporated, and licensed at its own terms.)
10 | */
11 |
12 | #define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */
13 |
14 | #include "MDD File System\fsio.h"
15 | #include
16 |
17 | #define INI_FILETYPE FSFILE*
18 | #define ini_openread(filename, file) ((*(file) = FSfopen((filename), FS_READ)) != NULL)
19 | #define ini_openwrite(filename, file) ((*(file) = FSfopen((filename), FS_WRITE)) != NULL)
20 | #define ini_openrewrite(filename, file) ((*(file) = fopen((filename), FS_READPLUS)) != NULL)
21 | #define ini_close(file) (FSfclose(*(file)) == 0)
22 | #define ini_write(buffer, file) (FSfwrite((buffer), 1, strlen(buffer), (*file)) > 0)
23 | #define ini_remove(filename) (FSremove((filename)) == 0)
24 |
25 | #define INI_FILEPOS long int
26 | #define ini_tell(file, pos) (*(pos) = FSftell(*(file)))
27 | #define ini_seek(file, pos) (FSfseek(*(file), *(pos), SEEK_SET) == 0)
28 |
29 | /* Since the Memory Disk Drive file system library reads only blocks of files,
30 | * the function to read a text line does so by "over-reading" a block of the
31 | * of the maximum size and truncating it behind the end-of-line.
32 | */
33 | static int ini_read(char* buffer, int size, INI_FILETYPE* file)
34 | {
35 | size_t numread = size;
36 | char* eol;
37 |
38 | if ((numread = FSfread(buffer, 1, size, *file)) == 0)
39 | return 0; /* at EOF */
40 | if ((eol = strchr(buffer, '\n')) == NULL)
41 | eol = strchr(buffer, '\r');
42 | if (eol != NULL)
43 | {
44 | /* terminate the buffer */
45 | *++eol = '\0';
46 | /* "unread" the data that was read too much */
47 | FSfseek(*file, -(int)(numread - (size_t)(eol - buffer)), SEEK_CUR);
48 | } /* if */
49 | return 1;
50 | }
51 |
52 | #ifndef INI_READONLY
53 | static int ini_rename(const char* source, const char* dest)
54 | {
55 | FSFILE* ftmp = FSfopen((source), FS_READ);
56 | FSrename((dest), ftmp);
57 | return FSfclose(ftmp) == 0;
58 | }
59 | #endif
60 |
--------------------------------------------------------------------------------
/source/minIni/minGlue-stdio.h:
--------------------------------------------------------------------------------
1 | /* Glue functions for the minIni library, based on the C/C++ stdio library
2 | *
3 | * Or better said: this file contains macros that maps the function interface
4 | * used by minIni to the standard C/C++ file I/O functions.
5 | *
6 | * By CompuPhase, 2008-2014
7 | * This "glue file" is in the public domain. It is distributed without
8 | * warranties or conditions of any kind, either express or implied.
9 | */
10 |
11 | /* map required file I/O types and functions to the standard C library */
12 | #include
13 |
14 | #define INI_FILETYPE FILE*
15 | #define ini_openread(filename, file) ((*(file) = fopen((filename), "rb")) != NULL)
16 | #define ini_openwrite(filename, file) ((*(file) = fopen((filename), "wb")) != NULL)
17 | #define ini_openrewrite(filename, file) ((*(file) = fopen((filename), "r+b")) != NULL)
18 | #define ini_close(file) (fclose(*(file)) == 0)
19 | #define ini_read(buffer, size, file) (fgets((buffer), (size), *(file)) != NULL)
20 | #define ini_write(buffer, file) (fputs((buffer), *(file)) >= 0)
21 | #define ini_rename(source, dest) (rename((source), (dest)) == 0)
22 | #define ini_remove(filename) (remove(filename) == 0)
23 |
24 | #define INI_FILEPOS long int
25 | #define ini_tell(file, pos) (*(pos) = ftell(*(file)))
26 | #define ini_seek(file, pos) (fseek(*(file), *(pos), SEEK_SET) == 0)
27 |
28 | /* for floating-point support, define additional types and functions */
29 | #define INI_REAL float
30 | #define ini_ftoa(string, value) sprintf((string), "%f", (value))
31 | #define ini_atof(string) (INI_REAL) strtod((string), NULL)
32 |
--------------------------------------------------------------------------------
/source/minIni/minGlue.h:
--------------------------------------------------------------------------------
1 | /* Glue functions for the minIni library, based on the C/C++ stdio library
2 | *
3 | * Or better said: this file contains macros that maps the function interface
4 | * used by minIni to the standard C/C++ file I/O functions.
5 | *
6 | * By CompuPhase, 2008-2014
7 | * This "glue file" is in the public domain. It is distributed without
8 | * warranties or conditions of any kind, either express or implied.
9 | */
10 |
11 | /* map required file I/O types and functions to the standard C library */
12 | #include
13 |
14 | #define INI_FILETYPE FILE*
15 | #define ini_openread(filename, file) ((*(file) = fopen((filename), "rb")) != NULL)
16 | #define ini_openwrite(filename, file) ((*(file) = fopen((filename), "wb")) != NULL)
17 | #define ini_openrewrite(filename, file) ((*(file) = fopen((filename), "r+b")) != NULL)
18 | #define ini_close(file) (fclose(*(file)) == 0)
19 | #define ini_read(buffer, size, file) (fgets((buffer), (size), *(file)) != NULL)
20 | #define ini_write(buffer, file) (fputs((buffer), *(file)) >= 0)
21 | #define ini_rename(source, dest) (rename((source), (dest)) == 0)
22 | #define ini_remove(filename) (remove(filename) == 0)
23 |
24 | #define INI_FILEPOS long int
25 | #define ini_tell(file, pos) (*(pos) = ftell(*(file)))
26 | #define ini_seek(file, pos) (fseek(*(file), *(pos), SEEK_SET) == 0)
27 |
28 | /* for floating-point support, define additional types and functions */
29 | #define INI_REAL float
30 | #define ini_ftoa(string, value) sprintf((string), "%f", (value))
31 | #define ini_atof(string) (INI_REAL) strtod((string), NULL)
32 |
--------------------------------------------------------------------------------
/source/minIni/wxMinIni.h:
--------------------------------------------------------------------------------
1 | /* minIni - Multi-Platform INI file parser, wxWidgets interface
2 | *
3 | * Copyright (c) CompuPhase, 2008-2012
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
6 | * use this file except in compliance with the License. You may obtain a copy
7 | * of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 | * License for the specific language governing permissions and limitations
15 | * under the License.
16 | *
17 | * Version: $Id: wxMinIni.h 44 2012-01-04 15:52:56Z thiadmer.riemersma@gmail.com $
18 | */
19 | #ifndef WXMININI_H
20 | #define WXMININI_H
21 |
22 | #include "minIni.h"
23 | #include
24 |
25 | class minIni
26 | {
27 | public:
28 | minIni(const wxString& filename) : iniFilename(filename)
29 | {
30 | }
31 |
32 | bool getbool(const wxString& Section, const wxString& Key, bool DefValue = false) const
33 | {
34 | return ini_getbool(Section.utf8_str(), Key.utf8_str(), int(DefValue), iniFilename.utf8_str()) != 0;
35 | }
36 |
37 | long getl(const wxString& Section, const wxString& Key, long DefValue = 0) const
38 | {
39 | return ini_getl(Section.utf8_str(), Key.utf8_str(), DefValue, iniFilename.utf8_str());
40 | }
41 |
42 | int geti(const wxString& Section, const wxString& Key, int DefValue = 0) const
43 | {
44 | return static_cast(ini_getl(Section.utf8_str(), Key.utf8_str(), (long)DefValue, iniFilename.utf8_str()));
45 | }
46 |
47 | wxString gets(const wxString& Section, const wxString& Key, const wxString& DefValue = wxT("")) const
48 | {
49 | char buffer[INI_BUFFERSIZE];
50 | ini_gets(Section.utf8_str(), Key.utf8_str(), DefValue.utf8_str(), buffer, INI_BUFFERSIZE, iniFilename.utf8_str());
51 | wxString result = wxString::FromUTF8(buffer);
52 | return result;
53 | }
54 |
55 | wxString getsection(int idx) const
56 | {
57 | char buffer[INI_BUFFERSIZE];
58 | ini_getsection(idx, buffer, INI_BUFFERSIZE, iniFilename.utf8_str());
59 | wxString result = wxString::FromUTF8(buffer);
60 | return result;
61 | }
62 |
63 | wxString getkey(const wxString& Section, int idx) const
64 | {
65 | char buffer[INI_BUFFERSIZE];
66 | ini_getkey(Section.utf8_str(), idx, buffer, INI_BUFFERSIZE, iniFilename.utf8_str());
67 | wxString result = wxString::FromUTF8(buffer);
68 | return result;
69 | }
70 |
71 | #if defined INI_REAL
72 | INI_REAL getf(const wxString& Section, wxString& Key, INI_REAL DefValue = 0) const
73 | {
74 | return ini_getf(Section.utf8_str(), Key.utf8_str(), DefValue, iniFilename.utf8_str());
75 | }
76 | #endif
77 |
78 | #if !defined INI_READONLY
79 | bool put(const wxString& Section, const wxString& Key, long Value) const
80 | {
81 | return ini_putl(Section.utf8_str(), Key.utf8_str(), Value, iniFilename.utf8_str()) != 0;
82 | }
83 |
84 | bool put(const wxString& Section, const wxString& Key, int Value) const
85 | {
86 | return ini_putl(Section.utf8_str(), Key.utf8_str(), (long)Value, iniFilename.utf8_str()) != 0;
87 | }
88 |
89 | bool put(const wxString& Section, const wxString& Key, bool Value) const
90 | {
91 | return ini_putl(Section.utf8_str(), Key.utf8_str(), (long)Value, iniFilename.utf8_str()) != 0;
92 | }
93 |
94 | bool put(const wxString& Section, const wxString& Key, const wxString& Value) const
95 | {
96 | return ini_puts(Section.utf8_str(), Key.utf8_str(), Value.utf8_str(), iniFilename.utf8_str()) != 0;
97 | }
98 |
99 | bool put(const wxString& Section, const wxString& Key, const char* Value) const
100 | {
101 | return ini_puts(Section.utf8_str(), Key.utf8_str(), Value, iniFilename.utf8_str()) != 0;
102 | }
103 |
104 | # if defined INI_REAL
105 | bool put(const wxString& Section, const wxString& Key, INI_REAL Value) const
106 | {
107 | return ini_putf(Section.utf8_str(), Key.utf8_str(), Value, iniFilename.utf8_str()) != 0;
108 | }
109 | # endif
110 |
111 | bool del(const wxString& Section, const wxString& Key) const
112 | {
113 | return ini_puts(Section.utf8_str(), Key.utf8_str(), 0, iniFilename.utf8_str()) != 0;
114 | }
115 |
116 | bool del(const wxString& Section) const
117 | {
118 | return ini_puts(Section.utf8_str(), 0, 0, iniFilename.utf8_str()) != 0;
119 | }
120 | #endif
121 |
122 | private:
123 | wxString iniFilename;
124 | };
125 |
126 | #endif /* WXMININI_H */
127 |
--------------------------------------------------------------------------------
/source/util.c:
--------------------------------------------------------------------------------
1 | #include "util.h"
2 | #include "led.h"
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 |
9 | #include "minIni.h"
10 | #include
11 |
12 | static bool inputThreadRunning = true;
13 | static bool paused = false;
14 | static Mutex pausedMutex = 0;
15 | static Thread pauseThread;
16 | static HidNpadButton comboKeys[8] = {0};
17 | static PadState pad = {0};
18 |
19 | bool isHidHandheld()
20 | {
21 | return padIsHandheld(&pad);
22 | }
23 |
24 | void initPads()
25 | {
26 | padInitializeAny(&pad);
27 | }
28 |
29 | void inputPoller()
30 | {
31 | do
32 | {
33 | padUpdate(&pad);
34 | u64 kHeld = padGetButtons(&pad);
35 |
36 | u64 keyCombo = 0;
37 | for (u8 i = 0; i != sizearray(comboKeys); ++i)
38 | keyCombo |= comboKeys[i];
39 |
40 | static bool keyComboPressed = false;
41 |
42 | if ((kHeld & keyCombo) == keyCombo)
43 | {
44 | if (!keyComboPressed)
45 | {
46 | keyComboPressed = true;
47 | setPaused(!isPaused());
48 | }
49 | }
50 | else
51 | {
52 | keyComboPressed = false;
53 | }
54 | svcSleepThread(1e+8);
55 | } while (inputThreadRunning);
56 | }
57 |
58 | const char* buttons[] = {
59 | "A",
60 | "B",
61 | "X",
62 | "Y",
63 | "LS",
64 | "RS",
65 | "L",
66 | "R",
67 | "ZL",
68 | "ZR",
69 | "PLUS",
70 | "MINUS",
71 | "DLEFT",
72 | "DUP",
73 | "DRIGHT",
74 | "DDOWN",
75 | };
76 |
77 | HidNpadButton GetKey(const char* text)
78 | {
79 | for (u8 i = 0; i != sizearray(buttons); ++i)
80 | {
81 | if (strcmp(text, buttons[i]) == 0)
82 | {
83 | return BIT(i);
84 | }
85 | }
86 | return 0;
87 | }
88 |
89 | Result pauseInit()
90 | {
91 | Result rc;
92 | mutexLock(&pausedMutex);
93 |
94 | FILE* should_pause_file = fopen("/config/sys-ftpd/ftpd_paused", "r");
95 | if (should_pause_file != NULL)
96 | {
97 | paused = true;
98 | fclose(should_pause_file);
99 | }
100 |
101 | {
102 | char buffer[128];
103 | ini_gets("Pause", "keycombo:", "PLUS+MINUS+X", buffer, 128, CONFIGPATH);
104 | char* token = strtok(buffer, "+ ");
105 | int i = 0;
106 | while (token != NULL && i != sizearray(comboKeys))
107 | {
108 | comboKeys[i++] = GetKey(token);
109 | token = strtok(NULL, "+ ");
110 | };
111 | }
112 |
113 | inputThreadRunning = true;
114 |
115 | rc = threadCreate(&pauseThread, inputPoller, NULL, NULL, 0x1000, 0x3B, -2);
116 | if (R_FAILED(rc))
117 | goto exit;
118 |
119 | rc = threadStart(&pauseThread);
120 | if (R_FAILED(rc))
121 | goto exit;
122 |
123 | exit:
124 | mutexUnlock(&pausedMutex);
125 | return rc;
126 | }
127 |
128 | void pauseExit()
129 | {
130 | inputThreadRunning = false;
131 | threadWaitForExit(&pauseThread);
132 | threadClose(&pauseThread);
133 | }
134 |
135 | bool isPaused()
136 | {
137 | mutexLock(&pausedMutex);
138 | bool ret = paused;
139 | mutexUnlock(&pausedMutex);
140 | return ret;
141 | }
142 |
143 | void setPaused(bool newPaused)
144 | {
145 | mutexLock(&pausedMutex);
146 | paused = newPaused;
147 | if (paused)
148 | {
149 | FILE* should_pause_file = fopen("/config/sys-ftpd/ftpd_paused", "w");
150 | fclose(should_pause_file);
151 | flash_led_pause();
152 | }
153 | else
154 | {
155 | unlink("/config/sys-ftpd/ftpd_paused");
156 | flash_led_unpause();
157 | }
158 | mutexUnlock(&pausedMutex);
159 | }
160 |
--------------------------------------------------------------------------------
/source/util.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #include
3 |
4 | #define sizearray(a) (sizeof(a) / sizeof((a)[0]))
5 |
6 | #define TITLE_ID 0x420000000000000E
7 | #define CONFIGPATH "/config/sys-ftpd/config.ini"
8 |
9 | #define R_ASSERT(res_expr) \
10 | ({ \
11 | const Result rc = (res_expr); \
12 | if (R_FAILED(rc)) \
13 | { \
14 | fatalThrow(rc); \
15 | } \
16 | })
17 |
18 | Result pauseInit();
19 | void pauseExit();
20 | bool isPaused();
21 | void setPaused(bool newPaused);
22 | bool isHidHandheld();
23 | void initPads();
--------------------------------------------------------------------------------
/sys-ftpd.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "sys-ftpd",
3 | "version": "1.0.5",
4 | "program_id": "0x420000000000000E",
5 | "program_id_range_min": "0x420000000000000E",
6 | "program_id_range_max": "0x420000000000000E",
7 | "main_thread_stack_size": "0x00004000",
8 | "main_thread_priority": 49,
9 | "default_cpu_id": 3,
10 | "process_category": 0,
11 | "is_retail": true,
12 | "pool_partition": 2,
13 | "is_64_bit": true,
14 | "signature_key_generation": 0,
15 | "address_space_type": 3,
16 | "optimize_memory_allocation": false,
17 | "disable_device_address_space_merge": true,
18 | "enable_alias_region_extra_size": false,
19 | "prevent_code_reads": false,
20 | "system_resource_size": "0",
21 | "filesystem_access": {
22 | "permissions": "0xffffffffffffffff"
23 | },
24 | "service_access": ["*"],
25 | "service_host": ["*"],
26 | "kernel_capabilities": [{
27 | "type": "kernel_flags",
28 | "value": {
29 | "highest_thread_priority": 63,
30 | "lowest_thread_priority": 24,
31 | "lowest_cpu_id": 3,
32 | "highest_cpu_id": 3
33 | }
34 | }, {
35 | "type": "syscalls",
36 | "value": {
37 | "svcUnknown": "0x00",
38 | "svcSetHeapSize": "0x01",
39 | "svcSetMemoryPermission": "0x02",
40 | "svcSetMemoryAttribute": "0x03",
41 | "svcMapMemory": "0x04",
42 | "svcUnmapMemory": "0x05",
43 | "svcQueryMemory": "0x06",
44 | "svcExitProcess": "0x07",
45 | "svcCreateThread": "0x08",
46 | "svcStartThread": "0x09",
47 | "svcExitThread": "0x0a",
48 | "svcSleepThread": "0x0b",
49 | "svcGetThreadPriority": "0x0c",
50 | "svcSetThreadPriority": "0x0d",
51 | "svcGetThreadCoreMask": "0x0e",
52 | "svcSetThreadCoreMask": "0x0f",
53 | "svcGetCurrentProcessorNumber": "0x10",
54 | "svcSignalEvent": "0x11",
55 | "svcClearEvent": "0x12",
56 | "svcMapSharedMemory": "0x13",
57 | "svcUnmapSharedMemory": "0x14",
58 | "svcCreateTransferMemory": "0x15",
59 | "svcCloseHandle": "0x16",
60 | "svcResetSignal": "0x17",
61 | "svcWaitSynchronization": "0x18",
62 | "svcCancelSynchronization": "0x19",
63 | "svcArbitrateLock": "0x1a",
64 | "svcArbitrateUnlock": "0x1b",
65 | "svcWaitProcessWideKeyAtomic": "0x1c",
66 | "svcSignalProcessWideKey": "0x1d",
67 | "svcGetSystemTick": "0x1e",
68 | "svcConnectToNamedPort": "0x1f",
69 | "svcSendSyncRequestLight": "0x20",
70 | "svcSendSyncRequest": "0x21",
71 | "svcSendSyncRequestWithUserBuffer": "0x22",
72 | "svcSendAsyncRequestWithUserBuffer": "0x23",
73 | "svcGetProcessId": "0x24",
74 | "svcGetThreadId": "0x25",
75 | "svcBreak": "0x26",
76 | "svcOutputDebugString": "0x27",
77 | "svcReturnFromException": "0x28",
78 | "svcGetInfo": "0x29",
79 | "svcFlushEntireDataCache": "0x2a",
80 | "svcFlushDataCache": "0x2b",
81 | "svcMapPhysicalMemory": "0x2c",
82 | "svcUnmapPhysicalMemory": "0x2d",
83 | "svcGetFutureThreadInfo": "0x2e",
84 | "svcGetLastThreadInfo": "0x2f",
85 | "svcGetResourceLimitLimitValue": "0x30",
86 | "svcGetResourceLimitCurrentValue": "0x31",
87 | "svcSetThreadActivity": "0x32",
88 | "svcGetThreadContext3": "0x33",
89 | "svcWaitForAddress": "0x34",
90 | "svcSignalToAddress": "0x35",
91 | "svcUnknown": "0x36",
92 | "svcUnknown": "0x37",
93 | "svcUnknown": "0x38",
94 | "svcUnknown": "0x39",
95 | "svcUnknown": "0x3a",
96 | "svcUnknown": "0x3b",
97 | "svcDumpInfo": "0x3c",
98 | "svcDumpInfoNew": "0x3d",
99 | "svcUnknown": "0x3e",
100 | "svcUnknown": "0x3f",
101 | "svcCreateSession": "0x40",
102 | "svcAcceptSession": "0x41",
103 | "svcReplyAndReceiveLight": "0x42",
104 | "svcReplyAndReceive": "0x43",
105 | "svcReplyAndReceiveWithUserBuffer": "0x44",
106 | "svcCreateEvent": "0x45",
107 | "svcUnknown": "0x46",
108 | "svcUnknown": "0x47",
109 | "svcMapPhysicalMemoryUnsafe": "0x48",
110 | "svcUnmapPhysicalMemoryUnsafe": "0x49",
111 | "svcSetUnsafeLimit": "0x4a",
112 | "svcCreateCodeMemory": "0x4b",
113 | "svcControlCodeMemory": "0x4c",
114 | "svcSleepSystem": "0x4d",
115 | "svcReadWriteRegister": "0x4e",
116 | "svcSetProcessActivity": "0x4f",
117 | "svcCreateSharedMemory": "0x50",
118 | "svcMapTransferMemory": "0x51",
119 | "svcUnmapTransferMemory": "0x52",
120 | "svcCreateInterruptEvent": "0x53",
121 | "svcQueryPhysicalAddress": "0x54",
122 | "svcQueryIoMapping": "0x55",
123 | "svcCreateDeviceAddressSpace": "0x56",
124 | "svcAttachDeviceAddressSpace": "0x57",
125 | "svcDetachDeviceAddressSpace": "0x58",
126 | "svcMapDeviceAddressSpaceByForce": "0x59",
127 | "svcMapDeviceAddressSpaceAligned": "0x5a",
128 | "svcMapDeviceAddressSpace": "0x5b",
129 | "svcUnmapDeviceAddressSpace": "0x5c",
130 | "svcInvalidateProcessDataCache": "0x5d",
131 | "svcStoreProcessDataCache": "0x5e",
132 | "svcFlushProcessDataCache": "0x5f",
133 | "svcDebugActiveProcess": "0x60",
134 | "svcBreakDebugProcess": "0x61",
135 | "svcTerminateDebugProcess": "0x62",
136 | "svcGetDebugEvent": "0x63",
137 | "svcContinueDebugEvent": "0x64",
138 | "svcGetProcessList": "0x65",
139 | "svcGetThreadList": "0x66",
140 | "svcGetDebugThreadContext": "0x67",
141 | "svcSetDebugThreadContext": "0x68",
142 | "svcQueryDebugProcessMemory": "0x69",
143 | "svcReadDebugProcessMemory": "0x6a",
144 | "svcWriteDebugProcessMemory": "0x6b",
145 | "svcSetHardwareBreakPoint": "0x6c",
146 | "svcGetDebugThreadParam": "0x6d",
147 | "svcUnknown": "0x6e",
148 | "svcGetSystemInfo": "0x6f",
149 | "svcCreatePort": "0x70",
150 | "svcManageNamedPort": "0x71",
151 | "svcConnectToPort": "0x72",
152 | "svcSetProcessMemoryPermission": "0x73",
153 | "svcMapProcessMemory": "0x74",
154 | "svcUnmapProcessMemory": "0x75",
155 | "svcQueryProcessMemory": "0x76",
156 | "svcMapProcessCodeMemory": "0x77",
157 | "svcUnmapProcessCodeMemory": "0x78",
158 | "svcCreateProcess": "0x79",
159 | "svcStartProcess": "0x7a",
160 | "svcTerminateProcess": "0x7b",
161 | "svcGetProcessInfo": "0x7c",
162 | "svcCreateResourceLimit": "0x7d",
163 | "svcSetResourceLimitLimitValue": "0x7e",
164 | "svcCallSecureMonitor": "0x7f"
165 | }
166 | }, {
167 | "type": "min_kernel_version",
168 | "value": "0x0060"
169 | }, {
170 | "type": "handle_table_size",
171 | "value": 1023
172 | }, {
173 | "type": "debug_flags",
174 | "value": {
175 | "allow_debug": false,
176 | "force_debug": true,
177 | "force_debug_prod": false
178 | }
179 | }]
180 | }
--------------------------------------------------------------------------------