├── .gitignore
├── .travis.yml
├── COPYING
├── Dockerfile
├── Makefile
├── README.md
├── config.toml
├── const_enums.go
├── const_settings.go
├── errors.go
├── glide.lock
├── glide.yaml
├── helpers.go
├── main.go
├── models.go
├── network.go
├── protocol_a2s.go
├── protocol_helpers.go
├── protocol_mumbles.go
├── protocol_mumbles_test.go
├── protocol_openttdm.go
├── protocol_openttdm_test.go
├── protocol_openttds.go
├── protocol_openttds_test.go
├── protocol_q3m.go
├── protocol_q3s.go
├── protocol_steam.go
├── protocol_teeworldsm.go
├── protocol_teeworldss.go
├── protocols.go
├── util.go
└── util_test.go
/.gitignore:
--------------------------------------------------------------------------------
1 | bin
2 | vendor
3 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: required
2 | language: go
3 | go:
4 | - 1.6
5 | services:
6 | - docker
7 | env:
8 | global:
9 | - secure: "cJ/MQsBlxWHpXyxGnhg5xm7PQMYWyGxk+hbRz1ujUX1fXjacG3SzTs4i+imdYSZznGi+QfVyxLt2DFAjf7c2rezwoiRogOL4S72uaDRIvOa5IODR4e0SsPGBTYOsoMG8blhxjc4ZnNkSfbHkc/sT9w2VoxhSEuXxnpUGmqstXcnWTf1wlfPQ8X5JG+jnNxg33X+MM8Lm44Gjb9wswJCcU28+0rIRDH3TfENMW6KzPHGsi/7dhgXCfeXGiq7mX2k62AuZUV3BDPUvyVg+sEAOln2/bGWCF2WN3vrGkhyhb/Dj5gKmdgNN7F3FAFgxAxhVSUN/NrRnjmNhKvjk8qY/+CvBuKvGoM/y62ch40CmYkEv4AJ0Hj3ao97S/yaWuZY2P7YxnEiHfCSQZs+mph6ATKL8nvU9eh6CWwK5q/YwFmlmzh93GXjc12n7llLYYyLaDhZlIUxi+Etb027sYubN2Y37xPwwAtgxENUZhsCQPy/jH3hsUF0MFdT7aF5FwLuQQxLtCes0CMYKomlJAsN3vKeq7DlNApvbbBH7gMLmFnsxYk8mfU9SF5Hc/9KgVt2bcGXMGATg0Vq26iGZ72XP1TR0gTpLm1HYUZWmZ/sPzK2ntLX1m6alFsoXk7oWa162mgJgV9ONyVh+imF7V6FEcUClK+TgVfrrJH8/zTsOFhA=" # DOCKER_EMAIL
10 | - secure: "WZHILcapJEkiKSdnoGsxElNoGLSgIBy4UYS72RZ2wI5duu6BGMXWIShJLpAMtQ+jbBoJk25DxcFjO/v99pORk3QdkKxi5sAnyFqE1lMti/Iqx0jk+QpGxJh4iL43+Qz9gAgCiCyYLKi1C25mQ928bxk8LCK3TCvjMfBpmxuPqb+pgq7L/mcYsnN9QuAKEttuqGszmv1lSqt8Qtjs3TGFuhd2Yl7fS+6SZsNvS1xU6Y4WWFcxof+CMetHWHZUml3ydXqb75sr4oM4+FicGi5jBV/SxmXyW05/fBanGpX7/JByBGBfLBMUe+dhg4mKObSMv2lgUacculRFTy9Ua5gAGOSR4WIPbPi04CloSIZDM6uWIKOgxJsz56UsSypQ/xDqdqYFwZsua4h70wLxcbiAus9Rkrzz8eJ7gZgZGeWyt4IIGkjfx1/2wpw0qASGZhbum2EedW9V6PZ9q/u6GMohStF16jSGv5sw+nGjxQyBtwXee7RFk8yOtpg3jj8NkrLG8F8An3tq9qPGb60eOBP2Rag6COIRO/TG44nQngWxqtCvH3mKOPeFUZq7JU+lnjx5XtBshEg/p+pDQXbnEIJ/6V4RKb7tYjLJFhYEMDy2bG3XIp2fppetnIZTsymZQejI2Au/r+mOokjC53G6wOnEq36XnjVskM1xqeoHQKIuAgM=" # DOCKER_USER
11 | - secure: "h9BGjHFdOWEikWYAN1spjV/DT/RDkhwokpWTN00KbTaZjNcrOjvoGtbvs+Gv6Mix9x2n7VJph1TBQcz6XQ/MtNd6n5mPM4NUJCQBzI/QlxRr2KN+f/ebec49qqCCToO0JAnVn9Dny6pjwteksJ22qMaDfG3g3KHlxOE/t9T+IQhmqhZDawkv4YukMq+4dvRRIiPH5is2LHxaR8143zmEFpmLLJ+R+lgJgW6KHdaf+eG9DOaWdD4vf2XDeLJJbgBVmiBJe3qwei6brcbnM4p2YqfmcQWui+YvRw0n7HEK6CgIw/aWsQ1CXtNaj/01xR4HYfjyH4eS8EBtmNFJBrCwBdrB6EhkHlxnLkIp95+KA39hS/9Od3SGUss6702YNQ/7N10WfjFsHurd2FLYHbbG+pe/OzeDoTDPityIN94dVz8E3jd5rdLmF+ONBkx/mENw5rH5okPBAbQTBc+R4XeKeBqFur/5l3R4D5HHTvFudjNrD6Bi8V9oJrgnRR7qB61T5m7b/IfQoOqs+0tkJDeyRhSMUQBKLqjvok6DBC8V6/ecS1fVfReTRU4Q0pDfYkKQtIJguRP+ilxVrUy2KsRNU0tdpDW/9kdLpFdljWBphtS8Qjq6Jg2Z7UtKNZAvQCN+e4n4MSyz8JE+dRNBka25kWNo7DTvrcNr+jdqFgk1moA=" # DOCKER_PASS
12 | - COMMIT=${TRAVIS_COMMIT::8}
13 | install:
14 | - go get github.com/Masterminds/glide
15 | - make deps
16 | script: make build
17 | after_success:
18 | - docker login -e $DOCKER_EMAIL -u $DOCKER_USER -p $DOCKER_PASS
19 | - export REPO=grokstat/grokstat
20 | - export TAG=`if [ "$TRAVIS_BRANCH" == "master" ]; then echo "latest"; else echo $TRAVIS_BRANCH ; fi`
21 | - docker build -f Dockerfile -t $REPO:$COMMIT .
22 | - docker tag $REPO:$COMMIT $REPO:$TAG
23 | - docker tag $REPO:$COMMIT $REPO:travis-$TRAVIS_BUILD_NUMBER
24 | - docker push $REPO
25 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
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
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM scratch
2 | MAINTAINER Artem Vorotnikov
3 | COPY ./bin/grokstat /usr/bin/grokstat
4 |
5 | ENTRYPOINT [ "/usr/bin/grokstat" ]
6 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | deps:
2 | glide i && glide rebuild
3 | clean:
4 | rm -rf ./bin/*
5 | build: clean
6 | CGO_ENABLED=0 GOOS=linux go build -o ./bin/grokstat
7 | start: build
8 | ./bin/grokstat $(FLAGS)
9 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # GrokStat
2 | [](https://travis-ci.org/vorot93/grokstat)
3 | [](https://hub.docker.com/r/vorot93/grokstat/)
4 |
5 | Retrieves information about game servers. Inspired by [QStat](https://github.com/multiplay/qstat), written in Go. Yet even more simple, extensible and fast.
6 |
7 | GrokStat accepts input data as JSON via stdin. The result is displayed in JSON form as well. In order to run a simple query you need to specify protocol and array of hosts to check. Please refer to the example below for more information.
8 |
9 | The server query is asynchronous, done via inbuilt UDP server.
10 |
11 | ## Protocols
12 | M stands for master server support. S stands for individual game server query support.
13 |
14 | ### Supported
15 | - **M** **S** | Quake-derived games:
16 | - Quake II
17 | - Quake III
18 | - Xonotic
19 | - OpenArena
20 | - Warsow
21 | - Unvanquished
22 | - Soldiers of Fortune 2
23 | - **M** **S** | OpenTTD
24 | - **M** **S** | Teeworlds
25 | - **M** **S** | Steam / SourceQuery
26 | - **S** | Mumble
27 |
28 | ## Get it
29 | ### Docker (simple)
30 | GrokStat project ships Docker images containing precompiled GrokStat, runnable out-of-the-box.
31 | #### Install / update
32 | docker pull vorot93/grokstat
33 | #### Run
34 | docker run -it --rm vorot93/grokstat
35 | ### Manual
36 | In addition to using docker you can compile and run manually.
37 | #### Dependencies
38 | go get -u github.com/BurntSushi/toml github.com/jteeuwen/go-bindata/...
39 | #### GrokStat itself
40 | git clone https://github.com/grokstat/grokstat.git
41 | cd grokstat && make build
42 | bin/grokstat
43 |
44 | ## Example
45 | ### Query servers
46 | docker run --rm grokstat/grokstat '{"hosts": {"openttdm": ["master.openttd.org:3978"], "q3m": ["master3.idsoftware.com"]}}'
47 |
48 | or
49 |
50 | echo '{"hosts": {"openttdm": ["master.openttd.org:3978"], "q3m": ["master3.idsoftware.com"]}}' | bin/grokstat
51 |
52 | or
53 |
54 | bin/grokstat '{"hosts": {"openttdm": ["master.openttd.org:3978"], "q3m": ["master3.idsoftware.com"]}}'
55 |
56 | Always mind the single quotes.
57 | ### Review available protocols
58 | docker run --rm grokstat/grokstat '{"show-protocols": true}'
59 |
60 | or
61 |
62 | echo '{"show-protocols": true}' | bin/grokstat
63 |
64 | ## License
65 | This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation.
66 |
67 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
68 |
--------------------------------------------------------------------------------
/config.toml:
--------------------------------------------------------------------------------
1 | [[Protocols]]
2 | Id = "q3m"
3 | Template = "Q3M"
4 | [Protocols.Overrides]
5 | MasterOf = "q3s"
6 |
7 | [[Protocols]]
8 | Id = "q3s"
9 | Template = "Q3S"
10 |
11 | [[Protocols]]
12 | Id = "q2m"
13 | Template = "Q3M"
14 | [Protocols.Overrides]
15 | RequestPreludeTemplate = "query"
16 | ResponsePreludeTemplate = "{{.PreludeStarter}}servers{{.x20}}"
17 | SplitterUsed = "false"
18 | MasterOf = "q2s"
19 |
20 | [[Protocols]]
21 | Id = "q2s"
22 | Template = "Q3S"
23 | [Protocols.Overrides]
24 | RequestPreludeTemplate = "{{.PreludeStarter}}status {{.Challenge}}"
25 | ResponsePreludeTemplate = "{{.PreludeStarter}}print"
26 | ServerNameRule = "hostname"
27 | NeedPassRule = "needpass"
28 | MaxClientsRule = "maxclients"
29 | DefaultRequestPort = "27910"
30 |
31 | [[Protocols]]
32 | Id = "sof2s"
33 | Template = "Q3S"
34 | [Protocols.Overrides]
35 | Name = "Soldier of Fortune 2"
36 | DefaultRequestPort = "20100"
37 |
38 | [[Protocols]]
39 | Id = "xonoticm"
40 | Template = "Q3M"
41 | [Protocols.Overrides]
42 | Name = "Xonotic Master"
43 | MasterOf = "xonotics"
44 | RequestPreludeTemplate = "{{.PreludeStarter}}getservers Xonotic {{.Version}} empty full"
45 | Version = "3"
46 |
47 | [[Protocols]]
48 | Id = "xonotics"
49 | Template = "Q3S"
50 | [Protocols.Overrides]
51 | Name = "Xonotic server"
52 | ServerNameRule = "hostname"
53 | ModNameRule = "modname"
54 | NumBotsRule = "bots"
55 |
56 | [[Protocols]]
57 | Id = "etm"
58 | Template = "Q3M"
59 | [Protocols.Overrides]
60 | Name = "Wolfenstein: Enemy Territory Master"
61 | MasterOf = "q3s"
62 | Version = "84"
63 |
64 | [[Protocols]]
65 | Id = "warsowm"
66 | Template = "Q3M"
67 | [Protocols.Overrides]
68 | Name = "Warsow Master"
69 | MasterOf = "q3s"
70 | RequestPreludeTemplate = "{{.PreludeStarter}}getservers Warsow {{.Version}} empty full"
71 | Version = "20"
72 |
73 | [[Protocols]]
74 | Id = "unvanquishedm"
75 | Template = "Q3M"
76 | [Protocols.Overrides]
77 | Name = "Unvanquished Master"
78 | MasterOf = "q3s"
79 | Version = "86"
80 |
81 | [[Protocols]]
82 | Id = "openarenam"
83 | Template = "Q3M"
84 | [Protocols.Overrides]
85 | Name = "OpenArena Master"
86 | MasterOf = "q3s"
87 | Version = "71"
88 |
89 | [[Protocols]]
90 | Id = "sof2m"
91 | Template = "Q3M"
92 | [Protocols.Overrides]
93 | Name = "Soldier of Fortune 2 Master"
94 | MasterOf = "sof2s"
95 | Version = "2004"
96 | RequestQueryParams = "SOF2FULL"
97 | DefaultRequestPort = "20110"
98 |
99 | [[Protocols]]
100 | Id = "teeworldsm"
101 | Template = "TEEWORLDSM"
102 | [Protocols.Overrides]
103 | MasterOf = "teeworldss"
104 |
105 | [[Protocols]]
106 | Id = "teeworldss"
107 | Template = "TEEWORLDSS"
108 |
109 | [[Protocols]]
110 | Id = "openttdm"
111 | Template = "OPENTTDM"
112 | [Protocols.Overrides]
113 | MasterOf = "openttds"
114 |
115 | [[Protocols]]
116 | Id = "openttds"
117 | Template = "OPENTTDS"
118 |
119 | [[Protocols]]
120 | Id = "steam"
121 | Template = "STEAM"
122 | [Protocols.Overrides]
123 | MasterOf = "a2s"
124 |
125 | [[Protocols]]
126 | Id = "a2s"
127 | Template = "A2S"
128 |
129 | [[Protocols]]
130 | Id = "mumbles"
131 | Template = "MUMBLES"
132 |
--------------------------------------------------------------------------------
/const_enums.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | const (
4 | MSG_OUTPUT = iota
5 | MSG_MAJOR
6 | MSG_MINOR
7 | MSG_DEBUG
8 | )
9 |
--------------------------------------------------------------------------------
/const_settings.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | const (
4 | VERSION = "0.1"
5 | DEFAULT_OUTPUT_LVL = MSG_MAJOR
6 | )
7 |
--------------------------------------------------------------------------------
/errors.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "errors"
4 |
5 | var (
6 | OK = errors.New("OK.")
7 |
8 | NoConfig = errors.New("No config file specified.")
9 | ErrorLoadingConfig = errors.New("Error loading config file.")
10 |
11 | IPv6NotSupported = errors.New("IPv6 is not supported yet.")
12 |
13 | NoProtocol = errors.New("Please specify the protocol.")
14 | NoHosts = errors.New("Please specify the hosts to query.")
15 |
16 | InvalidProtocol = errors.New("Invalid protocol specified.")
17 | InvalidMasterOf = errors.New("Invalid query part attached to master protocol.")
18 |
19 | ServerDown = errors.New("Server down.")
20 |
21 | MalformedPacket = errors.New("Malformed packet.")
22 |
23 | InvalidResponseHeader = errors.New("Invalid response header.")
24 | InvalidResponseLength = errors.New("Invalid response length.")
25 | InvalidResponseChallenge = errors.New("Invalid response challenge.")
26 |
27 | InvalidServerEntryInMasterResponse = errors.New("Invalid server entry in the master server response.")
28 |
29 | NoInfoResponse = errors.New("No info response.")
30 | NoServersResponse = errors.New("No servers response.")
31 | NoStatusResponse = errors.New("No status response.")
32 |
33 | InvalidServerHeader = errors.New("Invalid server header.")
34 |
35 | InvalidPlayerString = errors.New("Invalid player string.")
36 | InvalidPlayerStringLength = errors.New("Invalid player string length.")
37 |
38 | InvalidRuleString = errors.New("Invalid rule string.")
39 | InvalidRuleStringLength = errors.New("Invalid rule string length.")
40 |
41 | CompError = errors.New("Mismatch.")
42 | )
43 |
--------------------------------------------------------------------------------
/glide.lock:
--------------------------------------------------------------------------------
1 | hash: 87a273547be6dd4da9e898a0aa593cac2ed624b6c348a91659727b83f3dc9d8d
2 | updated: 2016-06-30T16:23:09.901101493+03:00
3 | imports:
4 | - name: github.com/BurntSushi/toml
5 | version: f0aeabca5a127c4078abb8c8d64298b147264b55
6 | - name: github.com/imdario/mergo
7 | version: 50d4dbd4eb0e84778abe37cefef140271d96fade
8 | - name: github.com/skybon/goutil
9 | version: dfe316edfe279ed3d64f506d9a43ff06ff0ad192
10 | devImports: []
11 |
--------------------------------------------------------------------------------
/glide.yaml:
--------------------------------------------------------------------------------
1 | package: grokstat
2 | import:
3 | - package: github.com/BurntSushi/toml
4 | - package: github.com/imdario/mergo
5 | - package: github.com/skybon/goutil
6 |
--------------------------------------------------------------------------------
/helpers.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "net"
6 | "time"
7 | )
8 |
9 | func GetServerResponse(conn net.Conn, requestPacket Packet, responseN int) (Packet, error) {
10 | var responsePacket Packet
11 | var err error
12 |
13 | packetId := requestPacket.Id
14 |
15 | buf_len := 16777215
16 | var buf []byte
17 | data := requestPacket.Data
18 | conn.Write(data)
19 | sendtime := time.Now()
20 | var recvtime time.Time
21 | var incr int
22 | var reads int
23 | if responseN > 0 {
24 | incr = 1
25 | reads = responseN
26 | } else {
27 | incr = 0
28 | reads = 1
29 | }
30 | for i := 0; i < reads; i += incr {
31 | var n int
32 | var connErr error
33 | var readBuf = make([]byte, buf_len)
34 | n, connErr = conn.Read(readBuf)
35 | if connErr != nil {
36 | break
37 | } else if n != 0 {
38 | if recvtime == (time.Time{}) {
39 | recvtime = time.Now()
40 | }
41 | buf = bytes.Join([][]byte{buf, bytes.TrimRight(readBuf, "\x00")}, []byte{})
42 | }
43 | }
44 | ping := int64(recvtime.Sub(sendtime) / time.Millisecond)
45 |
46 | responsePacket = Packet{Data: bytes.TrimRight(buf, "\x00"), Id: packetId, Ping: ping}
47 | if len(responsePacket.Data) == 0 {
48 | err = ServerDown
49 | }
50 |
51 | return responsePacket, err
52 | }
53 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | /*
2 | grokstat is a tool for querying game servers for various information: server list, player count, active map etc
3 |
4 | The program takes protocol name and remote ip address as arguments, fetches information from the remote server, parses it and outputs back as JSON. As convenience the status and message are also provided.
5 |
6 | grokstat uses JSON input instead of command line flags. The JSON input is structured as follows:
7 | hosts - map of string keys and string array values - hosts to query
8 | show-protocols - boolean - if true, show protocols and exit
9 | output-lvl - int - tune the output from bare JSON to full-fledged debug
10 | custom-config-path - path of custom config file to be used
11 | */
12 | package main
13 |
14 | import (
15 | "bufio"
16 | "encoding/json"
17 | "fmt"
18 | "log"
19 | "net"
20 | "net/url"
21 | "os"
22 | "strings"
23 | "time"
24 |
25 | "github.com/BurntSushi/toml"
26 | "github.com/imdario/mergo"
27 | )
28 |
29 | type ServerResponseStruct struct {
30 | Hostname string
31 | ResponseMap map[string]Packet
32 | ResponseErr error
33 | }
34 |
35 | type InputData struct {
36 | Hosts map[string][]string `json:"hosts"`
37 | ShowProtocols bool `json:"show-protocols"`
38 | OutputLvl int `json:"output-lvl"`
39 | ConfigPath string `json:"config-path"`
40 | }
41 |
42 | func MakeInputData() InputData {
43 | return InputData{Hosts: make(map[string][]string)}
44 | }
45 |
46 | type ConfigFile struct {
47 | Protocols []ProtocolConfig `toml:"Protocols"`
48 | }
49 |
50 | type JsonResponse struct {
51 | Version string `json:"version"`
52 | Status int `json:"status"`
53 | Message string `json:"message"`
54 | Flags InputData `json:"input-flags"`
55 | Output interface{} `json:"output"`
56 | }
57 |
58 | type PacketErrorPair struct {
59 | Packet Packet
60 | Error error
61 | }
62 |
63 | func MakePacketErrorPair(hosts []HostProtocolIdPair, protColl *ProtocolCollection) (packErrPairs []PacketErrorPair) {
64 | packErrPairs = []PacketErrorPair{}
65 |
66 | for _, hostpair := range hosts {
67 | var hostpackets = []Packet{}
68 | var err error
69 |
70 | hostport := strings.Split(hostpair.RemoteAddr, ":")
71 | protocolId := hostpair.ProtocolId
72 | protocol, protocolExists := protColl.Get(protocolId)
73 | if protocolExists {
74 | host := hostport[0]
75 | var port string
76 | if len(hostport) < 2 {
77 | port, _ = protocol.Information["DefaultRequestPort"]
78 | } else {
79 | port = hostport[1]
80 | }
81 | ipAddr, rErr := net.ResolveIPAddr("ip4", host)
82 | if rErr == nil {
83 | addrFinal := strings.Join([]string{ipAddr.String(), port}, ":")
84 |
85 | reqPackets := MakeSendPackets(HostProtocolIdPair{RemoteAddr: addrFinal, ProtocolId: protocolId}, protColl)
86 |
87 | for _, reqPacket := range reqPackets {
88 | hostpackets = append(hostpackets, reqPacket)
89 | }
90 | } else {
91 | err = rErr
92 | }
93 | } else {
94 | err = InvalidProtocol
95 | }
96 |
97 | for _, packetFinal := range hostpackets {
98 | packErrPairs = append(packErrPairs, PacketErrorPair{Packet: packetFinal, Error: err})
99 | }
100 | }
101 |
102 | return packErrPairs
103 | }
104 |
105 | // FormJSONResponse creates a JSON string out of Grokstat output.
106 | var FormJSONResponse = func(output interface{}, err error, flags InputData) (string, error) {
107 | result := JsonResponse{Version: VERSION, Flags: flags}
108 |
109 | if err != nil {
110 | result.Output = make(map[string]interface{})
111 | result.Status = 500
112 | result.Message = err.Error()
113 | } else {
114 | result.Output = output
115 | result.Status = 200
116 | result.Message = OK.Error()
117 | }
118 |
119 | jsonOut, jsonErr := json.Marshal(result)
120 |
121 | if jsonErr != nil {
122 | jsonOut = []byte(`{"status": 500, "message": "JSON marshaller error."}`)
123 | }
124 |
125 | return string(jsonOut), jsonErr
126 | }
127 |
128 | func CleanupMessageChan(messageChan chan ConsoleMsg, endChan <-chan struct{}) {
129 | close(messageChan)
130 | <-endChan
131 | }
132 |
133 | var PrintProtocols = func(messageChan chan ConsoleMsg, protColl *ProtocolCollection, flags InputData) {
134 | output := make(map[string]interface{})
135 | output["protocols"] = protColl.Map()
136 |
137 | PrintJsonResponse(messageChan, output, nil, flags)
138 | }
139 |
140 | var PrintError = func(messageChan chan ConsoleMsg, err error, flags InputData) {
141 | PrintJsonResponse(messageChan, nil, err, flags)
142 | }
143 |
144 | var PrintJsonResponse = func(messageChan chan ConsoleMsg, output interface{}, err error, flags InputData) {
145 | jsonOut, _ := FormJSONResponse(output, err, flags)
146 | messageChan <- ConsoleMsg{Type: MSG_MAJOR, Message: jsonOut}
147 | }
148 |
149 | var DefaultConfigBinPath = "data/grokstat.toml"
150 |
151 | var ParseIPAddr = func(ipString string, defaultPort string) map[string]string {
152 | var ipStringMod string
153 |
154 | if len(strings.Split(ipString, "://")) == 1 {
155 | ipStringMod = "placeholder://" + ipString
156 | } else {
157 | ipStringMod = ipString
158 | }
159 |
160 | urlInfo, _ := url.Parse(ipStringMod)
161 |
162 | result := make(map[string]string)
163 | result["http_protocol"] = urlInfo.Scheme
164 | result["host"] = urlInfo.Host
165 |
166 | if len(strings.Split(result["host"], ":")) == 1 {
167 | result["host"] = result["host"] + ":" + defaultPort
168 | }
169 |
170 | return result
171 | }
172 |
173 | func identifyPacketProtocol(packet Packet) (string, bool) {
174 | return "STEAM", true
175 | }
176 |
177 | func Query(hosts []HostProtocolIdPair, protColl *ProtocolCollection, messageChan chan<- ConsoleMsg, debugLvl int) (serverHosts []string, output []ServerEntry, err error) {
178 | serverHosts = []string{}
179 | output = []ServerEntry{}
180 |
181 | // This is for easier server identification.
182 | var serverProtocolMapping = map[string]string{}
183 | var protocolMappingInChan = make(chan HostProtocolIdPair)
184 |
185 | go func() {
186 | for {
187 | mappingEntry := <-protocolMappingInChan
188 | serverProtocolMapping[mappingEntry.RemoteAddr] = mappingEntry.ProtocolId
189 | }
190 | }()
191 | //
192 |
193 | getProtocolOfServer := func(remoteAddr string) (string, bool) {
194 | protocolName, pOk := serverProtocolMapping[remoteAddr]
195 | return protocolName, pOk
196 | }
197 |
198 | serverEntryChan := make(chan ServerEntry, 9999)
199 | sendPacketChan := make(chan Packet, 9999)
200 | receivePacketChan := make(chan Packet, 9999)
201 |
202 | serverInitChan := make(chan struct{})
203 | serverStopChan := make(chan struct{})
204 |
205 | serverDataMap := make(map[string]ServerEntry)
206 |
207 | go func() {
208 | for {
209 | serverEntry := <-serverEntryChan
210 | hostname := serverEntry.Host
211 |
212 | oldEntry, exists := serverDataMap[hostname]
213 | if !exists {
214 | serverDataMap[hostname] = serverEntry
215 | } else {
216 | mergedEntry := oldEntry
217 | mergedRules := map[string]string{}
218 |
219 | for k, v := range mergedEntry.Rules {
220 | mergedRules[k] = v
221 | }
222 |
223 | mergo.Merge(&mergedEntry, serverEntry)
224 | mergo.Merge(&mergedRules, serverEntry.Rules)
225 |
226 | mergedEntry.Rules = mergedRules
227 |
228 | serverDataMap[hostname] = mergedEntry
229 | }
230 | }
231 | }()
232 |
233 | parseHandlerWrapper := func(packet Packet) (sendPackets []Packet) {
234 | sendPackets = make([]Packet, 0)
235 | var protocolName string
236 | protocolMappingName, pOk := getProtocolOfServer(packet.RemoteAddr)
237 | if pOk {
238 | protocolName = protocolMappingName
239 | } else {
240 | protocolIdentifiedName, iOk := identifyPacketProtocol(packet)
241 | if iOk {
242 | protocolName = protocolIdentifiedName
243 | }
244 | }
245 | if protocolName != "" {
246 | protocolEntry, protocolExists := protColl.Get(protocolName)
247 | if protocolExists {
248 | packet.ProtocolId = protocolName
249 | handlerFunc := protocolEntry.Base.HandlerFunc
250 |
251 | if handlerFunc != nil {
252 | sendPackets = handlerFunc(packet, protColl, messageChan, protocolMappingInChan, serverEntryChan)
253 | }
254 | }
255 | }
256 |
257 | return sendPackets
258 |
259 | }
260 |
261 | for _, packPair := range MakePacketErrorPair(hosts, protColl) {
262 | packet := packPair.Packet
263 | err := packPair.Error
264 |
265 | if err == nil {
266 | protocolMappingInChan <- HostProtocolIdPair{RemoteAddr: packet.RemoteAddr, ProtocolId: packet.ProtocolId}
267 | sendPacketChan <- packet
268 | } else {
269 | messageChan <- ConsoleMsg{Type: MSG_DEBUG, Message: err.Error()}
270 | }
271 | }
272 |
273 | go AsyncNetworkServer(serverInitChan, serverStopChan, messageChan, sendPacketChan, receivePacketChan, parseHandlerWrapper, 5*time.Second)
274 | <-serverInitChan
275 | <-serverStopChan
276 |
277 | for _, entry := range serverDataMap {
278 | serverHosts = append(serverHosts, entry.Host)
279 | output = append(output, entry)
280 | }
281 |
282 | return serverHosts, output, err
283 | }
284 |
285 | func conditionalPrint(message ConsoleMsg, outputLvl int, useLogging bool) {
286 | if message.Type <= outputLvl {
287 | if useLogging {
288 | log.Println(message.Message)
289 | } else {
290 | fmt.Println(message.Message)
291 | }
292 | }
293 | }
294 |
295 | func outputLoop(messageChan <-chan ConsoleMsg, messageEndChan chan<- struct{}, outputLvl int) {
296 | for {
297 | message, mOk := <-messageChan
298 | if mOk {
299 | conditionalPrint(message, outputLvl, outputLvl >= MSG_DEBUG)
300 | } else {
301 | messageEndChan <- struct{}{}
302 | return
303 | }
304 | }
305 | }
306 |
307 | func main() {
308 | var configInstance ConfigFile
309 | args := os.Args
310 | var argJsonText string
311 | var jsonText string
312 |
313 | if len(args) > 1 {
314 | argJsonText = args[1]
315 | }
316 |
317 | if argJsonText != "" {
318 | jsonText = argJsonText
319 | } else {
320 | reader := bufio.NewReader(os.Stdin)
321 | jsonText, _ = reader.ReadString('\n')
322 | }
323 |
324 | jsonFlags := MakeInputData()
325 | jsonFlags.OutputLvl = DEFAULT_OUTPUT_LVL
326 | jsonErr := json.Unmarshal([]byte(jsonText), &jsonFlags)
327 |
328 | messageChan := make(chan ConsoleMsg)
329 | messageEndChan := make(chan struct{})
330 |
331 | outputLvl := jsonFlags.OutputLvl
332 |
333 | go outputLoop(messageChan, messageEndChan, outputLvl)
334 |
335 | if jsonErr != nil {
336 | PrintError(messageChan, jsonErr, jsonFlags)
337 | CleanupMessageChan(messageChan, messageEndChan)
338 | return
339 | }
340 |
341 | hostMap := jsonFlags.Hosts
342 | showProtocols := jsonFlags.ShowProtocols
343 | configPath := jsonFlags.ConfigPath
344 | debugLvl := outputLvl
345 |
346 | if configPath == "" {
347 | PrintError(messageChan, NoConfig, jsonFlags)
348 | CleanupMessageChan(messageChan, messageEndChan)
349 | return
350 | }
351 |
352 | _, err := toml.DecodeFile(configPath, &configInstance)
353 | if err != nil {
354 | PrintError(messageChan, ErrorLoadingConfig, jsonFlags)
355 | CleanupMessageChan(messageChan, messageEndChan)
356 | return
357 | }
358 |
359 | protColl := LoadProtocols(configInstance.Protocols)
360 |
361 | if showProtocols {
362 | PrintProtocols(messageChan, protColl, jsonFlags)
363 | CleanupMessageChan(messageChan, messageEndChan)
364 | return
365 | }
366 |
367 | hosts := []HostProtocolIdPair{}
368 | for protocolId, hostList := range hostMap {
369 | for _, host := range RemoveDuplicates(hostList) {
370 | hosts = append(hosts, HostProtocolIdPair{RemoteAddr: host, ProtocolId: protocolId})
371 | }
372 | }
373 |
374 | if len(hosts) == 0 {
375 | PrintError(messageChan, NoHosts, jsonFlags)
376 | CleanupMessageChan(messageChan, messageEndChan)
377 | return
378 | }
379 |
380 | serverList, serverData, err := Query(hosts, protColl, messageChan, debugLvl)
381 |
382 | if err == nil {
383 | PrintJsonResponse(messageChan, map[string]interface{}{"server-list": serverList, "servers": serverData}, err, jsonFlags)
384 | } else {
385 | PrintError(messageChan, err, jsonFlags)
386 | CleanupMessageChan(messageChan, messageEndChan)
387 | return
388 | }
389 |
390 | CleanupMessageChan(messageChan, messageEndChan)
391 | }
392 |
--------------------------------------------------------------------------------
/models.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | type ConsoleMsg struct {
4 | Type int
5 | Message string
6 | }
7 |
8 | type Packet struct {
9 | Id string
10 | Type PacketType
11 | RemoteAddr string
12 | ProtocolId string
13 | Data []byte
14 | Ping int64
15 | Timestamp int64
16 | }
17 |
18 | type PacketType int
19 |
20 | const (
21 | TYPE_UNKNOWN PacketType = iota
22 | TYPE_TCP
23 | TYPE_TCP4
24 | TYPE_TCP6
25 | TYPE_UDP
26 | TYPE_UDP4
27 | TYPE_UDP6
28 | )
29 |
30 | func (v PacketType) IsTCP() bool {
31 | if v == TYPE_TCP || v == TYPE_TCP4 || v == TYPE_TCP6 {
32 | return true
33 | } else {
34 | return false
35 | }
36 | }
37 |
38 | func (v PacketType) IsUDP() bool {
39 | if v == TYPE_UDP || v == TYPE_UDP4 || v == TYPE_UDP6 {
40 | return true
41 | } else {
42 | return false
43 | }
44 | }
45 |
46 | func (v PacketType) IsIP6() bool {
47 | if v == TYPE_TCP6 || v == TYPE_UDP6 {
48 | return true
49 | } else {
50 | return false
51 | }
52 | }
53 |
54 | type ProtocolEntryInfo map[string]string
55 |
56 | type ProtocolEntryBase struct {
57 | MakePayloadFunc func(Packet, ProtocolEntryInfo) Packet `json:"-"`
58 | RequestPackets []RequestPacket `json:"-"`
59 | HandlerFunc func(Packet, *ProtocolCollection, chan<- ConsoleMsg, chan<- HostProtocolIdPair, chan<- ServerEntry) []Packet `json:"-"`
60 | HttpProtocol string `json:"http_protocol"`
61 | ResponseType string `json:"response_type"`
62 | }
63 |
64 | type RequestPacket struct {
65 | Id string `json:"id"`
66 | ResponsePacketNum int `json:"response_packet_num"`
67 | }
68 |
69 | // Server query protocol entry defining grokstat's behavior
70 | type ProtocolEntry struct {
71 | Id string
72 | Base ProtocolEntryBase
73 | Information ProtocolEntryInfo
74 | }
75 |
76 | type HostProtocolIdPair struct {
77 | RemoteAddr string
78 | ProtocolId string
79 | }
80 |
81 | func MakeProtocolEntry(entryTemplate ProtocolEntry) ProtocolEntry {
82 | entryInformation := make(ProtocolEntryInfo, len(entryTemplate.Information))
83 | for k, v := range entryTemplate.Information {
84 | entryInformation[k] = v
85 | }
86 |
87 | entry := ProtocolEntry{Base: entryTemplate.Base, Information: entryInformation}
88 |
89 | return entry
90 | }
91 |
92 | type PlayerEntry struct {
93 | Name string `json:"name"`
94 | Ping int64 `json:"ping"`
95 | Info map[string]string `json:"info"`
96 | }
97 |
98 | var MakePlayerEntry = func() PlayerEntry {
99 | return PlayerEntry{Info: map[string]string{}}
100 | }
101 |
102 | type ServerEntry struct {
103 | Protocol string `json:"protocol"`
104 | Status int `json:"status"`
105 | Error error `json:"-"`
106 | Message string `json:"message"`
107 | Host string `json:"host"`
108 | Name string `json:"name"`
109 | NeedPass bool `json:"need-pass"`
110 | ModName string `json:"modname"`
111 | GameType string `json:"gametype"`
112 | Terrain string `json:"terrain"`
113 | NumClients int64 `json:"numclients"`
114 | MaxClients int64 `json:"maxclients"`
115 | NumBots int64 `json:"numbots"`
116 | Secure bool `json:"secure"`
117 | Ping int64 `json:"ping"`
118 | Players []PlayerEntry `json:"players"`
119 | Rules map[string]string `json:"rules"`
120 | }
121 |
122 | var MakeServerEntry = func() ServerEntry {
123 | return ServerEntry{Players: []PlayerEntry{}, Rules: map[string]string{}}
124 | }
125 |
--------------------------------------------------------------------------------
/network.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net"
6 | "time"
7 | )
8 |
9 | func receiveHandler(packet Packet, sendRequestChan chan<- Packet, parseHandler func(Packet) []Packet) {
10 | sendPackets := parseHandler(packet)
11 |
12 | for _, sendPacket := range sendPackets {
13 | sendRequestChan <- sendPacket
14 | }
15 | }
16 |
17 | func receiveHandlerLoop(endChan chan struct{}, receiveChan chan Packet, sendRequestChan chan<- Packet, receiveHandler func(Packet, chan<- Packet, func(Packet) []Packet), parseHandler func(Packet) []Packet, awakeChan chan<- struct{}) {
18 | for {
19 | select {
20 | case dataAvailable := <-receiveChan:
21 | awakeChan <- struct{}{}
22 | go receiveHandler(dataAvailable, sendRequestChan, parseHandler)
23 | case <-endChan:
24 | return
25 | }
26 | }
27 | }
28 |
29 | func keepAliveLoop(awakeChan chan struct{}, timeOut time.Duration, endChans ...chan struct{}) {
30 | <-awakeChan
31 | for {
32 | if timeOut > 0 {
33 | select {
34 | case <-awakeChan:
35 | case <-time.After(timeOut):
36 | for _, endChannel := range endChans {
37 | endChannel <- struct{}{}
38 | }
39 | return
40 | }
41 | } else {
42 | <-awakeChan
43 | }
44 | }
45 | }
46 |
47 | func readUDP(conn *net.UDPConn) (Packet, error) {
48 | bufsize := 2048
49 | buf := make([]byte, bufsize)
50 |
51 | n, addr, err := conn.ReadFromUDP(buf)
52 | if err != nil {
53 | return Packet{}, err
54 | }
55 |
56 | return Packet{Data: buf[:n], Timestamp: time.Now().Unix(), RemoteAddr: addr.String()}, nil
57 | }
58 |
59 | func writeUDP(conn *net.UDPConn, packet Packet) {
60 | remoteIpUdp, rErr := net.ResolveUDPAddr("udp4", packet.RemoteAddr)
61 | CheckError(rErr)
62 | conn.WriteToUDP(packet.Data, remoteIpUdp)
63 | }
64 |
65 | func udpReceiveLoop(endChan <-chan struct{}, conn *net.UDPConn, messageChan chan<- ConsoleMsg, receiveChan chan Packet, awakeChan chan struct{}) {
66 | for {
67 | select {
68 | case <-endChan:
69 | return
70 | default:
71 | packet, err := readUDP(conn)
72 | awakeChan <- struct{}{}
73 | if err == nil {
74 | messageChan <- ConsoleMsg{Type: MSG_DEBUG, Message: fmt.Sprintf("Read %d bytes from %s", len(packet.Data), packet.RemoteAddr)}
75 | receiveChan <- packet
76 | }
77 | }
78 | }
79 |
80 | }
81 |
82 | func udpSendLoop(endChan <-chan struct{}, conn *net.UDPConn, messageChan chan<- ConsoleMsg, sendChan chan Packet, awakeChan chan struct{}) {
83 | for {
84 | select {
85 | case dataSendPayload := <-sendChan:
86 | messageChan <- ConsoleMsg{Type: MSG_DEBUG, Message: fmt.Sprintf("Writing %d bytes to %s", len(dataSendPayload.Data), dataSendPayload.RemoteAddr)}
87 | awakeChan <- struct{}{}
88 | go writeUDP(conn, dataSendPayload)
89 | case <-endChan:
90 | return
91 | }
92 | }
93 | }
94 |
95 | func AsyncUDPServer(endChan <-chan struct{}, initChan, doneChan chan<- struct{}, messageChan chan<- ConsoleMsg, sendChan, receiveChan chan Packet, parseHandler func(Packet) []Packet, timeOut time.Duration, awakeChan chan struct{}) {
96 | conn, err := net.ListenUDP("udp", &net.UDPAddr{
97 | Port: 0,
98 | IP: net.IPv4zero,
99 | })
100 | if err != nil {
101 | panic(err)
102 | }
103 | defer conn.Close()
104 | messageChan <- ConsoleMsg{Type: MSG_MINOR, Message: fmt.Sprintf("Starting UDP server at %s", conn.LocalAddr().String())}
105 |
106 | endReceive := make(chan struct{}, 1)
107 | endWrite := make(chan struct{}, 1)
108 |
109 | go udpReceiveLoop(endReceive, conn, messageChan, receiveChan, awakeChan)
110 | go udpSendLoop(endWrite, conn, messageChan, sendChan, awakeChan)
111 |
112 | initChan <- struct{}{}
113 | messageChan <- ConsoleMsg{Type: MSG_MINOR, Message: fmt.Sprintf("Started UDP server at %s", conn.LocalAddr().String())}
114 | <-endChan
115 | endWrite <- struct{}{}
116 | messageChan <- ConsoleMsg{Type: MSG_DEBUG, Message: fmt.Sprintf("Stopped UDP send loop.")}
117 | endReceive <- struct{}{}
118 | messageChan <- ConsoleMsg{Type: MSG_DEBUG, Message: fmt.Sprintf("Stopped UDP capture loop.")}
119 | messageChan <- ConsoleMsg{Type: MSG_MINOR, Message: fmt.Sprintf("UDP server stopped.")}
120 | doneChan <- struct{}{}
121 | }
122 |
123 | func AsyncTCPServer(endChan <-chan struct{}, initChan, doneChan chan<- struct{}, messageChan chan<- ConsoleMsg, sendChan, receiveChan chan Packet, parseHandler func(Packet) []Packet, timeOut time.Duration, awakeChan chan struct{}) {
124 | initChan <- struct{}{}
125 | <-endChan
126 | doneChan <- struct{}{}
127 | }
128 |
129 | func splitSendPacketsLoop(genChan <-chan Packet, udpChan, tcpChan chan<- Packet) {
130 | for {
131 | packet := <-genChan
132 | if packet.Type.IsTCP() {
133 | tcpChan <- packet
134 | } else {
135 | udpChan <- packet
136 | }
137 | }
138 | }
139 |
140 | func AsyncNetworkServer(initChan, doneChan chan<- struct{}, messageChan chan<- ConsoleMsg, sendChan, receiveChan chan Packet, parseHandler func(Packet) []Packet, timeOut time.Duration) {
141 | awakeChan := make(chan struct{}, 9999)
142 |
143 | udpKillChan := make(chan struct{}, 1)
144 | tcpKillChan := make(chan struct{}, 1)
145 |
146 | udpStartedChan := make(chan struct{})
147 | udpStoppedChan := make(chan struct{})
148 | tcpStartedChan := make(chan struct{})
149 | tcpStoppedChan := make(chan struct{})
150 |
151 | udpSendChan := make(chan Packet)
152 | tcpSendChan := make(chan Packet)
153 |
154 | endCallbackChan := make(chan struct{})
155 |
156 | go splitSendPacketsLoop(sendChan, udpSendChan, tcpSendChan)
157 |
158 | go AsyncUDPServer(udpKillChan, udpStartedChan, udpStoppedChan, messageChan, udpSendChan, receiveChan, parseHandler, timeOut, awakeChan)
159 | go AsyncTCPServer(tcpKillChan, tcpStartedChan, tcpStoppedChan, messageChan, tcpSendChan, receiveChan, parseHandler, timeOut, awakeChan)
160 |
161 | go receiveHandlerLoop(endCallbackChan, receiveChan, sendChan, receiveHandler, parseHandler, awakeChan)
162 |
163 | <-udpStartedChan
164 | <-tcpStartedChan
165 | initChan <- struct{}{}
166 |
167 | go keepAliveLoop(awakeChan, timeOut, udpKillChan, tcpKillChan)
168 |
169 | <-udpStoppedChan
170 | <-tcpStoppedChan
171 | doneChan <- struct{}{}
172 | }
173 |
--------------------------------------------------------------------------------
/protocol_a2s.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | )
7 |
8 | func A2SMakeProtocolTemplate() ProtocolEntry {
9 | return ProtocolEntry{Base: ProtocolEntryBase{MakePayloadFunc: MakePayload, RequestPackets: []RequestPacket{RequestPacket{Id: "A2S_INFO"}}, HandlerFunc: func(packet Packet, protocolCollection *ProtocolCollection, messageChan chan<- ConsoleMsg, protocolMappingInChan chan<- HostProtocolIdPair, serverEntryChan chan<- ServerEntry) (sendPackets []Packet) {
10 | return SimpleReceiveHandler(A2SparsePacket, packet, protocolCollection, messageChan, protocolMappingInChan, serverEntryChan)
11 | }, HttpProtocol: "udp", ResponseType: "Server list"}, Information: ProtocolEntryInfo{"Name": "Source Engine Server", "DefaultRequestPort": "27015", "RequestPreludeTemplate": "\xff\xff\xff\xffTSource Engine Query\x00", "ResponsePreludeTemplate": "\xFF\xFF\xFF\xFF"}}
12 | }
13 |
14 | func A2SparsePacket(packet Packet, protocolInfo ProtocolEntryInfo) (ServerEntry, error) {
15 | preludeTemplate, pTOk := protocolInfo["ResponsePreludeTemplate"]
16 | var body []byte
17 | var preludeOk bool
18 | if pTOk {
19 | prelude := []byte(preludeTemplate)
20 | body, preludeOk = CheckPrelude(packet.Data, prelude)
21 | } else {
22 | body = packet.Data
23 | preludeOk = true
24 | }
25 |
26 | if !preludeOk {
27 | return ServerEntry{}, InvalidResponseHeader
28 | }
29 | entryBuf := bytes.NewBuffer(body)
30 | serverHeader := entryBuf.Next(1)
31 | if !bytes.Equal(serverHeader, []byte{0x49}) {
32 | return ServerEntry{}, InvalidServerHeader
33 | }
34 | protocolVer := entryBuf.Next(1)
35 | serverNameRaw, serverNameErr := entryBuf.ReadBytes(byte(0))
36 | if serverNameErr != nil {
37 | return ServerEntry{}, InvalidResponseLength
38 | }
39 | serverName := string(bytes.Trim(serverNameRaw, "\x00"))
40 |
41 | mapNameRaw, mapNameErr := entryBuf.ReadBytes(byte(0))
42 | if mapNameErr != nil {
43 | return ServerEntry{}, InvalidResponseLength
44 | }
45 | mapName := string(bytes.Trim(mapNameRaw, "\x00"))
46 |
47 | folderNameRaw, folderNameErr := entryBuf.ReadBytes(byte(0))
48 | if folderNameErr != nil {
49 | return ServerEntry{}, InvalidResponseLength
50 | }
51 | folderName := string(bytes.Trim(folderNameRaw, "\x00"))
52 |
53 | modNameRaw, modNameErr := entryBuf.ReadBytes(byte(0))
54 | if modNameErr != nil {
55 | return ServerEntry{}, InvalidResponseLength
56 | }
57 | modName := string(bytes.Trim(modNameRaw, "\x00"))
58 |
59 | steamAppidLE := entryBuf.Next(2)
60 |
61 | numPlayers := entryBuf.Next(1)
62 | maxPlayers := entryBuf.Next(1)
63 | numBots := entryBuf.Next(1)
64 | serverTypeKW := entryBuf.Next(1)
65 |
66 | var serverType string
67 | switch string(serverTypeKW) {
68 | case "d":
69 | serverType = "dedicated"
70 | case "l":
71 | serverType = "non-dedicated"
72 | case "p":
73 | serverType = "proxy"
74 | default:
75 | return ServerEntry{}, InvalidResponseLength
76 | }
77 |
78 | serverOSKW := entryBuf.Next(1)
79 | var serverOS string
80 | switch string(serverOSKW) {
81 | case "l":
82 | serverOS = "linux"
83 | case "w":
84 | serverOS = "windows"
85 | case "m", "o":
86 | serverOS = "osx"
87 | default:
88 | return ServerEntry{}, InvalidResponseLength
89 | }
90 |
91 | needPassKW := entryBuf.Next(1)
92 | var needPass bool
93 | switch int(needPassKW[0]) {
94 | case 0:
95 | needPass = false
96 | case 1:
97 | needPass = true
98 | default:
99 | return ServerEntry{}, InvalidResponseLength
100 | }
101 |
102 | secureKW := entryBuf.Next(1)
103 | var secure bool
104 | switch int(secureKW[0]) {
105 | case 0:
106 | secure = false
107 | case 1:
108 | secure = true
109 | default:
110 | return ServerEntry{}, InvalidResponseLength
111 | }
112 |
113 | steamAppid := ByteLEToInt64(steamAppidLE)
114 |
115 | var additionalRules map[string]string
116 | if steamAppid == int64(2400) {
117 | additionalRules = make(map[string]string)
118 | additionalRules["theship-mode"] = fmt.Sprint(int(entryBuf.Next(1)[0]))
119 | additionalRules["theship-witnesses"] = fmt.Sprint(int(entryBuf.Next(1)[0]))
120 | additionalRules["theship-duration"] = fmt.Sprint(int(entryBuf.Next(1)[0]))
121 | }
122 |
123 | versionRaw, versionErr := entryBuf.ReadBytes(byte(0))
124 | if versionErr != nil {
125 | return ServerEntry{}, InvalidResponseLength
126 | }
127 | version := string(bytes.Trim(versionRaw, "\x00"))
128 |
129 | serverEntry := MakeServerEntry()
130 | serverEntry.Name = serverName
131 | serverEntry.Terrain = mapName
132 | serverEntry.ModName = modName
133 | serverEntry.NumClients = int64(numPlayers[0])
134 | serverEntry.MaxClients = int64(maxPlayers[0])
135 | serverEntry.NumBots = int64(numBots[0])
136 | serverEntry.NeedPass = needPass
137 | serverEntry.Secure = secure
138 | serverEntry.Rules["folder-name"] = string(folderName)
139 | serverEntry.Rules["protocol-version"] = fmt.Sprint(protocolVer)
140 | serverEntry.Rules["server-type"] = serverType
141 | serverEntry.Rules["server-os"] = serverOS
142 | serverEntry.Rules["version"] = version
143 | if additionalRules != nil {
144 | for k, v := range additionalRules {
145 | serverEntry.Rules[k] = v
146 | }
147 | }
148 |
149 | return serverEntry, nil
150 | }
151 |
--------------------------------------------------------------------------------
/protocol_helpers.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | )
7 |
8 | func MakeRequestPacket(packetId string, protocolInfo ProtocolEntryInfo) (requestPacket Packet) {
9 | templ, _ := protocolInfo["RequestPreludeTemplate"]
10 | requestPacket = Packet{Data: []byte(ParseTemplate(templ, protocolInfo))}
11 | return requestPacket
12 | }
13 |
14 | func MakePayload(packet Packet, protocolInfo ProtocolEntryInfo) Packet {
15 | packet.Data = MakeRequestPacket(packet.Id, protocolInfo).Data
16 | return packet
17 | }
18 |
19 | func SimpleReceiveHandler(parseFunc func(Packet, ProtocolEntryInfo) (ServerEntry, error), packet Packet, protColl *ProtocolCollection, messageChan chan<- ConsoleMsg, protocolMappingInChan chan<- HostProtocolIdPair, serverEntryChan chan<- ServerEntry) (sendPackets []Packet) {
20 | sendPackets = []Packet{}
21 |
22 | protocolId := packet.ProtocolId
23 | protocol, protocolExists := protColl.Get(protocolId)
24 | if !protocolExists {
25 | return sendPackets
26 | }
27 |
28 | protocolInfo := protocol.Information
29 | remoteIp := packet.RemoteAddr
30 | serverEntry, sErr := parseFunc(packet, protocolInfo)
31 |
32 | if sErr != nil {
33 | messageChan <- ConsoleMsg{Type: MSG_MINOR, Message: fmt.Sprintf("%s - %s - %s", protocolId, remoteIp, sErr.Error())}
34 | return sendPackets
35 | }
36 |
37 | serverEntry.Protocol = protocolId
38 | serverEntry.Host = remoteIp
39 | serverEntry.Status = 200
40 |
41 | serverEntryChan <- serverEntry
42 |
43 | return sendPackets
44 | }
45 |
46 | func MasterReceiveHandler(parseFunc func(Packet, ProtocolEntryInfo) ([]string, error), packet Packet, protColl *ProtocolCollection, messageChan chan<- ConsoleMsg, protocolMappingInChan chan<- HostProtocolIdPair, serverEntryChan chan<- ServerEntry) (sendPackets []Packet) {
47 | sendPackets = []Packet{}
48 |
49 | protocolId := packet.ProtocolId
50 | protocol, protocolExists := protColl.Get(protocolId)
51 | if !protocolExists {
52 | return sendPackets
53 | }
54 |
55 | protocolInfo := protocol.Information
56 | protocolName, _ := protocolInfo["Name"]
57 | remoteIp := packet.RemoteAddr
58 | servers, err := parseFunc(packet, protocolInfo)
59 |
60 | if err != nil {
61 | messageChan <- ConsoleMsg{Type: MSG_MINOR, Message: fmt.Sprintf("%s - %s - %s.", protocolId, remoteIp, err.Error())}
62 | return sendPackets
63 | }
64 |
65 | masterOf := protocolInfo["MasterOf"]
66 | for _, ipAddr := range servers {
67 | pair := HostProtocolIdPair{RemoteAddr: ipAddr, ProtocolId: masterOf}
68 | protocolMappingInChan <- pair
69 | sendPackets = append(sendPackets, MakeSendPackets(pair, protColl)...)
70 | }
71 |
72 | masterServerEntry := MakeServerEntry()
73 | masterServerEntry.Protocol = packet.ProtocolId
74 | masterServerEntry.Host = packet.RemoteAddr
75 | masterServerEntry.Name = fmt.Sprintf("%s Server", protocolName)
76 | masterServerEntry.Status = 200
77 |
78 | serverEntryChan <- masterServerEntry
79 |
80 | return sendPackets
81 | }
82 |
83 | func MakeSendPackets(pair HostProtocolIdPair, protocolCollection *ProtocolCollection) (sendPackets []Packet) {
84 | sendPackets = []Packet{}
85 |
86 | remoteAddr := pair.RemoteAddr
87 | protocolId := pair.ProtocolId
88 | if protocol, exists := protocolCollection.Get(protocolId); exists {
89 | requestPackets := protocol.Base.RequestPackets
90 | for _, reqPacketDesc := range requestPackets {
91 | packetId := reqPacketDesc.Id
92 | makePayloadFunc := protocol.Base.MakePayloadFunc
93 | if makePayloadFunc != nil {
94 | newReqPacket := protocol.Base.MakePayloadFunc(Packet{Id: packetId, RemoteAddr: remoteAddr, ProtocolId: protocolId}, protocol.Information)
95 | sendPackets = append(sendPackets, newReqPacket)
96 | }
97 | }
98 | }
99 | return sendPackets
100 | }
101 |
102 | func CheckPrelude(data []byte, prelude []byte) (body []byte, rOk bool) {
103 | rOk = bytes.Equal(data[:len(prelude)], prelude)
104 | body = data[len(prelude):]
105 | return body, rOk
106 | }
107 |
108 | func DefaultMasterReceiveHandler() {}
109 |
110 | func ParseHandlerPrint(packet Packet, messageChan chan<- ConsoleMsg) []Packet {
111 | messageChan <- ConsoleMsg{Type: 3, Message: string(packet.Data)}
112 | return nil
113 | }
114 |
115 | var ParseBinaryIPv4Entry = func(entryRaw []byte, portLittleEndian bool) (string, error) {
116 | if len(entryRaw) != 6 {
117 | return "", InvalidServerEntryInMasterResponse
118 | }
119 |
120 | entry := make([]int, 6)
121 | for i, v := range entryRaw {
122 | entry[i] = int(v)
123 | }
124 | var a, b, c, d, port int
125 | a = entry[0]
126 | b = entry[1]
127 | c = entry[2]
128 | d = entry[3]
129 | if portLittleEndian {
130 | port = entry[5]<<8 | entry[4]
131 | } else {
132 | port = entry[4]<<8 | entry[5]
133 | }
134 |
135 | if a == 0 {
136 | return "", InvalidServerEntryInMasterResponse
137 | }
138 |
139 | serverEntry := fmt.Sprintf("%d.%d.%d.%d:%d", a, b, c, d, port)
140 |
141 | return serverEntry, nil
142 | }
143 |
--------------------------------------------------------------------------------
/protocol_mumbles.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "encoding/binary"
6 | "fmt"
7 | )
8 |
9 | func MUMBLESMakeProtocolTemplate() ProtocolEntry {
10 | return ProtocolEntry{Base: ProtocolEntryBase{MakePayloadFunc: MakePayload, RequestPackets: []RequestPacket{RequestPacket{Id: "ping"}}, HandlerFunc: func(packet Packet, protocolCollection *ProtocolCollection, messageChan chan<- ConsoleMsg, protocolMappingInChan chan<- HostProtocolIdPair, serverEntryChan chan<- ServerEntry) []Packet {
11 | return SimpleReceiveHandler(MUMBLESparsePacket, packet, protocolCollection, messageChan, protocolMappingInChan, serverEntryChan)
12 | }, HttpProtocol: "udp", ResponseType: "Server ping"}, Information: ProtocolEntryInfo{"Name": "Mumble Server", "PreludeStarter": "\x00\x00\x00\x00", "PreludeFinisher": "", "Challenge": "grokstat", "RequestPreludeTemplate": "{{.PreludeStarter}}{{.Challenge}}{{.PreludeFinisher}}", "DefaultRequestPort": "64738"}}
13 | }
14 |
15 | func MUMBLESparsePacket(p Packet, info ProtocolEntryInfo) (v ServerEntry, err error) {
16 | defer func() {
17 | if r := recover(); r != nil {
18 | v = MakeServerEntry()
19 | err = MalformedPacket
20 | }
21 | }()
22 | var challenge *string
23 | var c, req = info["Challenge"]
24 | if req {
25 | challenge = &c
26 | }
27 | return MUMBLESparseData(p.Data, challenge)
28 | }
29 |
30 | func MUMBLESparseData(b []byte, challenge *string) (v ServerEntry, err error) {
31 | var data = bytes.NewBuffer(b)
32 |
33 | var protocolVerBytes = data.Next(4)
34 | var protocolVer = fmt.Sprintf("%d.%d.%d", protocolVerBytes[1], protocolVerBytes[2], protocolVerBytes[3])
35 |
36 | var respChallenge = string(data.Next(8))
37 | if challenge != nil {
38 | if *challenge != respChallenge {
39 | return MakeServerEntry(), InvalidResponseChallenge
40 | }
41 | }
42 |
43 | var currentClients uint32
44 | var currentClientsBytes = data.Next(4)
45 | _ = binary.Read(bytes.NewReader(currentClientsBytes), binary.BigEndian, ¤tClients)
46 |
47 | var maxClients uint32
48 | var maxClientsBytes = data.Next(4)
49 | _ = binary.Read(bytes.NewReader(maxClientsBytes), binary.BigEndian, &maxClients)
50 |
51 | var maxBandwidth uint32
52 | var maxBandwidthBytes = data.Next(4)
53 | _ = binary.Read(bytes.NewReader(maxBandwidthBytes), binary.BigEndian, &maxBandwidth)
54 |
55 | var rules = map[string]string{}
56 | rules["protocol-version"] = protocolVer
57 | rules["current-clients"] = fmt.Sprint(currentClients)
58 | rules["max-clients"] = fmt.Sprint(maxClients)
59 | rules["max-bandwidth"] = fmt.Sprint(maxBandwidth)
60 | if challenge != nil {
61 | rules["challenge"] = *challenge
62 | }
63 |
64 | v = MakeServerEntry()
65 | v.MaxClients = int64(maxClients)
66 | v.NumClients = int64(currentClients)
67 | v.Rules = rules
68 |
69 | return v, nil
70 | }
71 |
--------------------------------------------------------------------------------
/protocol_mumbles_test.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func TestParsePacket(t *testing.T) {
9 | var err error
10 | s1 := Packet{Id: "ping", Data: []byte("\x00\x01\x02\x05\x67\x72\x6F\x6B\x73\x74\x61\x74\x00\x00\x00\x02\x00\x00\x02\x00\x00\x01\x19\x40")}
11 | s2 := "grokstat"
12 | expectation := ServerEntry{NumClients: int64(2), MaxClients: int64(512), NeedPass: false, Players: []PlayerEntry{}, Rules: map[string]string{"protocol-version": "1.2.5", "current-clients": "2", "max-clients": "512", "max-bandwidth": "72000", "challenge": "grokstat"}}
13 |
14 | result, resultErr := MUMBLESparseData(s1.Data, &s2)
15 |
16 | if resultErr != nil {
17 | t.Errorf(resultErr.Error())
18 | }
19 |
20 | if len(result.Rules) != len(expectation.Rules) {
21 | err = CompError
22 | }
23 |
24 | for i := range result.Rules {
25 | if result.Rules[i] != expectation.Rules[i] {
26 | err = CompError
27 | }
28 | }
29 |
30 | if err != nil {
31 | fmt.Println(MapComparison(expectation.Rules, result.Rules))
32 | t.Errorf(ErrorOut(expectation.Rules, result.Rules))
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/protocol_openttdm.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "bytes"
4 |
5 | const (
6 | _ = iota
7 | SLT_IPV4 = iota
8 | SLT_IPV6 = iota
9 | )
10 |
11 | func OPENTTDMMakeProtocolTemplate() ProtocolEntry {
12 | return ProtocolEntry{Base: ProtocolEntryBase{MakePayloadFunc: MakePayload, RequestPackets: []RequestPacket{RequestPacket{Id: "servers4"}}, HandlerFunc: func(packet Packet, protocolCollection *ProtocolCollection, messageChan chan<- ConsoleMsg, protocolMappingInChan chan<- HostProtocolIdPair, serverEntryChan chan<- ServerEntry) (sendPackets []Packet) {
13 | return MasterReceiveHandler(OPENTTDMparsePacket, packet, protocolCollection, messageChan, protocolMappingInChan, serverEntryChan)
14 | }, HttpProtocol: "udp", ResponseType: "Server list"}, Information: ProtocolEntryInfo{"Name": "OpenTTD Master", "DefaultRequestPort": "3978", "ProtocolVer": string(byte(2)), "IPType": string(byte(0)), "RequestPreludeTemplate": "\x05\x00\x06{{.ProtocolVer}}{{.IPType}}"}}
15 | }
16 |
17 | func OPENTTDMparsePacket(p Packet, i ProtocolEntryInfo) ([]string, error) {
18 | return OPENTTDMparseData(p.Data)
19 | }
20 |
21 | func OPENTTDMparseData(data []byte) ([]string, error) {
22 | buf := bytes.NewBuffer(data)
23 |
24 | var servers = []string{}
25 |
26 | for buf.Len() > 0 {
27 | _ = buf.Next(2)
28 | var responseNum = int(buf.Next(1)[0])
29 | if responseNum != 7 {
30 | return nil, MalformedPacket
31 | }
32 | var ipVer = int(buf.Next(1)[0])
33 | if ipVer == SLT_IPV6 {
34 | return nil, IPv6NotSupported
35 | }
36 | var hostnumLE = buf.Next(2)
37 | var hostnum = int(hostnumLE[1])<<8 | int(hostnumLE[0])
38 |
39 | if buf.Len() < hostnum*6 {
40 | return nil, MalformedPacket
41 | }
42 |
43 | for i := 0; i < hostnum; i++ {
44 | entry, entryErr := ParseBinaryIPv4Entry(buf.Next(6), true)
45 | if entryErr == nil {
46 | servers = append(servers, entry)
47 | }
48 | }
49 | }
50 |
51 | return servers, nil
52 | }
53 |
--------------------------------------------------------------------------------
/protocol_openttdm_test.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "testing"
4 |
5 | func TestOPENTTDMparseData(t *testing.T) {
6 | var err error
7 | var s1 = Packet{Id: "servers4", Data: []byte("\x42\x00\x07\x01\x0A\x00\x4A\xD0\x4B\xB7\x8B\x0F\xAC\xF9\xB0\x91\x8B\x0F\x53\xC7\x18\x16\x8B\x0F\x3E\x8F\x2E\x44\x8B\x0F\x79\x2A\xA0\x97\x3E\x0F\x5C\xDE\x6E\x7C\x8B\x0F\x6C\x34\xE4\x4C\x8B\x0F\xB2\xEB\xB2\x57\x8B\x0F\x80\x48\x4A\x71\x8B\x0F\x40\x8A\xE7\x36\x8B\x0F\x42\x00\x07\x01\x01\x00\x4A\xD0\x4B\xB7\x8C\x0F")}
8 | expectation := []string{"74.208.75.183:3979", "172.249.176.145:3979", "83.199.24.22:3979", "62.143.46.68:3979", "121.42.160.151:3902", "92.222.110.124:3979", "108.52.228.76:3979", "178.235.178.87:3979", "128.72.74.113:3979", "64.138.231.54:3979", "74.208.75.183:3980"}
9 |
10 | result, resultErr := OPENTTDMparseData(s1.Data)
11 |
12 | if resultErr != nil {
13 | t.Errorf(resultErr.Error())
14 | }
15 |
16 | if len(result) != len(expectation) {
17 | err = CompError
18 | } else {
19 | for i := range result {
20 | if result[i] != expectation[i] {
21 | err = CompError
22 | break
23 | }
24 | }
25 | }
26 |
27 | if err != nil {
28 | t.Errorf(ErrorOut(expectation, result))
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/protocol_openttds.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "encoding/binary"
6 | "fmt"
7 | "strings"
8 |
9 | "github.com/skybon/goutil"
10 | )
11 |
12 | func OPENTTDSMakeProtocolTemplate() ProtocolEntry {
13 | return ProtocolEntry{Base: ProtocolEntryBase{MakePayloadFunc: MakePayload, RequestPackets: []RequestPacket{RequestPacket{Id: "info"}}, HandlerFunc: func(packet Packet, protocolCollection *ProtocolCollection, messageChan chan<- ConsoleMsg, protocolMappingInChan chan<- HostProtocolIdPair, serverEntryChan chan<- ServerEntry) (sendPackets []Packet) {
14 | return SimpleReceiveHandler(OPENTTDSparsePacket, packet, protocolCollection, messageChan, protocolMappingInChan, serverEntryChan)
15 | }, HttpProtocol: "udp", ResponseType: "Server info"}, Information: ProtocolEntryInfo{"Name": "OpenTTD Server", "PreludeStarter": "", "PreludeFinisher": "\x00\x00", "RequestPreludeTemplate": "{{.PreludeStarter}}\x03{{.PreludeFinisher}}", "DefaultRequestPort": "3979"}}
16 | }
17 |
18 | func OPENTTDSparsePacket(p Packet, protocolInfo ProtocolEntryInfo) (serverEntry ServerEntry, err error) {
19 | defer func() {
20 | if r := recover(); r != nil {
21 | serverEntry = MakeServerEntry()
22 | err = MalformedPacket
23 | }
24 | }()
25 | return OPENTTDSparseData(p.Data)
26 | }
27 |
28 | func OPENTTDSparseData(p []byte) (serverEntry ServerEntry, err error) {
29 | var infoData = bytes.NewBuffer(p[3:])
30 |
31 | var protocolVer = int(infoData.Next(1)[0])
32 |
33 | var activeNewGRFsNum int
34 | var activeNewGRFsInfo string
35 | if protocolVer >= 4 {
36 | activeNewGRFsNum = int(infoData.Next(1)[0])
37 | for n := 0; n < activeNewGRFsNum; n++ {
38 | NewGRFID := GetByteString(infoData.Next(4))
39 | NewGRFMD5 := GetByteString(infoData.Next(16))
40 | activeNewGRFsInfo = activeNewGRFsInfo + fmt.Sprintf("ID:%s/MD5:%s; ", NewGRFID, NewGRFMD5)
41 | }
42 | activeNewGRFsInfo = strings.Trim(activeNewGRFsInfo, " ;")
43 | }
44 |
45 | var timeCurrent uint32
46 | var timeStart uint32
47 | if protocolVer >= 3 {
48 | _ = binary.Read(bytes.NewReader(infoData.Next(4)), binary.BigEndian, &timeCurrent)
49 | _ = binary.Read(bytes.NewReader(infoData.Next(4)), binary.BigEndian, &timeStart)
50 | }
51 |
52 | var maxCompanies *int
53 | var currentCompanies *int
54 | var maxSpectators *int
55 | if protocolVer >= 2 {
56 | maxCompanies = goutil.IntP(int(infoData.Next(1)[0]))
57 | currentCompanies = goutil.IntP(int(infoData.Next(1)[0]))
58 | maxSpectators = goutil.IntP(int(infoData.Next(1)[0]))
59 | }
60 | serverNameBytes, _ := infoData.ReadBytes(byte(0))
61 | serverName := string(bytes.Trim(serverNameBytes, "\x00"))
62 |
63 | serverVersionBytes, _ := infoData.ReadBytes(byte(0))
64 | serverVersion := string(bytes.Trim(serverVersionBytes, "\x00"))
65 |
66 | languageId := int(infoData.Next(1)[0])
67 | needPass := bool(infoData.Next(1)[0] != 0)
68 | maxClients := int(infoData.Next(1)[0])
69 | currentClients := int(infoData.Next(1)[0])
70 | currentSpectators := int(infoData.Next(1)[0])
71 |
72 | if protocolVer < 3 {
73 | _ = infoData.Next(2)
74 | _ = infoData.Next(2)
75 | }
76 |
77 | mapNameBytes, _ := infoData.ReadBytes(byte(0))
78 | mapName := string(bytes.Trim(mapNameBytes, "\x00"))
79 |
80 | var mapWidth uint16
81 | _ = binary.Read(bytes.NewReader(infoData.Next(2)), binary.BigEndian, &mapWidth)
82 |
83 | var mapHeight uint16
84 | _ = binary.Read(bytes.NewReader(infoData.Next(2)), binary.BigEndian, &mapHeight)
85 |
86 | mapSet := int(infoData.Next(1)[0])
87 | dedicatedServer := int(infoData.Next(1)[0])
88 |
89 | var rules = map[string]string{}
90 | rules["protocol-version"] = fmt.Sprint(protocolVer)
91 | rules["active-newgrfs-num"] = fmt.Sprint(activeNewGRFsNum)
92 | rules["active-newgrfs"] = fmt.Sprint(activeNewGRFsInfo)
93 | rules["time-current"] = fmt.Sprint(timeCurrent)
94 | rules["time-start"] = fmt.Sprint(timeStart)
95 | if maxCompanies != nil {
96 | rules["max-companies"] = fmt.Sprint(*maxCompanies)
97 | }
98 | if currentCompanies != nil {
99 | rules["current-companies"] = fmt.Sprint(*currentCompanies)
100 | }
101 | if maxSpectators != nil {
102 | rules["max-spectators"] = fmt.Sprint(*maxSpectators)
103 | }
104 | rules["server-name"] = fmt.Sprint(serverName)
105 | rules["server-version"] = fmt.Sprint(serverVersion)
106 | rules["language-id"] = fmt.Sprint(languageId)
107 | rules["need-pass"] = fmt.Sprint(needPass)
108 | rules["max-clients"] = fmt.Sprint(maxClients)
109 | rules["current-clients"] = fmt.Sprint(currentClients)
110 | rules["current-spectators"] = fmt.Sprint(currentSpectators)
111 | rules["map-name"] = fmt.Sprint(mapName)
112 | rules["map-set"] = fmt.Sprint(mapSet)
113 | rules["dedicated"] = fmt.Sprint(dedicatedServer)
114 |
115 | serverEntry = ServerEntry{Name: string(serverName), MaxClients: int64(maxClients), NumClients: int64(currentClients), NeedPass: bool(needPass), Terrain: string(mapName), Rules: rules, Players: []PlayerEntry{}}
116 | return serverEntry, nil
117 | }
118 |
--------------------------------------------------------------------------------
/protocol_openttds_test.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func TestOPENTTDSparseData(t *testing.T) {
9 | var err error
10 | s1 := Packet{Id: "info", Data: []byte("\x86\x00\x01\x04\x03\x4D\x47\x03\x05\x2E\x96\xB9\xAB\x2B\xEA\x68\x6B\xFF\x94\x96\x1A\xD4\x33\xA7\x01\x32\x32\x33\x22\x31\x61\x80\xDA\x1B\xA6\x44\x4A\x06\xCD\x17\xF8\xFA\x79\xD6\x0A\x44\x4E\x07\x00\x48\xB3\xF9\xE4\xFD\x0D\xF2\xA7\x2B\x5F\x44\xD3\xC8\xA2\xF4\xA0\x63\xEC\x0A\x00\x63\xEC\x0A\x00\x0F\x00\x0A\x4F\x6E\x6C\x79\x46\x72\x69\x65\x6E\x64\x73\x20\x4F\x70\x65\x6E\x54\x54\x44\x20\x53\x65\x72\x76\x65\x72\x20\x23\x31\x00\x31\x2E\x35\x2E\x33\x00\x16\x00\x19\x00\x00\x52\x61\x6E\x64\x6F\x6D\x20\x4D\x61\x70\x00\x00\x04\x00\x04\x01\x01")}
11 | expectation := ServerEntry{Name: "OnlyFriends OpenTTD Server #1", Terrain: "Random Map", NumClients: int64(0), MaxClients: int64(25), NeedPass: false, Players: []PlayerEntry{}, Rules: map[string]string{"protocol-version": "4", "active-newgrfs-num": "3", "active-newgrfs": "ID:4d470305/MD5:2e96b9ab2bea686bff94961ad433a701; ID:32323322/MD5:316180da1ba6444a06cd17f8fa79d60a; ID:444e0700/MD5:48b3f9e4fd0df2a72b5f44d3c8a2f4a0", "time-current": "1676413440", "time-start": "1676413440", "max-companies": "15", "current-companies": "0", "max-spectators": "10", "server-name": "OnlyFriends OpenTTD Server #1", "server-version": "1.5.3", "language-id": "22", "need-pass": "false", "max-clients": "25", "current-clients": "0", "current-spectators": "0", "map-name": "Random Map", "map-set": "1", "dedicated": "1"}}
12 |
13 | result, resultErr := OPENTTDSparseData(s1.Data)
14 |
15 | if resultErr != nil {
16 | t.Errorf(resultErr.Error())
17 | }
18 |
19 | if len(result.Rules) != len(expectation.Rules) {
20 | err = CompError
21 | }
22 |
23 | for i := range result.Rules {
24 | if result.Rules[i] != expectation.Rules[i] {
25 | err = CompError
26 | }
27 | }
28 |
29 | if err != nil {
30 | fmt.Println(MapComparison(expectation.Rules, result.Rules))
31 | t.Errorf(ErrorOut(expectation.Rules, result.Rules))
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/protocol_q3m.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "math"
6 | )
7 |
8 | func Q3MMakeProtocolTemplate() ProtocolEntry {
9 | return ProtocolEntry{Base: ProtocolEntryBase{MakePayloadFunc: MakePayload, RequestPackets: []RequestPacket{RequestPacket{Id: "servers"}}, HandlerFunc: func(packet Packet, protocolCollection *ProtocolCollection, messageChan chan<- ConsoleMsg, protocolMappingInChan chan<- HostProtocolIdPair, serverEntryChan chan<- ServerEntry) (sendPackets []Packet) {
10 | return MasterReceiveHandler(Q3MParsePacket, packet, protocolCollection, messageChan, protocolMappingInChan, serverEntryChan)
11 | }, HttpProtocol: "udp", ResponseType: "Server list"}, Information: ProtocolEntryInfo{"Name": "Quake III Arena Master", "SplitterUsed": "true", "PreludeStarter": "\xFF\xFF\xFF\xFF", "RequestQueryParams": "empty full", "RequestPreludeTemplate": "{{.PreludeStarter}}getservers {{.Version}} {{.RequestQueryParams}}\n", "ResponsePreludeTemplate": "{{.PreludeStarter}}getserversResponse", "Version": "68", "DefaultRequestPort": "27950"}}
12 | }
13 |
14 | // Parses the response from Quake III Arena master server.
15 | func Q3MParsePacket(p Packet, protocolInfo ProtocolEntryInfo) ([]string, error) {
16 | data := p.Data
17 | responsePreludeTemplate, _ := protocolInfo["ResponsePreludeTemplate"]
18 | splitterUsed, _ := protocolInfo["SplitterUsed"]
19 |
20 | var header = []byte(ParseTemplate(responsePreludeTemplate, protocolInfo))
21 |
22 | var payload, rOk = CheckPrelude(data, header)
23 |
24 | if !rOk {
25 | return nil, InvalidResponseHeader
26 | }
27 |
28 | var servers = []string{}
29 |
30 | var splitter = []byte{0x5c}
31 | var payloadSplit [][]byte
32 | if splitterUsed == "true" {
33 | payloadSplit = bytes.Split(payload, splitter)
34 | } else {
35 | if math.Mod(float64(len(payload)), 6.0) != 0.0 {
36 | return nil, InvalidResponseLength
37 | }
38 | for i := 0; i < int(len(payload)/6.0); i++ {
39 | payloadSplit = append(payloadSplit, payload[i:i+6])
40 | }
41 | }
42 | for _, entryRaw := range payloadSplit {
43 | var serverEntry, entryErr = ParseBinaryIPv4Entry(entryRaw, false)
44 |
45 | if entryErr == nil {
46 | servers = append(servers, serverEntry)
47 | }
48 | }
49 | return servers, nil
50 | }
51 |
--------------------------------------------------------------------------------
/protocol_q3s.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "math"
6 | "strconv"
7 | "strings"
8 | "time"
9 | )
10 |
11 | func Q3SMakeProtocolTemplate() ProtocolEntry {
12 | return ProtocolEntry{Base: ProtocolEntryBase{MakePayloadFunc: MakePayload, RequestPackets: []RequestPacket{RequestPacket{Id: "status", ResponsePacketNum: 1}}, HandlerFunc: func(packet Packet, protocolCollection *ProtocolCollection, messageChan chan<- ConsoleMsg, protocolMappingInChan chan<- HostProtocolIdPair, serverEntryChan chan<- ServerEntry) (sendPackets []Packet) {
13 | return SimpleReceiveHandler(Q3SParsePacket, packet, protocolCollection, messageChan, protocolMappingInChan, serverEntryChan)
14 | }, HttpProtocol: "udp", ResponseType: "Server info"}, Information: ProtocolEntryInfo{"Name": "Quake III Arena", "PreludeStarter": "\xFF\xFF\xFF\xFF", "Challenge": "GrokStat_" + string(time.Now().Unix()), "RequestPreludeTemplate": "{{.PreludeStarter}}getstatus {{.Challenge}}\n", "headerTemplate": "{{.PreludeStarter}}statusResponse", "ServerNameRule": "sv_hostname", "NeedPassRule": "g_needpass", "TerrainRule": "mapname", "ModNameRule": "game", "GameTypeRule": "g_gametype", "MaxClientsRule": "sv_maxclients", "SecureRule": "sv_punkbuster", "Version": "68", "DefaultRequestPort": "27950"}}
15 | }
16 |
17 | func Q3SParsePlayerstring(arr [][]byte) []PlayerEntry {
18 | var v = []PlayerEntry{}
19 | for _, b := range arr {
20 | s := bytes.Split(b, []byte(" "))
21 | if len(s) < 3 {
22 | continue
23 | }
24 | ping, _ := strconv.ParseInt(string(s[1]), 10, 64)
25 | e := MakePlayerEntry()
26 | e.Name = strings.Trim(string(bytes.Join(s[2:], []byte(" "))), `"`)
27 | e.Ping = ping
28 | e.Info["Score"] = string(s[0])
29 | v = append(v, e)
30 | }
31 | return v
32 | }
33 |
34 | func Q3SParseRulestring(str [][]byte) map[string]string {
35 | var ruleArray = map[int][]string{}
36 | var m = map[string]string{}
37 | for i, e := range str {
38 | vstr := string(e)
39 | if len(vstr) == 0 {
40 | continue
41 | }
42 | if math.Mod(float64(i), 2) != 0 {
43 | ruleArray[i] = []string{vstr} // Key
44 | } else {
45 | ruleArray[i-1] = append(ruleArray[i-1], vstr) // Value
46 | }
47 | }
48 | for _, e := range ruleArray {
49 | if len(e) < 2 {
50 | continue
51 | }
52 | var k = e[0]
53 | var v = e[1]
54 | m[k] = v
55 | }
56 |
57 | return m
58 | }
59 |
60 | // Parses the response from Quake III Arena server
61 | func Q3SParsePacket(p Packet, info ProtocolEntryInfo) (entry ServerEntry, err error) {
62 | defer func() {
63 | if r := recover(); r != nil {
64 | err = MalformedPacket
65 | }
66 | }()
67 | packetPing := p.Ping
68 | response := p.Data
69 | headerTemplate, _ := info["headerTemplate"]
70 | header := []byte(ParseTemplate(headerTemplate, info))
71 |
72 | sepBody := []byte{0xa}
73 | sepRules := []byte{0x5c}
74 |
75 | if bytes.Equal(response[:len(header)], header) != true {
76 | return entry, InvalidResponseHeader
77 | }
78 |
79 | payload := bytes.Trim(response[len(header):], string(sepBody))
80 | payloadSplit := bytes.Split(payload, sepBody)
81 |
82 | rulePlayerBoundary := len(payloadSplit)
83 | for i, line := range payloadSplit {
84 | if line[0] != sepRules[0] {
85 | rulePlayerBoundary = i
86 | break
87 | }
88 | }
89 |
90 | ruleByteArray := bytes.Join(payloadSplit[:rulePlayerBoundary], sepRules)
91 | playerByteArray := payloadSplit[rulePlayerBoundary:]
92 |
93 | ruleByteArraySplit := bytes.Split(ruleByteArray, sepRules)
94 |
95 | var players = Q3SParsePlayerstring(playerByteArray)
96 | var rules = Q3SParseRulestring(ruleByteArraySplit)
97 |
98 | entry = MakeServerEntry()
99 | entry.Ping = packetPing
100 | entry.Players = players
101 | entry.NumClients = int64(len(players))
102 | entry.Rules = rules
103 |
104 | serverNameRule, serverNameRuleOk := info["ServerNameRule"]
105 | if serverNameRuleOk {
106 | serverName, _ := rules[serverNameRule]
107 | entry.Name = strings.TrimSpace(serverName)
108 | }
109 |
110 | needPassRule, needPassRuleOk := info["NeedPassRule"]
111 | if needPassRuleOk {
112 | needPass, _ := rules[needPassRule]
113 | entry.NeedPass, _ = strconv.ParseBool(needPass)
114 | }
115 |
116 | terrainRule, terrainRuleOk := info["TerrainRule"]
117 | if terrainRuleOk {
118 | terrain, _ := rules[terrainRule]
119 | entry.Terrain = strings.TrimSpace(terrain)
120 | }
121 |
122 | modNameRule, modNameRuleOk := info["ModNameRule"]
123 | if modNameRuleOk {
124 | modName, _ := rules[modNameRule]
125 | entry.ModName = strings.TrimSpace(modName)
126 | }
127 |
128 | gameTypeRule, gameTypeRuleOk := info["GameTypeRule"]
129 | if gameTypeRuleOk {
130 | gameType, _ := rules[gameTypeRule]
131 | entry.GameType = strings.TrimSpace(gameType)
132 | }
133 |
134 | secureRule, secureRuleOk := info["SecureRule"]
135 | if secureRuleOk {
136 | secure, _ := rules[secureRule]
137 | entry.Secure, _ = strconv.ParseBool(secure)
138 | }
139 |
140 | maxClientsRule, maxClientsRuleOk := info["MaxClientsRule"]
141 | if maxClientsRuleOk {
142 | maxClients, maxClientsOk := rules[maxClientsRule]
143 | if maxClientsOk {
144 | entry.MaxClients, _ = strconv.ParseInt(strings.TrimSpace(maxClients), 10, 64)
145 | }
146 | }
147 |
148 | numBotsRule, numBotsRuleOk := info["NumBotsRule"]
149 | if numBotsRuleOk {
150 | numBots, numBotsOk := rules[numBotsRule]
151 | if numBotsOk {
152 | entry.NumBots, _ = strconv.ParseInt(strings.TrimSpace(numBots), 10, 64)
153 | }
154 | }
155 |
156 | return entry, nil
157 | }
158 |
--------------------------------------------------------------------------------
/protocol_steam.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | "math"
7 | )
8 |
9 | func STEAMMakeProtocolTemplate() ProtocolEntry {
10 | return ProtocolEntry{Base: ProtocolEntryBase{MakePayloadFunc: MakeSteamPayload, RequestPackets: []RequestPacket{RequestPacket{Id: "STEAM_REQUEST"}}, HandlerFunc: SteamHandler, HttpProtocol: "udp", ResponseType: "Server list"}, Information: ProtocolEntryInfo{"Name": "Steam Master", "DefaultRequestPort": "27011", "ResponsePreludeTemplate": "\xFF\xFF\xFF\xFF\x66\x0A"}}
11 | }
12 |
13 | func makeSteamRequest(lastIp string) []byte {
14 | return []byte(fmt.Sprintf("\x31\xff%s\x00\x00", lastIp))
15 | }
16 |
17 | func MakeSteamRequestPacket(packetId string, protocolInfo ProtocolEntryInfo) Packet {
18 | return Packet{Data: makeSteamRequest("0.0.0.0:0")}
19 | }
20 |
21 | func MakeSteamPayload(packet Packet, protocolEntryInfo ProtocolEntryInfo) Packet {
22 | if packet.Id == "STEAM_REQUEST" {
23 | packet.Data = makeSteamRequest("0.0.0.0:0")
24 | }
25 |
26 | return packet
27 | }
28 |
29 | func SteamHandler(packet Packet, protocolCollection *ProtocolCollection, messageChan chan<- ConsoleMsg, protocolMappingInChan chan<- HostProtocolIdPair, serverEntryChan chan<- ServerEntry) (sendPackets []Packet) {
30 | sendPackets = make([]Packet, 0)
31 |
32 | protocolId := packet.ProtocolId
33 | protocol, protocolExists := protocolCollection.Get(protocolId)
34 | if !protocolExists {
35 | return sendPackets
36 | }
37 | protocolInfo := protocol.Information
38 | remoteIp := packet.RemoteAddr
39 |
40 | preludeTemplate, pTOk := protocolInfo["ResponsePreludeTemplate"]
41 | var body []byte
42 | var preludeOk bool
43 | if pTOk {
44 | prelude := []byte(preludeTemplate)
45 | body, preludeOk = CheckPrelude(packet.Data, prelude)
46 | } else {
47 | body = packet.Data
48 | preludeOk = true
49 | }
50 |
51 | if preludeOk {
52 | bodyOk := math.Mod(float64(len(body)), 6.0) == 0
53 | if !bodyOk {
54 | messageChan <- ConsoleMsg{Type: MSG_MINOR, Message: fmt.Sprintf("STEAM - %s - Invalid body length.", remoteIp)}
55 | return sendPackets
56 | }
57 |
58 | pairList := []HostProtocolIdPair{}
59 |
60 | ipBuf := bytes.NewBuffer(body)
61 | for {
62 | ipAddrRaw := ipBuf.Next(6)
63 | ipAddr, ipErr := ParseBinaryIPv4Entry(ipAddrRaw, false)
64 | if ipErr != nil {
65 | messageChan <- ConsoleMsg{Type: MSG_MINOR, Message: fmt.Sprintf("STEAM - %s - Error parsing IP in response.", remoteIp)}
66 | return sendPackets
67 | }
68 | masterOf, mOk := protocolInfo["MasterOf"]
69 | if mOk {
70 | pair := HostProtocolIdPair{RemoteAddr: ipAddr, ProtocolId: masterOf}
71 | protocolMappingInChan <- pair
72 | pairList = append(pairList, pair)
73 | }
74 | if ipBuf.Len() == 0 {
75 | break
76 | }
77 | }
78 |
79 | lastIp := pairList[len(pairList)-1].RemoteAddr
80 |
81 | messageChan <- ConsoleMsg{Type: MSG_DEBUG, Message: fmt.Sprintf("STEAM - %s - Last IP: %s.", remoteIp, lastIp)}
82 | if lastIp == "0.0.0.0:0" {
83 | messageChan <- ConsoleMsg{Type: MSG_DEBUG, Message: "STEAM: Query complete."}
84 | } else {
85 | sendPacket := Packet{Id: "STEAM_REQUEST", Data: []byte(makeSteamRequest(lastIp)), RemoteAddr: remoteIp, ProtocolId: "STEAM"}
86 | sendPackets = append(sendPackets, sendPacket)
87 | }
88 |
89 | for _, pair := range pairList {
90 | sendPackets = append(sendPackets, MakeSendPackets(pair, protocolCollection)...)
91 | }
92 |
93 | masterServerEntry := ServerEntry{Protocol: packet.ProtocolId, Host: packet.RemoteAddr, Name: "Steam Master Server"}
94 | serverEntryChan <- masterServerEntry
95 |
96 | } else {
97 | messageChan <- ConsoleMsg{Type: MSG_MINOR, Message: fmt.Sprintf("STEAM - %s - Prelude Error", remoteIp)}
98 | }
99 | return sendPackets
100 | }
101 |
--------------------------------------------------------------------------------
/protocol_teeworldsm.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | )
7 |
8 | func TEEWORLDSMMakeProtocolTemplate() ProtocolEntry {
9 | return ProtocolEntry{Base: ProtocolEntryBase{MakePayloadFunc: MakePayload, RequestPackets: []RequestPacket{RequestPacket{Id: "servers"}}, HandlerFunc: func(packet Packet, protocolCollection *ProtocolCollection, messageChan chan<- ConsoleMsg, protocolMappingInChan chan<- HostProtocolIdPair, serverEntryChan chan<- ServerEntry) (sendPackets []Packet) {
10 | return MasterReceiveHandler(TEEWORLDSMparsePacket, packet, protocolCollection, messageChan, protocolMappingInChan, serverEntryChan)
11 | }, HttpProtocol: "udp", ResponseType: "Server list"}, Information: ProtocolEntryInfo{"Name": "Teeworlds Master", "RequestPreludeStarter": "\x20\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF", "RequestPreludeTemplate": "{{.RequestPreludeStarter}}req2", "ResponsePreludeStarter": "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", "ResponsePreludeTemplate": "{{.ResponsePreludeStarter}}lis2", "DefaultRequestPort": "8300"}}
12 | }
13 |
14 | func parseMasterServerEntry(entryRaw []byte) (string, error) {
15 | if len(entryRaw) != 8 {
16 | return "", InvalidServerEntryInMasterResponse
17 | }
18 |
19 | if entryRaw[0] != byte(0xff) || entryRaw[1] != byte(0xff) {
20 | return "", InvalidServerEntryInMasterResponse
21 | }
22 |
23 | entry := make([]int, 6)
24 | for i, v := range entryRaw[2:] {
25 | entry[i] = int(v)
26 | }
27 | a := entry[0]
28 | b := entry[1]
29 | c := entry[2]
30 | d := entry[3]
31 | port := entry[4]*(16*16) + entry[5]
32 |
33 | if a == 0 {
34 | return "", InvalidServerEntryInMasterResponse
35 | }
36 |
37 | serverEntry := fmt.Sprintf("%d.%d.%d.%d:%d", a, b, c, d, port)
38 |
39 | return serverEntry, nil
40 | }
41 |
42 | // Parses the response from Teeworlds master server.
43 | func TEEWORLDSMparsePacket(responsePacket Packet, protocolInfo ProtocolEntryInfo) ([]string, error) {
44 | response := responsePacket.Data
45 | responsePreludeTemplate, _ := protocolInfo["ResponsePreludeTemplate"]
46 | responsePrelude := []byte(ParseTemplate(responsePreludeTemplate, protocolInfo))
47 |
48 | splitter := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
49 |
50 | servers := []string{}
51 |
52 | if bytes.Equal(response[:len(responsePrelude)], responsePrelude) != true {
53 | return nil, InvalidResponseHeader
54 | }
55 |
56 | responseBody := response[len(responsePrelude):]
57 | responseBodySplit := bytes.Split(responseBody, splitter)
58 | for _, entryRaw := range responseBodySplit {
59 | serverEntry, entryErr := parseMasterServerEntry(entryRaw)
60 |
61 | if entryErr == nil {
62 | servers = append(servers, serverEntry)
63 | }
64 | }
65 | return servers, nil
66 | }
67 |
--------------------------------------------------------------------------------
/protocol_teeworldss.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "math"
6 | "strconv"
7 | "strings"
8 | )
9 |
10 | func TEEWORLDSSMakeProtocolTemplate() ProtocolEntry {
11 | return ProtocolEntry{Base: ProtocolEntryBase{MakePayloadFunc: MakePayload, RequestPackets: []RequestPacket{RequestPacket{Id: "info"}}, HandlerFunc: func(packet Packet, protocolCollection *ProtocolCollection, messageChan chan<- ConsoleMsg, protocolMappingInChan chan<- HostProtocolIdPair, serverEntryChan chan<- ServerEntry) (sendPackets []Packet) {
12 | return SimpleReceiveHandler(TEEWORLDSSparsePacket, packet, protocolCollection, messageChan, protocolMappingInChan, serverEntryChan)
13 | }, HttpProtocol: "udp", ResponseType: "Server info"}, Information: ProtocolEntryInfo{"Name": "Teeworlds Server", "PreludeStarter": "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", "PreludeFinisher": "\x00", "RequestPreludeTemplate": "{{.PreludeStarter}}gie3{{.PreludeFinisher}}", "ResponsePreludeTemplate": "{{.PreludeStarter}}inf3", "DefaultRequestPort": "8305"}}
14 | }
15 |
16 | func parsePlayerstring(playerByteArray [][]byte) ([]PlayerEntry, error) {
17 | if math.Mod(float64(len(playerByteArray)), float64(5)) != 0.0 {
18 | return nil, InvalidPlayerStringLength
19 | }
20 |
21 | var playerArray = []PlayerEntry{}
22 |
23 | playerNum := int(len(playerByteArray) / 5)
24 | for i := 0; i < playerNum; i++ {
25 | entryRaw := playerByteArray[i*5 : i*5+5]
26 | playerEntry := MakePlayerEntry()
27 | playerEntry.Name = string(entryRaw[0])
28 | playerEntry.Info["clan"] = string(entryRaw[1])
29 | playerEntry.Info["country"] = string(entryRaw[2])
30 | playerEntry.Info["score"] = string(entryRaw[3])
31 | playerEntry.Info["is_player"] = string(entryRaw[4])
32 |
33 | playerArray = append(playerArray, playerEntry)
34 | }
35 | return playerArray, nil
36 | }
37 |
38 | func parseRulestring(rulestring [][]byte) (map[string]string, error) {
39 | if len(rulestring) < 10 {
40 | return map[string]string{}, InvalidRuleStringLength
41 | }
42 |
43 | ruleMap := make(map[string]string)
44 |
45 | ruleMap["token"] = string(rulestring[0])
46 | ruleMap["version"] = string(rulestring[1])
47 | ruleMap["name"] = string(rulestring[2])
48 | ruleMap["map"] = string(rulestring[3])
49 | ruleMap["gametype"] = string(rulestring[4])
50 | ruleMap["flags"] = string(rulestring[5])
51 | ruleMap["num_players"] = string(rulestring[6])
52 | ruleMap["max_players"] = string(rulestring[7])
53 | ruleMap["num_clients"] = string(rulestring[8])
54 | ruleMap["max_clients"] = string(rulestring[9])
55 |
56 | return ruleMap, nil
57 | }
58 |
59 | func TEEWORLDSSParseData(data [][]byte) (ServerEntry, error) {
60 | var v = MakeServerEntry()
61 |
62 | rulePlayerBoundary := 10
63 |
64 | var ruleByteArray [][]byte
65 | var playerByteArray [][]byte
66 | if len(data) >= rulePlayerBoundary {
67 | ruleByteArray = data[:rulePlayerBoundary]
68 | }
69 |
70 | if len(data) > rulePlayerBoundary {
71 | playerByteArray = data[rulePlayerBoundary:]
72 | }
73 |
74 | if len(data) < rulePlayerBoundary {
75 | return MakeServerEntry(), InvalidResponseLength
76 | }
77 |
78 | players, playerErr := parsePlayerstring(playerByteArray)
79 | if playerErr != nil {
80 | return MakeServerEntry(), playerErr
81 | }
82 |
83 | rules, ruleErr := parseRulestring(ruleByteArray)
84 | if ruleErr != nil {
85 | return MakeServerEntry(), ruleErr
86 | }
87 |
88 | v.Players = players
89 |
90 | hostName, _ := rules["name"]
91 | v.Name = strings.TrimSpace(hostName)
92 |
93 | needPass, _ := rules["flags"]
94 | v.NeedPass, _ = strconv.ParseBool(needPass)
95 |
96 | terrain, _ := rules["map"]
97 | v.Terrain = strings.TrimSpace(terrain)
98 |
99 | v.ModName = "Teeworlds"
100 |
101 | gameType, _ := rules["gametype"]
102 | v.GameType = strings.TrimSpace(gameType)
103 |
104 | v.NumClients = int64(len(players))
105 |
106 | maxClients, nc_ok := rules["max_clients"]
107 | if nc_ok {
108 | v.MaxClients, _ = strconv.ParseInt(strings.TrimSpace(maxClients), 10, 64)
109 | }
110 |
111 | v.Secure = false
112 |
113 | v.Rules = rules
114 |
115 | return v, nil
116 | }
117 |
118 | // Parses the response from Quake III Arena server
119 | func TEEWORLDSSparsePacket(p Packet, protocolInfo ProtocolEntryInfo) (ServerEntry, error) {
120 | packetPing := p.Ping
121 | response := p.Data
122 | responsePreludeTemplate, _ := protocolInfo["ResponsePreludeTemplate"]
123 | responsePrelude := []byte(ParseTemplate(responsePreludeTemplate, protocolInfo))
124 |
125 | var sep = []byte{0x0}
126 |
127 | if bytes.Equal(response[:len(responsePrelude)], responsePrelude) != true {
128 | return MakeServerEntry(), InvalidResponseHeader
129 | }
130 |
131 | b := bytes.Trim(response[len(responsePrelude):], string(sep))
132 |
133 | var entry, err = TEEWORLDSSParseData(bytes.Split(b, sep))
134 | if err != nil {
135 | return entry, err
136 | }
137 |
138 | entry.Ping = packetPing
139 |
140 | return entry, nil
141 | }
142 |
--------------------------------------------------------------------------------
/protocols.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "sync"
4 |
5 | type ProtocolConfig struct {
6 | Id string `toml:"Id"`
7 | Template string `toml:"Template"`
8 | Overrides map[string]string `toml:"Overrides"`
9 | }
10 |
11 | type ProtocolCollection struct {
12 | sync.Mutex
13 | data map[string]ProtocolEntry
14 | }
15 |
16 | func (c *ProtocolCollection) Get(k string) (ProtocolEntry, bool) {
17 | c.Lock()
18 | defer c.Unlock()
19 | var v, exists = c.data[k]
20 | return v, exists
21 | }
22 |
23 | func (c *ProtocolCollection) Set(k string, v ProtocolEntry) {
24 | c.Lock()
25 | defer c.Unlock()
26 | c.data[k] = v
27 | }
28 |
29 | func (c *ProtocolCollection) Delete(k string) {
30 | c.Lock()
31 | defer c.Unlock()
32 | delete(c.data, k)
33 | }
34 |
35 | func (c *ProtocolCollection) Map() map[string]ProtocolEntry {
36 | c.Lock()
37 | defer c.Unlock()
38 |
39 | var m = make(map[string]ProtocolEntry, len(c.data))
40 | for k, v := range c.data {
41 | m[k] = v
42 | }
43 | return m
44 | }
45 |
46 | func MakeProtocolCollection() *ProtocolCollection {
47 | return &ProtocolCollection{data: map[string]ProtocolEntry{}}
48 | }
49 |
50 | // Returns a map with protocols initialized
51 | func LoadProtocols(configData []ProtocolConfig) *ProtocolCollection {
52 | infoBase := ProtocolEntryInfo{`x20`: "\x20", `xFF`: "\xFF"}
53 |
54 | templates := make(map[string]func() ProtocolEntry)
55 |
56 | templates["Q3M"] = Q3MMakeProtocolTemplate
57 | templates["Q3S"] = Q3SMakeProtocolTemplate
58 | templates["TEEWORLDSM"] = TEEWORLDSMMakeProtocolTemplate
59 | templates["TEEWORLDSS"] = TEEWORLDSSMakeProtocolTemplate
60 | templates["OPENTTDM"] = OPENTTDMMakeProtocolTemplate
61 | templates["OPENTTDS"] = OPENTTDSMakeProtocolTemplate
62 | templates["STEAM"] = STEAMMakeProtocolTemplate
63 | templates["A2S"] = A2SMakeProtocolTemplate
64 | templates["MUMBLES"] = MUMBLESMakeProtocolTemplate
65 |
66 | var protMap = make(map[string]ProtocolEntry, len(templates))
67 | for k, v := range templates {
68 | entry := v()
69 | for k1, v1 := range infoBase {
70 | entry.Information[k1] = v1
71 | }
72 | protMap[k] = entry
73 | }
74 |
75 | var m = MakeProtocolCollection()
76 |
77 | for _, configEntry := range configData {
78 | entryId := configEntry.Id
79 | templateId := configEntry.Template
80 | overrides := configEntry.Overrides
81 |
82 | entryTemplate, eOk := protMap[templateId]
83 | if eOk == false {
84 | continue
85 | }
86 | protocolEntry := MakeProtocolEntry(entryTemplate)
87 | for k, v := range overrides {
88 | protocolEntry.Information[k] = v
89 | }
90 | protocolEntry.Id = entryId
91 | protocolEntry.Information["Id"] = entryId
92 |
93 | m.Set(entryId, protocolEntry)
94 | }
95 |
96 | return m
97 | }
98 |
--------------------------------------------------------------------------------
/util.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | "os"
7 | "sort"
8 | "text/template"
9 | "time"
10 | )
11 |
12 | func ParseTemplate(templ string, keys map[string]string) string {
13 | buf := new(bytes.Buffer)
14 | t, _ := template.New("New template").Parse(templ)
15 | t.Execute(buf, keys)
16 | return buf.String()
17 | }
18 |
19 | func RemoveDuplicates(ListA []string) []string {
20 | tempDict := make(map[string]bool, len(ListA))
21 | for _, entry := range ListA {
22 | tempDict[entry] = true
23 | }
24 |
25 | ListB := make([]string, 0, len(tempDict))
26 | for entry, _ := range tempDict {
27 | ListB = append(ListB, entry)
28 | }
29 | return ListB
30 | }
31 |
32 | func CheckError(err error) {
33 | if err != nil {
34 | fmt.Printf("Error: %s\n", err.Error())
35 | os.Exit(0)
36 | }
37 | }
38 |
39 | func ByteLEToInt64(byteArray []byte) int64 {
40 | var result int64
41 | j := uint(0)
42 | for i := 0; i < len(byteArray); i++ {
43 | result += int64(byteArray[i]) << j
44 | j += 8
45 | }
46 | return result
47 | }
48 |
49 | func ConvertByteArray32to8(byteArray []byte) []byte {
50 | newByteArray := make([]byte, len(byteArray)*2)
51 | i := 0
52 | for _, v := range byteArray {
53 | newByteArray[i] = v / 16
54 | i += 1
55 | newByteArray[i] = v - (v * (v / 16))
56 | i += 1
57 | }
58 | return newByteArray
59 | }
60 |
61 | func Clamp(value, min, max int) int {
62 | clamp := sort.IntSlice([]int{value, min, max})
63 | clamp.Sort()
64 | return clamp[1]
65 | }
66 |
67 | func GetByteString(byteArray []byte) string {
68 | return fmt.Sprintf("%x", byteArray)
69 | }
70 |
71 | func Print(enabled bool, data interface{}) {
72 | if enabled != true {
73 | return
74 | }
75 | fmt.Print(data)
76 | }
77 |
78 | func PrintWait(enabled bool, interval int, active chan struct{}) {
79 | if enabled != true {
80 | return
81 | }
82 | for {
83 | select {
84 | default:
85 | os.Stdout.Write([]byte("."))
86 | os.Stdout.Sync()
87 | time.Sleep(time.Duration(interval) * time.Millisecond)
88 | case <-active:
89 | return
90 | }
91 | }
92 | }
93 |
94 | func PrintReplace(enabled bool, data string, replaceLength int) (newLength int) {
95 | if enabled != true {
96 | return
97 | }
98 | for i := 0; i < replaceLength; i++ {
99 | fmt.Print("\033[D")
100 | }
101 | fmt.Print(data)
102 | newLength = len(data)
103 | return newLength
104 | }
105 |
106 | func PrintEmptyLine(enabled bool) {
107 | if enabled != true {
108 | return
109 | }
110 | fmt.Print("\n")
111 | }
112 |
113 | func ErrorOut(expectation interface{}, result interface{}) string {
114 | return fmt.Sprintf("\nExpected:\n%+v\n\nReceived:\n%+v\n", expectation, result)
115 | }
116 |
117 | func MapComparison(A, B map[string]string) (length, keys string) {
118 | length = fmt.Sprintf("Length:\nA:%d\nB:%d\n\n", len(A), len(B))
119 | for k, _ := range A {
120 | keys = keys + fmt.Sprintf("\nKey: %s\nA: %s\nB: %s\n", k, A[k], B[k])
121 | }
122 | return length, keys
123 | }
124 |
--------------------------------------------------------------------------------
/util_test.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "testing"
4 |
5 | func TestByteLEToInt64(t *testing.T) {
6 | var err error
7 | s1 := []byte{0x60, 0x09}
8 | expectation := int64(2400)
9 |
10 | result := ByteLEToInt64(s1)
11 |
12 | if result != expectation {
13 | err = CompError
14 | }
15 |
16 | if err != nil {
17 | t.Errorf(ErrorOut(expectation, result))
18 | }
19 | }
20 |
--------------------------------------------------------------------------------