├── .github
└── workflows
│ └── ccpp.yml
├── .gitignore
├── LICENSE
├── Makefile
├── README.md
└── src
├── .cproject
├── .project
├── Speedtest.c
├── Speedtest.h
├── SpeedtestConfig.c
├── SpeedtestConfig.h
├── SpeedtestDownloadTest.c
├── SpeedtestDownloadTest.h
├── SpeedtestLatencyTest.c
├── SpeedtestLatencyTest.h
├── SpeedtestServers.c
├── SpeedtestServers.h
├── SpeedtestUploadTest.c
├── SpeedtestUploadTest.h
├── http.c
├── http.h
├── url.c
└── url.h
/.github/workflows/ccpp.yml:
--------------------------------------------------------------------------------
1 | name: C/C++ CI
2 |
3 | on: [push]
4 |
5 | jobs:
6 | build:
7 |
8 | runs-on: ubuntu-latest
9 |
10 | steps:
11 | - uses: actions/checkout@v1
12 | - name: make
13 | run: make
14 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Object files
2 | *.o
3 | *.ko
4 | # Libraries
5 | *.lib
6 | *.a
7 | # Shared objects (inc. Windows DLLs)
8 | *.dll
9 | *.so
10 | *.so.*
11 | *.dylib
12 | # Executables
13 | *.exe
14 | *.out
15 | *.app
16 | SpeedTestC
17 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
341 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | # For FreshTomato builds, ignored in other cases
2 | -include ../common.mak
3 |
4 | OPENSSL_CFLAGS = -DOPENSSL -DURL_PROTOCOL='"https"'
5 | OPENSSL_LIBS = -lssl -lcrypto
6 |
7 | CFLAGS = -Os -Wall -std=c99 $(OPENSSL_CFLAGS) $(EXTRACFLAGS)
8 | LDFLAGS =
9 | LIBS := -lm -lpthread $(OPENSSL_LIBS)
10 |
11 | ifdef TOMATO_BUILD
12 | LIBS += -L$(TOP)/openssl
13 | CFLAGS += -I $(TOP)/openssl/include
14 | endif
15 |
16 | OBJDIR = .
17 | SRCDIR = src
18 | SOURCES := $(wildcard $(SRCDIR)/*.c)
19 |
20 | OBJS := $(SOURCES:$(SRCDIR)/%.c=$(OBJDIR)/%.o)
21 |
22 | all: SpeedTestC
23 |
24 | SpeedTestC: $(OBJS)
25 | @echo " [SpeedTestC] CC $@"
26 | @$(CC) -o $@ $(OBJS) $(LIBS)
27 |
28 | $(SIZECHECK)
29 | $(CPTMP)
30 |
31 |
32 | install:
33 | @echo " [SpeedTestC] Installing to $(INSTALLDIR)"
34 | @install -D SpeedTestC $(INSTALLDIR)/usr/bin/SpeedTestC
35 | @$(STRIP) $(INSTALLDIR)/usr/bin/SpeedTestC
36 | @chmod 0500 $(INSTALLDIR)/usr/bin/SpeedTestC
37 |
38 | clean:
39 | rm -f SpeedTestC *.o .*.depend
40 |
41 | size: SpeedTestC
42 | mipsel-uclibc-nm --print-size --size-sort SpeedTestC
43 |
44 | $(OBJS): $(OBJDIR)/%.o : $(SRCDIR)/%.c
45 | @echo " [SpeedTestC] CC $@"
46 | @$(CC) $(CFLAGS) -c $< -o $@
47 |
48 | .%.depend: %.c
49 | @$(CC) $(CFLAGS) -M $< > $@
50 |
51 | -include $(OBJS:%.o=.%.depend)
52 |
53 | test: SpeedTestC
54 | valgrind --leak-check=full --show-leak-kinds=all ./SpeedTestC --server http://speedtest.skynet.net.pl/speedtest/upload.php
55 | valgrind --leak-check=full --show-leak-kinds=all ./SpeedTestC
56 |
57 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Client for SpeedTest.net infrastructure written in pure C99 standard using only POSIX and OpenSSL libraries.
2 |
3 | Main purpose for this project was to deliver client for Speedtest.net
4 | infrastructure for embedded devices.
5 |
6 | All application is written in pure C99 standard (it should compile with C90
7 | too), without using any external libraries - only POSIX and OpenSSL is used.
8 |
9 | Code is not perfect, and it has a few bugs, but it is stable and it works.
10 |
11 | Big thanks for Luke Graham for his http function.
12 |
13 | To compile, just type make.
14 |
15 | If you want to build it for FreshTomato Firmware, copy this repository into
16 | release//router
17 |
18 | and add following line somewhere at beginning of Makefile inside router directory:
19 |
20 | obj-y += SpeedTestC
21 |
--------------------------------------------------------------------------------
/src/.cproject:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/src/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | Speedtest_C
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.cdt.managedbuilder.core.genmakebuilder
10 | clean,full,incremental,
11 |
12 |
13 | ?name?
14 |
15 |
16 |
17 | org.eclipse.cdt.make.core.append_environment
18 | true
19 |
20 |
21 | org.eclipse.cdt.make.core.autoBuildTarget
22 | all
23 |
24 |
25 | org.eclipse.cdt.make.core.buildArguments
26 |
27 |
28 |
29 | org.eclipse.cdt.make.core.buildCommand
30 | make
31 |
32 |
33 | org.eclipse.cdt.make.core.buildLocation
34 | /home/m.obrembski/SpeedTestC/build
35 |
36 |
37 | org.eclipse.cdt.make.core.cleanBuildTarget
38 | clean
39 |
40 |
41 | org.eclipse.cdt.make.core.contents
42 | org.eclipse.cdt.make.core.activeConfigSettings
43 |
44 |
45 | org.eclipse.cdt.make.core.enableAutoBuild
46 | false
47 |
48 |
49 | org.eclipse.cdt.make.core.enableCleanBuild
50 | true
51 |
52 |
53 | org.eclipse.cdt.make.core.enableFullBuild
54 | true
55 |
56 |
57 | org.eclipse.cdt.make.core.fullBuildTarget
58 | all
59 |
60 |
61 | org.eclipse.cdt.make.core.stopOnError
62 | true
63 |
64 |
65 | org.eclipse.cdt.make.core.useDefaultBuildCmd
66 | true
67 |
68 |
69 |
70 |
71 | org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder
72 | full,incremental,
73 |
74 |
75 |
76 |
77 | org.tizen.nativecpp.apichecker.core.builder
78 |
79 |
80 |
81 |
82 |
83 | org.eclipse.cdt.core.cnature
84 | org.eclipse.cdt.core.ccnature
85 | org.eclipse.cdt.managedbuilder.core.managedBuildNature
86 | org.eclipse.cdt.managedbuilder.core.ScannerConfigNature
87 | org.tizen.nativecpp.apichecker.core.tizenCppNature
88 |
89 |
90 |
--------------------------------------------------------------------------------
/src/Speedtest.c:
--------------------------------------------------------------------------------
1 | /*
2 | Main program.
3 |
4 | Michał Obrembski (byku@byku.com.pl)
5 | */
6 | #include "http.h"
7 | #include "SpeedtestConfig.h"
8 | #include "SpeedtestServers.h"
9 | #include "Speedtest.h"
10 | #include "SpeedtestLatencyTest.h"
11 | #include "SpeedtestDownloadTest.h"
12 | #include "SpeedtestUploadTest.h"
13 |
14 | #include
15 | #include
16 | #include
17 | #include
18 |
19 | // Global variables
20 | SPEEDTESTSERVER_T **serverList;
21 | int serverCount;
22 | unsigned totalDownloadTestCount;
23 | char *downloadUrl;
24 | char *tmpUrl;
25 | char *uploadUrl;
26 | char *latencyUrl;
27 | unsigned long totalTransfered;
28 | unsigned long totalToBeTransfered;
29 | int randomizeBestServers;
30 | int lowestLatencyServers;
31 |
32 | // strdup isnt a C99 function, so we need it to define itself
33 | char *strdup(const char *str)
34 | {
35 | int n = strlen(str) + 1;
36 | char *dup = malloc(n);
37 | if(dup)
38 | {
39 | strcpy(dup, str);
40 | }
41 | return dup;
42 | }
43 |
44 | int sortServersDistance(SPEEDTESTSERVER_T **srv1, SPEEDTESTSERVER_T **srv2)
45 | {
46 | return((*srv1)->distance - (*srv2)->distance);
47 | }
48 |
49 | int sortServersLatency(SPEEDTESTSERVER_T **srv1, SPEEDTESTSERVER_T **srv2)
50 | {
51 | return (*srv1)->latency - (*srv2)->latency;
52 | }
53 |
54 | float getElapsedTime(struct timeval tval_start) {
55 | struct timeval tval_end, tval_diff;
56 | gettimeofday(&tval_end, NULL);
57 | tval_diff.tv_sec = tval_end.tv_sec - tval_start.tv_sec;
58 | tval_diff.tv_usec = tval_end.tv_usec - tval_start.tv_usec;
59 | if(tval_diff.tv_usec < 0)
60 | {
61 | --tval_diff.tv_sec;
62 | tval_diff.tv_usec += 1000000;
63 | }
64 | return (float)tval_diff.tv_sec + (float)tval_diff.tv_usec / 1000000;
65 | }
66 |
67 | void parseCmdLine(int argc, char **argv) {
68 | int i;
69 | for(i=1; iip, speedTestConfig->isp);
133 | printf("Lat: %f Lon: %f\n", speedTestConfig->lat, speedTestConfig->lon);
134 | serverList = getServers(&serverCount, URL_PROTOCOL "://www.speedtest.net/speedtest-servers-static.php");
135 | if (serverCount == 0)
136 | {
137 | // Primary server is not responding. Let's give a try with secondary one.
138 | serverList = getServers(&serverCount, URL_PROTOCOL "://c.speedtest.net/speedtest-servers-static.php");
139 | }
140 | printf("Grabbed %d servers\n", serverCount);
141 | if (serverCount == 0)
142 | {
143 | printf("Cannot download any speedtest.net server. Something is wrong...\n");
144 | freeMem();
145 | exit(1);
146 | }
147 | for(i=0; idistance = haversineDistance(speedTestConfig->lat,
149 | speedTestConfig->lon,
150 | serverList[i]->lat,
151 | serverList[i]->lon);
152 |
153 | qsort(serverList, serverCount, sizeof(SPEEDTESTSERVER_T *),
154 | (int (*)(const void *,const void *)) sortServersDistance);
155 |
156 | if (lowestLatencyServers != 0)
157 | {
158 | int debug = 0;
159 | if (lowestLatencyServers < 0)
160 | {
161 | lowestLatencyServers = -lowestLatencyServers;
162 | debug = 1;
163 | }
164 | printf("Testing closest %d servers for latency", lowestLatencyServers);
165 | fflush(stdout);
166 | // for LARGE numbers of servers could do this in parallel
167 | // (but best not to pester them, maybe limit max number??)
168 | for(i=0; iurl);
171 | serverList[i]->latency = getLatency(latencyUrl);
172 | putchar('.');
173 | fflush(stdout);
174 | }
175 | putchar('\n');
176 |
177 | /* perform secondary sort on latency */
178 | qsort(serverList, lowestLatencyServers, sizeof(SPEEDTESTSERVER_T *),
179 | (int (*)(const void *,const void *)) sortServersLatency);
180 |
181 | if (debug)
182 | {
183 | for(i=0; isponsor, serverList[i]->name,
187 | serverList[i]->distance, serverList[i]->latency, LATENCY_UNITS);
188 | }
189 | }
190 |
191 | if (randomizeBestServers >= lowestLatencyServers)
192 | randomizeBestServers = lowestLatencyServers / 2;
193 | }
194 | if (randomizeBestServers > 1)
195 | {
196 | printf("Randomizing selection of %d best servers...\n", randomizeBestServers);
197 | srand(time(NULL));
198 | selectedServer = rand() % randomizeBestServers;
199 | }
200 |
201 | printf("Best Server URL: %s\n\t Name: %s Country: %s Sponsor: %s Dist: %ld km\n",
202 | serverList[selectedServer]->url, serverList[selectedServer]->name, serverList[selectedServer]->country,
203 | serverList[selectedServer]->sponsor, serverList[selectedServer]->distance);
204 | downloadUrl = getServerDownloadUrl(serverList[selectedServer]->url);
205 | uploadUrl = malloc(sizeof(char) * strlen(serverList[selectedServer]->url) + 1);
206 | strcpy(uploadUrl, serverList[selectedServer]->url);
207 |
208 | if (lowestLatencyServers) /* avoid getting latency twice! */
209 | printf("Latency: %ld %s\n",
210 | serverList[selectedServer]->latency, LATENCY_UNITS);
211 |
212 | for(i=0; iurl);
215 | free(serverList[i]->name);
216 | free(serverList[i]->sponsor);
217 | free(serverList[i]->country);
218 | free(serverList[i]);
219 | }
220 | }
221 |
222 | static void getUserDefinedServer()
223 | {
224 | /* When user specify server URL, then we're not downloading config,
225 | so we need to specify thread count */
226 | speedTestConfig = malloc(sizeof(struct speedtestConfig));
227 | speedTestConfig->downloadThreadConfig.threadsCount = 4;
228 | speedTestConfig->uploadThreadConfig.threadsCount = 2;
229 | speedTestConfig->uploadThreadConfig.length = 3;
230 |
231 | uploadUrl = downloadUrl;
232 | tmpUrl = malloc(sizeof(char) * strlen(downloadUrl) + 1);
233 | strcpy(tmpUrl, downloadUrl);
234 | downloadUrl = getServerDownloadUrl(tmpUrl);
235 | free(tmpUrl);
236 | }
237 |
238 | int main(int argc, char **argv)
239 | {
240 | totalTransfered = 1024 * 1024;
241 | totalToBeTransfered = 1024 * 1024;
242 | totalDownloadTestCount = 1;
243 | randomizeBestServers = 0;
244 | lowestLatencyServers = 0;
245 | speedTestConfig = NULL;
246 |
247 | parseCmdLine(argc, argv);
248 |
249 | #ifdef OPENSSL
250 | SSL_library_init();
251 | SSL_load_error_strings();
252 | OpenSSL_add_all_algorithms();
253 | #endif
254 |
255 | if(downloadUrl == NULL)
256 | {
257 | getBestServer();
258 | }
259 | else
260 | {
261 | getUserDefinedServer();
262 | }
263 |
264 | if (lowestLatencyServers == 0)
265 | {
266 | latencyUrl = getLatencyUrl(uploadUrl);
267 | printf("Latency: %ld %s\n", getLatency(latencyUrl), LATENCY_UNITS);
268 | }
269 |
270 | testDownload(downloadUrl);
271 | testUpload(uploadUrl);
272 |
273 | freeMem();
274 | return 0;
275 | }
276 |
--------------------------------------------------------------------------------
/src/Speedtest.h:
--------------------------------------------------------------------------------
1 | #ifndef _SPEEDTEST_
2 | #define _SPEEDTEST_
3 |
4 | #include
5 | #include
6 |
7 | #define SPEED_TEST_FILE_SIZE 31625365
8 | #define BUFFER_SIZE 1500
9 | extern SPEEDTESTCONFIG_T *speedTestConfig;
10 | extern unsigned totalDownloadTestCount;
11 | extern unsigned long totalTransfered;
12 | extern unsigned long totalToBeTransfered;
13 |
14 | typedef struct thread_args {
15 | pthread_t tid;
16 | char *url;
17 | unsigned int testCount;
18 | unsigned long transferedBytes;
19 | float elapsedSecs;
20 | } THREADARGS_T;
21 |
22 | float getElapsedTime(struct timeval tval_start);
23 | char *strdup(const char *str);
24 | #endif
25 |
--------------------------------------------------------------------------------
/src/SpeedtestConfig.c:
--------------------------------------------------------------------------------
1 | /*
2 | Client configuration parsing functions.
3 |
4 | Michał Obrembski (byku@byku.com.pl)
5 | */
6 | #include "SpeedtestConfig.h"
7 | #include "http.h"
8 | #include "url.h"
9 |
10 | #include
11 | #include
12 | #include
13 |
14 | static const char *ConfigLineIdentitier[] = {"ip, lat, lon, result->isp)!=4)
57 | {
58 | fprintf(stderr,"Cannot parse all fields! Config line: %s", configline);
59 | exit(1);
60 | }
61 | result->lat = strtof(lat, NULL);
62 | result->lon = strtof(lon, NULL);
63 | }
64 |
65 | static void parseUpload(const char *configline, SPEEDTESTCONFIG_T **result_p)
66 | {
67 | SPEEDTESTCONFIG_T *result = *result_p;
68 | char threads[8] = {"3"}, testlength[8] = {"9"};
69 |
70 | getValue(configline, "testlength=", testlength);
71 | getValue(configline, "threads=", threads);
72 |
73 | result->uploadThreadConfig.threadsCount = atoi(threads);
74 | result->uploadThreadConfig.length = atoi(testlength);
75 | }
76 |
77 | static void parseDownload(const char *configline, SPEEDTESTCONFIG_T **result_p)
78 | {
79 | SPEEDTESTCONFIG_T *result = *result_p;
80 | char threadcount[8] = {"3"};
81 |
82 | getValue(configline, "threadcount=", threadcount);
83 |
84 | result->downloadThreadConfig.threadsCount = atoi(threadcount);
85 | }
86 |
87 | static void parseServerConfig(const char *configline, SPEEDTESTCONFIG_T **result_p)
88 | {
89 | SPEEDTESTCONFIG_T *result = *result_p;
90 | char threadcount[8] = {"3"};
91 |
92 | getValue(configline, "threadcount=", threadcount);
93 |
94 | result->downloadThreadConfig.threadsCount = atoi(threadcount);
95 | }
96 |
97 | SPEEDTESTCONFIG_T *getConfig()
98 | {
99 | SPEEDTESTCONFIG_T *result = NULL;
100 | char buffer[0xFFFF] = {0};
101 | int i, parsed = 0;
102 | long size;
103 | void (*parsefuncs[])(const char *configline, SPEEDTESTCONFIG_T **result_p)
104 | = { parseClient, parseUpload, parseDownload, parseServerConfig };
105 | sock_t sockId = httpGetRequestSocket(URL_PROTOCOL "://www.speedtest.net/speedtest-config.php");
106 |
107 | if(!sockId)
108 | {
109 | return NULL; /* Cannot connect to server */
110 | }
111 |
112 | while((size = recvLine(sockId, buffer, sizeof(buffer))) > 0)
113 | {
114 | buffer[size + 1] = '\0';
115 | for (i = 0; i < ARRAY_SIZE(ConfigLineIdentitier); i++)
116 | {
117 | if(strncmp(buffer, ConfigLineIdentitier[i], strlen(ConfigLineIdentitier[i])))
118 | {
119 | continue;
120 | }
121 |
122 | if (!result)
123 | {
124 | result = malloc(sizeof(struct speedtestConfig));
125 | if (!result)
126 | {
127 | /* Out of memory */
128 | return NULL;
129 | }
130 | }
131 | parsefuncs[i](buffer, &result);
132 | if (i == 0)
133 | {
134 | /* The '
4 | #define R 6371
5 | #define PI 3.1415926536
6 | #define TO_RAD (PI / 180)
7 |
8 | #ifndef URL_PROTOCOL
9 | #define URL_PROTOCOL "http"
10 | #endif
11 |
12 | #ifndef ARRAY_SIZE
13 | #define ARRAY_SIZE(_x) \
14 | (sizeof(_x) / sizeof(_x[0]))
15 | #endif /* ARRAY_SIZE */
16 |
17 | typedef struct ThreadConfig {
18 | int threadsCount; /* number of threads */
19 | int length; /* testlength? */
20 | } THREADCONFIG_T;
21 |
22 | typedef struct speedtestConfig
23 | {
24 | char ip[16];
25 | float lat;
26 | float lon;
27 | char isp[255];
28 | THREADCONFIG_T uploadThreadConfig;
29 | THREADCONFIG_T downloadThreadConfig;
30 | } SPEEDTESTCONFIG_T;
31 |
32 | SPEEDTESTCONFIG_T *getConfig();
33 | long haversineDistance(float lat1, float lon1, float lat2, float lon2);
34 | #endif
35 |
--------------------------------------------------------------------------------
/src/SpeedtestDownloadTest.c:
--------------------------------------------------------------------------------
1 | #include "SpeedtestDownloadTest.h"
2 | #include "SpeedtestConfig.h"
3 | #include "SpeedtestServers.h"
4 | #include "Speedtest.h"
5 | #include "http.h"
6 |
7 | #include
8 | #include
9 | #include
10 | #include
11 |
12 | static void *__downloadThread(void *arg)
13 | {
14 | THREADARGS_T *threadConfig = (THREADARGS_T*)arg;
15 | int testNum;
16 | char buffer[BUFFER_SIZE] = {0};
17 | struct timeval tval_start;
18 |
19 | gettimeofday(&tval_start, NULL);
20 | for (testNum = 0; testNum < threadConfig->testCount; testNum++)
21 | {
22 | int size = -1;
23 | sock_t sockId = httpGetRequestSocket(threadConfig->url);
24 |
25 | if(sockId == 0)
26 | {
27 | fprintf(stderr, "Unable to open socket for Download!");
28 | pthread_exit(NULL);
29 | }
30 |
31 | while(size != 0)
32 | {
33 | size = httpRecv(sockId, buffer, BUFFER_SIZE);
34 | if (size != -1)
35 | {
36 | threadConfig->transferedBytes += size;
37 | }
38 | }
39 | httpClose(sockId);
40 | }
41 | threadConfig->elapsedSecs = getElapsedTime(tval_start);
42 |
43 | return NULL;
44 | }
45 |
46 | void testDownload(const char *url)
47 | {
48 | size_t numOfThreads = speedTestConfig->downloadThreadConfig.threadsCount;
49 | THREADARGS_T *param = (THREADARGS_T *)calloc(numOfThreads, sizeof(THREADARGS_T));
50 | int i;
51 | float speed = 0;
52 |
53 | /* Initialize and start threads */
54 | for (i = 0; i < numOfThreads; i++)
55 | {
56 | param[i].testCount = totalDownloadTestCount / numOfThreads;
57 | if (param[i].testCount == 0)
58 | {
59 | /* At least one test should be run */
60 | param[i].testCount = 1;
61 | }
62 | param[i].url = strdup(url);
63 | if (param[i].url)
64 | {
65 | pthread_create(¶m[i].tid, NULL, &__downloadThread, ¶m[i]);
66 | }
67 | }
68 | /* Wait for all threads */
69 | for (i = 0; i < numOfThreads; i++)
70 | {
71 | pthread_join(param[i].tid, NULL);
72 | if (param[i].transferedBytes)
73 | {
74 | /* There's no reason that we transfered nothing except error occured */
75 | totalTransfered += param[i].transferedBytes;
76 | speed += (param[i].transferedBytes / param[i].elapsedSecs) / 1024;
77 | }
78 | /* Cleanup */
79 | free(param[i].url);
80 | }
81 | free(param);
82 |
83 | /* Report */
84 | printf("Bytes %lu downloaded with a speed %.2f kB/s (%.2f Mbit/s)\n",
85 | totalTransfered, speed, speed * 8 / 1024);
86 | }
87 |
--------------------------------------------------------------------------------
/src/SpeedtestDownloadTest.h:
--------------------------------------------------------------------------------
1 | #ifndef _SPEEDTEST_DOWNLOAD_TEST_
2 | #define _SPEEDTEST_DOWNLOAD_TEST_
3 |
4 | void testDownload(const char *url);
5 |
6 | #endif
7 |
--------------------------------------------------------------------------------
/src/SpeedtestLatencyTest.c:
--------------------------------------------------------------------------------
1 | #include "SpeedtestConfig.h"
2 | #include "SpeedtestServers.h"
3 | #include "SpeedtestLatencyTest.h"
4 | #include "Speedtest.h"
5 | #include "http.h"
6 |
7 | #include
8 | #include
9 | #include
10 |
11 | /* Latency test is just testing time taken to download single latency.txt file
12 | which contains 10 chars: "test=test\n"*/
13 | #define LATENCY_SIZE 10
14 |
15 | long getLatency(const char *url)
16 | {
17 | char buffer[LATENCY_SIZE] = {0};
18 | sock_t sockId;
19 | struct timeval tval_start;
20 |
21 | gettimeofday(&tval_start, NULL);
22 | sockId = httpGetRequestSocket(url);
23 | if(sockId == 0)
24 | return LATENCY_CONNECT_ERROR;
25 |
26 | for (;;)
27 | {
28 | int size = httpRecv(sockId, buffer, LATENCY_SIZE);
29 | if (size == -1)
30 | {
31 | httpClose(sockId);
32 | return LATENCY_DATA_ERROR;
33 | }
34 | if (size == 0)
35 | break;
36 | }
37 |
38 | httpClose(sockId);
39 | return (long)(getElapsedTime(tval_start) * LATENCY_UNITS_PER_SECOND); /* ms */
40 | }
41 |
--------------------------------------------------------------------------------
/src/SpeedtestLatencyTest.h:
--------------------------------------------------------------------------------
1 | #ifndef _SPEEDTEST_LATENCY_TEST_
2 | #define _SPEEDTEST_LATENCY_TEST_
3 |
4 | #define LATENCY_UNITS_PER_SECOND 1000L
5 | #define LATENCY_UNITS "ms"
6 |
7 | long getLatency(const char *url);
8 |
9 | /* return large positive values on error, so they sort last */
10 | #define LATENCY_CONNECT_ERROR (1000 * LATENCY_UNITS_PER_SECOND)
11 | #define LATENCY_DATA_ERROR (1000 * LATENCY_UNITS_PER_SECOND + 1)
12 |
13 | #endif
14 |
--------------------------------------------------------------------------------
/src/SpeedtestServers.c:
--------------------------------------------------------------------------------
1 | /*
2 | Server list parsing functions.
3 |
4 | Michał Obrembski (byku@byku.com.pl)
5 | */
6 | #include
7 | #include
8 | #include
9 | #include "SpeedtestServers.h"
10 | #include "http.h"
11 |
12 | void parseServer(SPEEDTESTSERVER_T *result, const char *configline)
13 | {
14 | /* TODO: Remove Switch, replace it with something space-friendly
15 | result = malloc(sizeof(SPEEDTESTSERVER_T));*/
16 | int tokensize,size;
17 | char *first, *second, *substr;
18 | const char *tokens[8] = {"url=\"","lat=\"", "lon=\"", "name=\"",
19 | "country=\"", "cc=\"", "sponsor=\"", "id=\""};
20 | int i;
21 | for(i=1; i < 8; i++)
22 | {
23 | first = strstr(configline, tokens[i-1]);
24 | second = strstr(configline, tokens[i]);
25 | if(first == NULL || second==NULL )
26 | return;
27 | tokensize = strlen(tokens[i-1]);
28 | size = second - first - 1;
29 | substr = calloc(sizeof(char), size);
30 | strncpy(substr, first+tokensize, size - tokensize - 1);
31 | substr[size - tokensize] = '\0';
32 | switch(i)
33 | {
34 | case 1:
35 | result->url = substr;
36 | break;
37 | case 2:
38 | result->lat = strtof(substr, NULL);
39 | free(substr);
40 | break;
41 | case 3:
42 | result->lon = strtof(substr, NULL);
43 | free(substr);
44 | break;
45 | case 4:
46 | result->name = substr;
47 | break;
48 | case 5:
49 | result->country = substr;
50 | break;
51 | case 7:
52 | result->sponsor = substr;
53 | break;
54 | default:
55 | free(substr);
56 | break;
57 | }
58 | }
59 | }
60 |
61 | SPEEDTESTSERVER_T **getServers(int *serverCount, const char *infraUrl)
62 | {
63 | char buffer[1500] = {0};
64 | SPEEDTESTSERVER_T **list = NULL;
65 | sock_t sockId = httpGetRequestSocket(infraUrl);
66 | if(sockId) {
67 | long size;
68 | while((size = recvLine(sockId, buffer, sizeof(buffer))) > 0)
69 | {
70 | buffer[size + 1] = '\0';
71 | if(strlen(buffer) > 25)
72 | {
73 | /*Ommiting XML invocation...*/
74 | if (strstr(buffer, "')
78 | {
79 | *serverCount = *serverCount + 1;
80 | list = (SPEEDTESTSERVER_T**)realloc(list,
81 | sizeof(SPEEDTESTSERVER_T**) * (*serverCount));
82 | if(list == NULL) {
83 | fprintf(stderr, "Unable to allocate memory for servers!\n");
84 | exit(1);
85 | }
86 | list[*serverCount - 1] = malloc(sizeof(SPEEDTESTSERVER_T));
87 | if(list[*serverCount - 1])
88 | parseServer(list[*serverCount - 1],buffer);
89 | }
90 | }
91 | }
92 | httpClose(sockId);
93 | return list;
94 | }
95 | return NULL;
96 | }
97 |
98 | static char *modifyServerUrl(char *serverUrl, const char *urlFile)
99 | {
100 | size_t urlSize = strlen(serverUrl);
101 | char *upload = strstr(serverUrl, "upload.php");
102 | if(upload == NULL)
103 | {
104 | printf("Download URL parsing error - cannot find upload.php in %s\n",
105 | serverUrl);
106 | exit(1);
107 | }
108 | size_t uploadSize = strlen(upload);
109 | size_t totalSize = (urlSize - uploadSize) +
110 | strlen(urlFile) + 1;
111 | char *result = (char*)malloc(sizeof(char) * totalSize);
112 | result[(urlSize - uploadSize)] = '\0';
113 | memcpy(result, serverUrl, urlSize - uploadSize);
114 | strcat(result, urlFile);
115 | return result;
116 | }
117 |
118 | char *getServerDownloadUrl(char *serverUrl)
119 | {
120 | return modifyServerUrl(serverUrl, "random4000x4000.jpg");
121 | }
122 |
123 | char *getLatencyUrl(char *serverUrl)
124 | {
125 | return modifyServerUrl(serverUrl, "latency.txt");
126 | }
127 |
--------------------------------------------------------------------------------
/src/SpeedtestServers.h:
--------------------------------------------------------------------------------
1 | #ifndef _SPEEDTEST_SERVERS_
2 | #define _SPEEDTEST_SERVERS_
3 |
4 | typedef struct speedtestServer
5 | {
6 | char *url;
7 | float lat;
8 | float lon;
9 | char *name;
10 | char *country;
11 | char *sponsor;
12 | long distance;
13 | long latency;
14 |
15 | } SPEEDTESTSERVER_T;
16 | SPEEDTESTSERVER_T **getServers(int *serverCount, const char *infraUrl);
17 | char *getServerDownloadUrl(char *serverUrl);
18 | char *getLatencyUrl(char *serverUrl);
19 | #endif
20 |
--------------------------------------------------------------------------------
/src/SpeedtestUploadTest.c:
--------------------------------------------------------------------------------
1 | #include "SpeedtestUploadTest.h"
2 | #include "SpeedtestConfig.h"
3 | #include "SpeedtestServers.h"
4 | #include "Speedtest.h"
5 | #include "http.h"
6 |
7 | #include
8 | #include
9 | #include
10 | #include
11 |
12 | static void __appendTimestamp(const char *url, char *buff, int buff_len)
13 | {
14 | char delim = '?';
15 | char *p = strchr(url, '?');
16 |
17 | if (p)
18 | delim = '&';
19 | snprintf(buff, buff_len, "%s%cx=%llu", url, delim, (unsigned long long)time(NULL));
20 | }
21 |
22 | static void *__uploadThread(void *arg)
23 | {
24 | /* Testing upload... */
25 | THREADARGS_T *threadConfig = (THREADARGS_T *)arg;
26 | char alphabet[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
27 | char buffer[BUFFER_SIZE] = {0};
28 | int i, size;
29 | struct timeval tval_start;
30 | unsigned long totalTransfered = 0;
31 | char uploadUrl[1024];
32 | sock_t sockId;
33 |
34 | /* Build the random buffer */
35 | srand(time(NULL));
36 | for(i=0; i < BUFFER_SIZE; i++)
37 | {
38 | buffer[i] = alphabet[rand() % ARRAY_SIZE(alphabet)];
39 | }
40 |
41 | gettimeofday(&tval_start, NULL);
42 | for (i = 0; i < threadConfig->testCount; i++)
43 | {
44 | __appendTimestamp(threadConfig->url, uploadUrl, sizeof(uploadUrl));
45 | /* FIXME: totalToBeTransfered should be readonly while the upload thread is running */
46 | totalTransfered = totalToBeTransfered;
47 | sockId = httpPutRequestSocket(uploadUrl, totalToBeTransfered);
48 | if(sockId == 0)
49 | {
50 | printf("Unable to open socket for Upload!");
51 | pthread_exit(NULL);
52 | }
53 |
54 | while(totalTransfered != 0)
55 | {
56 | if (totalTransfered > BUFFER_SIZE)
57 | {
58 | size = httpSend(sockId, buffer, BUFFER_SIZE);
59 | }
60 | else
61 | {
62 | buffer[totalTransfered - 1] = '\n'; /* Indicate terminated */
63 | size = httpSend(sockId, buffer, totalTransfered);
64 | }
65 |
66 | totalTransfered -= size;
67 | }
68 | threadConfig->transferedBytes += totalToBeTransfered;
69 | /* Cleanup */
70 | httpClose(sockId);
71 | }
72 | threadConfig->elapsedSecs = getElapsedTime(tval_start);
73 |
74 | return NULL;
75 | }
76 |
77 | void testUpload(const char *url)
78 | {
79 | size_t numOfThreads = speedTestConfig->uploadThreadConfig.threadsCount;
80 | THREADARGS_T *param = (THREADARGS_T *) calloc(numOfThreads, sizeof(THREADARGS_T));
81 | int i;
82 | for (i = 0; i < numOfThreads; i++)
83 | {
84 | /* Initializing some parameters */
85 | param[i].testCount = speedTestConfig->uploadThreadConfig.length;
86 | if (param[i].testCount == 0)
87 | {
88 | /* At least three test should be run */
89 | param[i].testCount = 3;
90 | }
91 | param[i].url = strdup(url);
92 | if (param[i].url)
93 | {
94 | pthread_create(¶m[i].tid, NULL, &__uploadThread, ¶m[i]);
95 | }
96 | }
97 |
98 | /* Refresh */
99 | totalTransfered = 0;
100 | float speed = 0;
101 |
102 | /* Wait for all threads */
103 | for (i = 0; i < numOfThreads; i++)
104 | {
105 | pthread_join(param[i].tid, NULL);
106 | if (param[i].transferedBytes)
107 | {
108 | /* There's no reason that we transfered nothing except error occured */
109 | totalTransfered += param[i].transferedBytes;
110 | speed += (param[i].transferedBytes / param[i].elapsedSecs) / 1024;
111 | }
112 | /* Cleanup */
113 | free(param[i].url);
114 | }
115 | free(param);
116 | printf("Bytes %lu uploaded with a speed %.2f kB/s (%.2f Mbit/s)\n",
117 | totalTransfered, speed, speed * 8 / 1024);
118 | }
119 |
--------------------------------------------------------------------------------
/src/SpeedtestUploadTest.h:
--------------------------------------------------------------------------------
1 | #ifndef _SPEEDTEST_UPLOAD_TEST_
2 | #define _SPEEDTEST_UPLOAD_TEST_
3 |
4 | void testUpload(const char *url);
5 |
6 | #endif
7 |
--------------------------------------------------------------------------------
/src/http.c:
--------------------------------------------------------------------------------
1 | /*
2 | Http functions. Dont forget to initialize winsock.
3 |
4 | Luke Graham (39ster@gmail.com)
5 | Michał Obrembski (byku@byku.com.pl)
6 | */
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include
14 |
15 | #ifdef OPENSSL
16 | #include
17 | #include
18 | #include
19 | #endif
20 |
21 | #include "url.h"
22 | #include "http.h"
23 |
24 | #define USER_AGENT "SpeedTestC"
25 |
26 | int _httpErrorCode = 0;
27 |
28 | int httpLastError()
29 | {
30 | return _httpErrorCode;
31 | }
32 |
33 | #ifdef OPENSSL
34 | static BIO *bioWrap(int s, int ssl, int client)
35 | {
36 | BIO *bio = BIO_new_socket(s, BIO_CLOSE);
37 | if (ssl) {
38 | SSL_CTX *ctx;
39 | BIO *sslbio;
40 | #if OPENSSL_VERSION_NUMBER < 0x10100000L
41 | if (client)
42 | ctx = SSL_CTX_new(TLSv1_2_client_method());
43 | else
44 | ctx = SSL_CTX_new(TLSv1_2_server_method());
45 | #else
46 | if (client)
47 | ctx = SSL_CTX_new(TLS_client_method());
48 | else
49 | ctx = SSL_CTX_new(TLS_server_method());
50 | #endif
51 | if (!ctx) {
52 | return NULL; /* XXX complain */
53 | }
54 |
55 | sslbio = BIO_new_ssl(ctx, client);
56 | if (!sslbio) {
57 | return NULL; /* XXX complain */
58 | }
59 |
60 | // layer SSL over socket
61 | bio = BIO_push(sslbio, bio);
62 | }
63 | return bio;
64 | }
65 | #endif
66 |
67 | sock_t httpPut(char* pAddress, int pPort, char* pRequest, unsigned long contentSize, int ssl)
68 | {
69 | char buffer[0xFFFF];
70 | int sockId;
71 | struct sockaddr_in addr;
72 | struct hostent* hostEntry;
73 |
74 | if ((sockId = (int)socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == 0)
75 | return 0;
76 |
77 | if ((hostEntry = gethostbyname(pAddress)) == NULL)
78 | return 0;
79 |
80 | addr.sin_family = AF_INET;
81 | addr.sin_addr = *((struct in_addr*)*hostEntry->h_addr_list);
82 | addr.sin_port = htons((unsigned short)pPort);
83 | if (connect(sockId, (struct sockaddr*)&addr,
84 | sizeof(struct sockaddr_in)) == -1)
85 | return 0;
86 |
87 | /* TODO: Content-Length isn't set up, this is some kind of "hack".
88 | I cannot understand, but some servers closes up connection too early
89 | even if we set up Content-Lenght to 10 times more than we actually send.
90 | Leaving it uninitialized gives us random high value.*/
91 | sprintf(buffer, "POST %s HTTP/1.1\r\n"
92 | "Host: %s\r\n"
93 | "User-Agent: %s\r\n"
94 | "Content-Type: application/x-www-form-urlencoded\r\n"
95 | "Connection: keep-alive\r\n"
96 | "Content-Length: %lu\r\n"
97 | "\r\n", pRequest, pAddress, USER_AGENT, 100*contentSize);
98 |
99 | #ifdef OPENSSL
100 | sock_t sock = bioWrap(sockId, ssl, 1);
101 | BIO_write(sock, buffer, strlen(buffer));
102 |
103 | return sock;
104 | #else
105 | send(sockId, buffer, strlen(buffer), 0);
106 |
107 | return sockId;
108 | #endif
109 | }
110 |
111 | sock_t httpGet(char* pAddress, int pPort, char* pRequest, int ssl)
112 | {
113 | char buffer[0xFFFF], *token;
114 | sock_t sockId;
115 | int s;
116 | struct sockaddr_in addr;
117 | struct hostent* hostEntry;
118 | int length = 0;
119 | int success = 0;
120 | int i;
121 | if ((s = (int)socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == 0)
122 | return 0;
123 |
124 | if ((hostEntry = gethostbyname(pAddress)) == NULL)
125 | return 0;
126 |
127 | addr.sin_family = AF_INET;
128 | addr.sin_addr = *((struct in_addr*)*hostEntry->h_addr_list);
129 | addr.sin_port = htons((unsigned short)pPort);
130 | if (connect(s, (struct sockaddr*)&addr,
131 | sizeof(struct sockaddr_in)) == -1)
132 | return 0;
133 |
134 | sprintf(buffer, "GET %s HTTP/1.1\r\n"
135 | "Host: %s\r\n"
136 | "User-Agent: %s\r\n"
137 | "Connection: close\r\n"
138 | "\r\n", pRequest, pAddress, USER_AGENT);
139 |
140 | #ifdef OPENSSL
141 | sockId = bioWrap(s, ssl, 1);
142 | BIO_write(sockId, buffer, strlen(buffer));
143 | #else
144 | sockId = s;
145 | send(sockId, buffer, strlen(buffer), 0);
146 | #endif
147 |
148 | while((length = recvLine(sockId, buffer, sizeof(buffer))) > 0)
149 | {
150 | /*trim line*/
151 | for(i = length-1; i >= 0; i--)
152 | {
153 | if(buffer[i] < ' ')
154 | buffer[i] = 0;
155 | else break;
156 | }
157 |
158 | /*if end of header*/
159 | if(!strlen(buffer))
160 | break;
161 |
162 | /*get first word*/
163 | token = strtok(buffer, " ");
164 | if(token == NULL)
165 | break;
166 |
167 | /*Check http error code*/
168 | if(strcmp(token, "HTTP/1.0") == 0 || strcmp(token, "HTTP/1.1") == 0)
169 | {
170 | _httpErrorCode = atoi(strtok(NULL, " "));
171 | if(_httpErrorCode == 200)
172 | success = 1;
173 | }
174 |
175 | }
176 |
177 | if(!success)
178 | {
179 | #ifdef OPENSSL
180 | BIO_free_all(sockId);
181 | #else
182 | close(sockId);
183 | #endif
184 | return 0;
185 | } else return sockId;
186 | }
187 |
188 | int httpRecv(sock_t pSockId, char* pOut, int pOutSize)
189 | {
190 | int size;
191 | #ifdef OPENSSL
192 | if((size = BIO_read(pSockId, pOut, pOutSize)) > 0)
193 | return size;
194 | #else
195 | if((size = recv(pSockId, pOut, pOutSize, 0)) > 0)
196 | return size;
197 | #endif
198 | return 0;
199 | }
200 |
201 | int httpSend(sock_t pSockId, char* pOut, int pOutSize)
202 | {
203 | int size;
204 | #ifdef OPENSSL
205 | if((size = BIO_write(pSockId, pOut, pOutSize)) > 0)
206 | return size;
207 | #else
208 | if((size = send(pSockId, pOut, pOutSize, 0)) > 0)
209 | return size;
210 | #endif
211 | return 0;
212 | }
213 |
214 | void httpClose(sock_t pSockId)
215 | {
216 | #ifdef OPENSSL
217 | BIO_free_all(pSockId);
218 | #else
219 | close(pSockId);
220 | #endif
221 | }
222 |
223 | sock_t httpGetRequestSocket(const char *urlToDownload)
224 | {
225 | char address[1024];
226 | char request[1024];
227 | URLPARTS_T url;
228 | sock_t sockId;
229 |
230 | memset(&url, 0, sizeof(url));
231 | url.address = address;
232 | url.request = request;
233 | url.addressLen = sizeof(address);
234 | url.requestLen = sizeof(request);
235 |
236 | #ifdef TRACE
237 | printf("GET %s\n", urlToDownload);
238 | #endif
239 | breakUrl(urlToDownload, &url);
240 |
241 | sockId = httpGet(address, url.port, request, url.ssl);
242 | if(sockId)
243 | return sockId;
244 | fprintf(stderr, "Http error while creating GET request socket: %i\n",
245 | httpLastError());
246 | return 0;
247 | }
248 |
249 | sock_t httpPutRequestSocket(const char *urlToUpload, unsigned long contentSize)
250 | {
251 | char address[1024];
252 | char request[1024];
253 | URLPARTS_T url;
254 | sock_t sockId;
255 |
256 | memset(&url, 0, sizeof(url));
257 | url.address = address;
258 | url.request = request;
259 | url.addressLen = sizeof(address);
260 | url.requestLen = sizeof(request);
261 |
262 | #ifdef TRACE
263 | printf("PUT %s\n", urlToUpload);
264 | #endif
265 | breakUrl(urlToUpload, &url);
266 |
267 | sockId = httpPut(address, url.port, request, contentSize, url.ssl);
268 | if(sockId != BAD_SOCKID)
269 | return sockId;
270 | fprintf(stderr, "Http error while creating PUT request socket: %i\n",
271 | httpLastError());
272 | return BAD_SOCKID;
273 | }
274 |
275 | static int
276 | sockRecv(sock_t pSockId, char *ptr, int len)
277 | {
278 | #ifdef OPENSSL
279 | return BIO_read(pSockId, ptr, len);
280 | #else
281 | return recv(pSockId, ptr, len, 0);
282 | #endif
283 | }
284 |
285 | int recvLine(sock_t pSockId, char* pOut, int pOutSize)
286 | {
287 | int received = 0;
288 | char letter;
289 | memset(pOut, 0, pOutSize);
290 | for(; received < pOutSize - 1; received++)
291 | {
292 | if(sockRecv(pSockId, (char*)&letter, 1) > 0)
293 | {
294 | pOut[received] = letter;
295 | if(letter == '\n')
296 | break;
297 | } else break;
298 | }
299 | return received;
300 | }
301 |
--------------------------------------------------------------------------------
/src/http.h:
--------------------------------------------------------------------------------
1 | #ifndef HTTPH
2 | #define HTTPH
3 |
4 | #ifdef OPENSSL
5 | #include
6 | #include
7 |
8 | typedef BIO *sock_t;
9 | #define BAD_SOCKID NULL
10 | #else
11 | typedef int sock_t;
12 | #define BAD_SOCKID 0 /* should use -1!! */
13 | #endif
14 |
15 | sock_t httpPut(char* pAddress, int pPort, char* pRequest, unsigned long contentSize, int ssl);
16 | sock_t httpGet(char* pAddress, int pPort, char* pRequest, int ssl);
17 | int httpRecv(sock_t pSockId, char* pOut, int pOutSize);
18 | int httpSend(sock_t pSockId, char* pOut, int pOutSize);
19 | int httpLastError();
20 | void httpClose(sock_t pSockId);
21 | sock_t httpGetRequestSocket(const char *urlToDownload);
22 | sock_t httpPutRequestSocket(const char *urlToUpload, unsigned long contentSize);
23 | int recvLine(sock_t pSockId, char* pOut, int pOutSize);
24 |
25 | #endif
26 |
--------------------------------------------------------------------------------
/src/url.c:
--------------------------------------------------------------------------------
1 | /*
2 | URL functions.
3 |
4 | Luke Graham (39ster@gmail.com)
5 | Michał Obrembski (byku@byku.com.pl)
6 | */
7 | #include
8 | #include
9 | #include
10 | #include "url.h"
11 |
12 | /*Breaks apart a url into a port, address and request*/
13 | void breakUrl(const char* pUrl, URLPARTS_T* pUrlStruct)
14 | {
15 | char url[2048];
16 | char *ptr2, *ptr1 = url;
17 | strncpy(url, pUrl, sizeof(url));
18 | pUrlStruct->port = 80;
19 | pUrlStruct->ssl = 0;
20 | /*find protocol (like http:// or ftp://)*/
21 | ptr2 = strstr(ptr1, "://");
22 | if(ptr2 != 0)
23 | {
24 | *ptr2 = 0;
25 | if(pUrlStruct->protocolLen > 0)
26 | strncpy(pUrlStruct->protocol, ptr1, pUrlStruct->protocolLen);
27 |
28 | if(strcmp(ptr1, "ftp") == 0)
29 | pUrlStruct->port = 21;
30 | else if(strcmp(ptr1, "https") == 0) {
31 | pUrlStruct->port = 443;
32 | pUrlStruct->ssl = 1;
33 | }
34 | ptr1 = ptr2 + 3;
35 | } else if(pUrlStruct->protocolLen > 0)
36 | *pUrlStruct->protocol = 0;
37 |
38 | /*find request (the part starting at "/" after the address and port)*/
39 | ptr2 = strchr(ptr1, '/');
40 | if(ptr2 != 0)
41 | {
42 | if(pUrlStruct->requestLen > 0)
43 | strncpy(pUrlStruct->request, ptr2, pUrlStruct->requestLen);
44 |
45 | *ptr2 = 0;
46 | } else if(pUrlStruct->requestLen > 1)
47 | strncpy(pUrlStruct->request, "/", pUrlStruct->requestLen);
48 |
49 | /*find port (the part after ":")*/
50 | ptr2 = strchr(ptr1, ':');
51 | if(ptr2 != 0)
52 | {
53 | pUrlStruct->port = atoi(ptr2+1);
54 | *ptr2 = 0;
55 | }
56 |
57 | /*whats left should only be the address*/
58 | if(pUrlStruct->addressLen > 0)
59 | strncpy(pUrlStruct->address, ptr1, pUrlStruct->addressLen);
60 | }
61 |
62 | int hexToAscii(char pHex)
63 | {
64 | if(pHex >= '0' && pHex <= '9')
65 | return pHex - '0';
66 | if(pHex >= 'A' && pHex <= 'F')
67 | return pHex - 'A' + 10;
68 | if(pHex >= 'a' && pHex <= 'f')
69 | return pHex - 'a' + 10;
70 | return 0;
71 | }
72 | /*Decodes the hex parts of the request (e.g %20 is ' ')*/
73 | void decodeRequest(const char* pRequest, char* pOut, int pOutSize)
74 | {
75 | char* ptr1 = (char*)pRequest;
76 | int i;
77 | memset(pOut, 0, pOutSize);
78 | for(i = 0; i < pOutSize-1; i++)
79 | {
80 | if(*ptr1 == 0)
81 | break;
82 |
83 | switch(*ptr1)
84 | {
85 | case '%':
86 | pOut[i] = hexToAscii(*++ptr1) << 4;
87 | pOut[i] += hexToAscii(*++ptr1);
88 | break;
89 |
90 | default:
91 | pOut[i] = *ptr1;
92 | break;
93 | }
94 | ptr1++;
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/src/url.h:
--------------------------------------------------------------------------------
1 | #ifndef URLDECODEH
2 | #define URLDECODEH
3 |
4 | typedef struct
5 | {
6 | char* address;
7 | int addressLen;
8 | char* request;
9 | int requestLen;
10 | char* protocol;
11 | int protocolLen;
12 | int port;
13 | int ssl;
14 | } URLPARTS_T;
15 |
16 | void decodeRequest(const char* pRequest, char* pOut, int pOutSize);
17 | void breakUrl(const char* pUrl, URLPARTS_T* pUrlStruct);
18 | #endif
19 |
--------------------------------------------------------------------------------