commit 740ef1bfbf1acb540feb77281b68d2863bb7b4a6 Author: Dan Bastone Date: Fri Oct 29 14:41:03 2021 -0400 initial commit (with submodule) diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..94b3b47 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "pjproject"] + path = pjproject + url = https://github.com/pjsip/pjproject diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/COPYING @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..f61e331 --- /dev/null +++ b/Makefile @@ -0,0 +1,26 @@ +PJSIP_DIR=pjproject-2.11.1 +PKG_CONFIG_PATH=pjsip.install/lib/pkgconfig + +all: d-modem slmodemd + +$(PKG_CONFIG_PATH)/libpjproject.pc: + (cd $(PJSIP_DIR); [ -f ./config.status ] || ./configure --prefix=`pwd`/../pjsip.install --disable-video) + $(MAKE) -C $(PJSIP_DIR) && \ + $(MAKE) -C $(PJSIP_DIR) install + +d-modem: d-modem.c $(PKG_CONFIG_PATH)/libpjproject.pc + $(CC) -o $@ $< `PKG_CONFIG_PATH="$(PKG_CONFIG_PATH)" pkg-config --static --cflags --libs libpjproject` + +slmodemd: + $(MAKE) -C slmodemd + +clean: + rm -f d-modem.o d-modem + $(MAKE) -C slmodemd clean + +realclean: clean + $(MAKE) -C $(PJSIP_DIR) realclean + rm -rf pjsip.install/* + + +.PHONY: all clean realclean slmodemd diff --git a/README.md b/README.md new file mode 100644 index 0000000..efecfe9 --- /dev/null +++ b/README.md @@ -0,0 +1,71 @@ +# D-Modem +Connect to dialup modems over VoIP using SIP, no modem hardware required. + +https://www.aon.com/cyber-solutions/aon_cyber_labs/introducing-d-modem-a-software-sip-modem/ + +## Building +You'll need Linux and a working 32-bit development environment (gcc -m32 needs to work, Debian-based systems can install libc6-dev-i386), along with PJSIP's dependencies (OpenSSL). Then run 'make' from the top-level directory. + +## How it Works +Traditional “controller-based” modems generally used a microcontroller and a DSP to handle all aspects of modem communication on the device itself. Later, so-called “Winmodems” were introduced that allowed for field-programmable DSPs and moved the controller and other functionality into software running on the host PC. This was followed by “pure software” modems that moved DSP functionality to the host as well. The physical hardware of these softmodems was only used to connect to the phone network, and all processing was done in software. + +D-Modem replaces a softmodem’s physical hardware with a SIP stack. Instead of passing audio to and from the software DSP over an analog phone line, audio travels via the RTP (or SRTP) media streams of a SIP VoIP call. + +## Usage +The repository contains two applications: + +slmodemd – A stripped down and patched version of Debian’s sl-modem-daemon package. All kernel driver code has been replaced with socket-based communication, allowing external applications to manage audio streams. + +d-modem – External application that interfaces with slmodemd to manage SIP calls and their associated audio streams. + +After they have been built, you will need to configure SIP account information in the SIP_LOGIN environment variable: + + # export SIP_LOGIN=username:password@sip.example.com +Next, run slmodemd, passing the path to d-modem in the -e option. Use -d for debug logging. + + # ./slmodemd/slmodemd -d9 -e ./d-modem + SmartLink Soft Modem: version 2.9.11 Oct 28 2021 16:51:30 + symbolic link `/dev/ttySL0' -> `/dev/pts/3' created. + modem `slamr0' created. TTY is `/dev/pts/3' + Use `/dev/ttySL0' as modem device, Ctrl+C for termination. + +In another terminal, connect to the newly created serial device at 115200 bps: + + # screen /dev/ttySL0 115200 + +You can now interact with this terminal (almost) as you would with a normal modem using standard AT commands. A similar modem’s manual provides a more complete list. + +Because there isn’t any dial tone on our SIP connection, you’ll need to disable dial tone detection: + + atx3 + OK + +To successfully connect, you will likely need to manually select a modulation and data rate. In our testing, V.32bis (14.4kbps) and below appears to be the most reliable, though V.34 (33.6kbps) connections are sometimes successful. For example, the following command selects V.32bis with a data rate of 4800 – 9600 bps. Refer to the manual for further details. + + at+ms=132,0,4800,9600 + OK + +Finally, dial the number of the target system. Below shows a connection to the NIST atomic clock: + + atd303-494-4774 + CONNECT 9600 + National Institute of Standards and Technology + Telephone Time Service, Generator 1b + Enter the question mark character for HELP + D L + MJD YR MO DA HH MM SS ST S UT1 msADV + 59515 21-10-28 21:40:18 11 0 -.1 045.0 UTC(NIST) * + 59515 21-10-28 21:40:19 11 0 -.1 045.0 UTC(NIST) * + 59515 21-10-28 21:40:20 11 0 -.1 045.0 UTC(NIST) * + 59515 21-10-28 21:40:21 11 0 -.1 045.0 UTC(NIST) * + 59515 21-10-28 21:40:22 11 0 -.1 045.0 UTC(NIST) * + 59515 21-10-28 21:40:23 11 0 -.1 045.0 UTC(NIST) * + +## Known Issues / Future Work +- Connections are unreliable, and it is currently difficult to connect at speeds higher than 14.4kbps or so. It might be possible to improve this by disabling/reconfiguring PJSIP’s jitter buffer. +- Additional logging/error handling is needed +- The serial interface could be replaced with stdio or a socket, and common AT configuration options could be exposed as command line options +- There is currently no support for receiving calls + + +Copyright 2021 Aon plc diff --git a/d-modem.c b/d-modem.c new file mode 100644 index 0000000..5a352b4 --- /dev/null +++ b/d-modem.c @@ -0,0 +1,262 @@ +/* + * Copyright (C) 2021 Aon plc + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include +#include +#include +#include +#include +#include + +#include + +#define SIGNATURE PJMEDIA_SIG_CLASS_PORT_AUD('D','M') + +struct dmodem { + pjmedia_port base; + pj_timestamp timestamp; + pj_sock_t sock; +}; + +static struct dmodem port; +static bool destroying = false; +static pj_pool_t *pool; + +static void error_exit(const char *title, pj_status_t status) { + pjsua_perror(__FILE__, title, status); + if (!destroying) { + destroying = true; + pjsua_destroy(); + exit(1); + } +} + +static pj_status_t dmodem_put_frame(pjmedia_port *this_port, pjmedia_frame *frame) { + struct dmodem *sm = (struct dmodem *)this_port; + int len; + + if (frame->type == PJMEDIA_FRAME_TYPE_AUDIO) { + if ((len=write(sm->sock, frame->buf, frame->size)) != frame->size) { + error_exit("error writing frame",0); + } + } + + return PJ_SUCCESS; +} + +static pj_status_t dmodem_get_frame(pjmedia_port *this_port, pjmedia_frame *frame) { + struct dmodem *sm = (struct dmodem *)this_port; + frame->size = PJMEDIA_PIA_AVG_FSZ(&this_port->info); // MAX? what is + + int len; + if ((len=read(sm->sock, frame->buf, frame->size)) != frame->size) { + error_exit("error reading frame",0); + } + + frame->timestamp.u64 = sm->timestamp.u64; + frame->type = PJMEDIA_FRAME_TYPE_AUDIO; + sm->timestamp.u64 += PJMEDIA_PIA_SPF(&this_port->info); + + return PJ_SUCCESS; +} + +static pj_status_t dmodem_on_destroy(pjmedia_port *this_port) { + printf("destroy\n"); + exit(-1); +} + +/* Callback called by the library when call's state has changed */ +static void on_call_state(pjsua_call_id call_id, pjsip_event *e) { + pjsua_call_info ci; + + PJ_UNUSED_ARG(e); + + pjsua_call_get_info(call_id, &ci); + PJ_LOG(3,(__FILE__, "Call %d state=%.*s", call_id, + (int)ci.state_text.slen, + ci.state_text.ptr)); + + if (ci.state == PJSIP_INV_STATE_DISCONNECTED) { + close(port.sock); + if (!destroying) { + destroying = true; + pjsua_destroy(); + exit(0); + } + } +} + +/* Callback called by the library when call's media state has changed */ +static void on_call_media_state(pjsua_call_id call_id) { + pjsua_call_info ci; + pjsua_conf_port_id port_id; + static int done=0; + + pjsua_call_get_info(call_id, &ci); + +// printf("media_status %d media_cnt %d ci.conf_slot %d aud.conf_slot %d\n",ci.media_status,ci.media_cnt,ci.conf_slot,ci.media[0].stream.aud.conf_slot); + if (ci.media_status == PJSUA_CALL_MEDIA_ACTIVE) { + if (!done) { + pjsua_conf_add_port(pool, &port.base, &port_id); + pjsua_conf_connect(ci.conf_slot, port_id); + pjsua_conf_connect(port_id, ci.conf_slot); + done = 1; + } + } else { + done = 0; + } +} + + +int main(int argc, char *argv[]) { + pjsua_acc_id acc_id; + pj_status_t status; + + if (argc != 3) { + return -1; + } + + signal(SIGPIPE,SIG_IGN); + + char *dialstr = argv[1]; + + char *sip_user = getenv("SIP_LOGIN"); + if (!sip_user) { + return -1; + } + char *sip_domain = strchr(sip_user,'@'); + if (!sip_domain) { + return -1; + } + *sip_domain++ = '\0'; + char *sip_pass = strchr(sip_user,':'); + if (!sip_pass) { + return -1; + } + *sip_pass++ = '\0'; + + status = pjsua_create(); + if (status != PJ_SUCCESS) error_exit("Error in pjsua_create()", status); + + /* Init pjsua */ + { + pjsua_config cfg; + pjsua_logging_config log_cfg; + pjsua_media_config med_cfg; + + pjsua_config_default(&cfg); + cfg.cb.on_call_media_state = &on_call_media_state; + cfg.cb.on_call_state = &on_call_state; + + pjsua_logging_config_default(&log_cfg); + log_cfg.console_level = 4; + + pjsua_media_config_default(&med_cfg); + med_cfg.no_vad = true; + med_cfg.ec_tail_len = 0; + med_cfg.jb_max = 2000; +// med_cfg.jb_init = 200; + med_cfg.audio_frame_ptime = 5; + + status = pjsua_init(&cfg, &log_cfg, &med_cfg); + if (status != PJ_SUCCESS) error_exit("Error in pjsua_init()", status); + } + + pjsua_set_ec(0,0); // maybe? + pjsua_set_null_snd_dev(); + + /* g711 only */ + pjsua_codec_info codecs[32]; + unsigned count = sizeof(codecs)/sizeof(*codecs); + pjsua_enum_codecs(codecs,&count); + for (int i=0; i> .depend ;) + +-include .depend + +# build_profile +-include .build_profile + +.build_profile:: +ifneq ($(CFLAGS),$(PROFILE_CFLAGS)) + @if [ "$(CFLAGS) $(EXTRA_CFLAGS)" != "$(PROFILE_CFLAGS)" ] ; then \ + echo "rebuild profile..." ; \ + echo "PROFILE_CFLAGS=$(CFLAGS) $(EXTRA_CFLAGS)" > $(@) ; fi +endif + +clean: clean-build-profile +clean-build-profile: + @$(RM) -f .build_profile + diff --git a/slmodemd/Makefile.20080401 b/slmodemd/Makefile.20080401 new file mode 100644 index 0000000..0787ce4 --- /dev/null +++ b/slmodemd/Makefile.20080401 @@ -0,0 +1,92 @@ +########################################################################### +# +# +# Makefile -- modem application Makefile. +# +# Copyright(c) 2003, Smart Link Ltd. (www.smlink.com) +# All rights reserved. +# +# Author: Sasha K (sashak@smlink.com) +# +# +########################################################################### +# +########################################################################### + +ARCH64:=$(shell uname -m | sed -e '/amd64/s//x86_64/' | grep -c x86_64) + +ifeq ($(ARCH64), 0) +CC:= gcc +else +# SUPPORT_ALSA:=1 +CC:= gcc -m32 +endif + +RM:= rm -f + +CFLAGS+= -Wall -g -O -I. -DCONFIG_DEBUG_MODEM + +modem-objs:= \ + modem.o modem_datafile.o modem_at.o modem_timer.o \ + modem_pack.o modem_ec.o modem_comp.o \ + modem_param.o modem_debug.o homolog_data.o +dp-objs:= dp_sinus.o dp_dummy.o +sysdep-objs:= sysdep_common.o +all-objs:= modem_cmdline.o $(modem-objs) $(dp-objs) dsplibs.o $(sysdep-objs) + +all: slmodemd modem_test + +slmodemd: modem_main.o $(all-objs) +modem_test: modem_test.o $(all-objs) + +ifdef SUPPORT_ALSA +CFLAGS+= -DSUPPORT_ALSA=1 +ifeq ($(ARCH64), 0) +LFLAGS+= /usr/lib/libasound.so +else +# LFLAGS+= /usr/lib32/libasound.so , replaced by -l commands search for asound +LFLAGS+= -lasound +endif +endif + +slmodemd: + $(CC) -o slmodemd modem_main.o $(all-objs) $(LFLAGS) + +modem_test: + $(CC) -o modem_test modem_test.o $(all-objs) $(LFLAGS) + +clean: + $(RM) slmodemd modem_test modem_main.o modem_cmdline.o modem_test.o $(modem-objs) $(dp-objs) $(sysdep-objs) + $(RM) *~ *.orig *.rej + +.PHONY: all dep generic-dep clean clean-build-profile + + +# +# rules +# + +%.o: %.c .build_profile + $(CC) $(CFLAGS) $(EXTRA_CFLAGS) $(CFLAGS_$@) -o $@ -c $< + +dep: generic-dep +generic-dep: + $(RM) .depend + $(foreach src,$(wildcard *.c),$(CC) -M $(CFLAGS) $(EXTRA_CFLAGS) $(CFLAGS_$(src:.c=.o)) -c $(src) >> .depend ;) + +-include .depend + +# build_profile +-include .build_profile + +.build_profile:: +ifneq ($(CFLAGS),$(PROFILE_CFLAGS)) + @if [ "$(CFLAGS) $(EXTRA_CFLAGS)" != "$(PROFILE_CFLAGS)" ] ; then \ + echo "rebuild profile..." ; \ + echo "PROFILE_CFLAGS=$(CFLAGS) $(EXTRA_CFLAGS)" > $(@) ; fi +endif + +clean: clean-build-profile +clean-build-profile: + @$(RM) -f .build_profile + diff --git a/slmodemd/dp_dummy.c b/slmodemd/dp_dummy.c new file mode 100644 index 0000000..8d9cafe --- /dev/null +++ b/slmodemd/dp_dummy.c @@ -0,0 +1,153 @@ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * dp_dummy.c -- dummy data pump (very stupid simulator). + * + * Author: Sasha K (sashak@smlink.com) + * + * + */ + +#include +#include + + +#define DUMMY_SKIP 100 +#define DUMMY_TIMEOUT 300 + +#define DUMMY_A1 0xff + + +struct dummy_dp { + struct dp dp; + unsigned long count; + unsigned long linked; + u8 buf[1024]; + void *dcr; +}; + +static struct dp *dummy_create(struct modem *m, enum DP_ID id, + int caller, int srate, int max_frag, + struct dp_operations *op) +{ + struct dummy_dp *d; + dprintf("dummy_create...\n"); + d = malloc(sizeof(*d)); + memset(d,0,sizeof(*d)); + d->dp.id = id; + d->dp.modem = m; + d->dp.op = op; + d->dp.dp_data = d; + d->dcr = m->dcr; + m->dcr = NULL; + return (struct dp *)d; +} + +static int dummy_delete(struct dp *dp) +{ + struct dummy_dp *d = (struct dummy_dp *)dp; + dprintf("dummy_delete...\n"); + dp->modem->dcr = d->dcr; + free(d); + return 0; +} + +static int dummy_process(struct dp *dp, void *in, void *out, int cnt) +{ + struct dummy_dp *d = (struct dummy_dp *)dp; + int n = cnt << MFMT_SHIFT(dp->modem->format); + s16 *s; + int i; + d->count++; + if (!d->linked) { + if (d->count < DUMMY_SKIP) { + memset(out,0,n); + return DPSTAT_OK; + } + else if(d->count > DUMMY_TIMEOUT) + return DPSTAT_ERROR; + s = out; + for(i = 0 ; i < cnt ; i++) { + *s = (1-2*(i&1))*('A'); + s++; + } + s = in; + for(i = 0 ; i < cnt ; i++) { + if(abs(*s) == 'A') { + d->linked = 1; + return DPSTAT_CONNECT; + } + s++; + } + } + else { + s = in; + for(i = 0 ; i < cnt ; i++) { + d->buf[i] = *s&0x1; + s++; + } + modem_put_bits(dp->modem,1,d->buf,cnt); + s = out; + modem_get_bits(dp->modem,1,d->buf,cnt); + for(i = 0 ; i < cnt ; i++) { + *s = d->buf[i]&1 ; + s++; + } + } + return DPSTAT_OK; +} + + +static struct dp_operations dummy_operations = { + name : "Dummy DataPump driver", + create: dummy_create, + delete: dummy_delete, + process:dummy_process +}; + + + +int dp_dummy_init(void) +{ + return modem_dp_register(DP_DUMMY,&dummy_operations); +} + +void dp_dummy_exit(void) +{ + modem_dp_deregister(DP_DUMMY,&dummy_operations); +} + + diff --git a/slmodemd/dp_sinus.c b/slmodemd/dp_sinus.c new file mode 100644 index 0000000..00081a1 --- /dev/null +++ b/slmodemd/dp_sinus.c @@ -0,0 +1,133 @@ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * sinus.c -- sinus data pump. + * + * Author: Sasha K (sashak@smlink.com) + * + * + */ + +#include +#include + +#ifdef __KERNEL__ +#define malloc(size) kmalloc(size,GFP_KERNEL) +#define free(mem) kfree(mem) +#endif + +#define SIN_AMPLITUDE 16384 +#define SIN_PERIOD (sizeof(sintab)/sizeof(sintab[0])) +static +const s16 sintab[] = { + 0, 3196, 6269, 9102, 11585, 13622, 15136, 16069, + 16384, 16069, 15136, 13622, 11585, 9102, 6269, 3196, + 0, -3196, -6269, -9102, -11585, -13622, -15136, -16069, + -16384, -16069, -15136, -13622, -11585, -9102, -6269, -3196}; + +#define SIN_DBG(fmt,arg...) dprintf("sin: " fmt , ##arg) + +struct sin_state { + struct dp dp; + int count; + int linked; + u8 buf[1024]; + int amp; + unsigned period; + unsigned phase; +}; + +static struct dp *sin_create(struct modem *m, enum DP_ID id, + int caller, int srate, int max_frag, + struct dp_operations *op) +{ + struct sin_state *s; + SIN_DBG("create...\n"); + s = malloc(sizeof(*s)); + if (!s) return NULL; + memset(s,0,sizeof(*s)); + s->dp.id = id; + s->dp.modem = m; + s->dp.op = op; + s->dp.dp_data = s; + s->phase = 0; + s->amp = SIN_AMPLITUDE; + s->period= SIN_PERIOD; + return &s->dp; +} + +static int sin_delete(struct dp *dp) +{ + struct sin_state *s = dp->dp_data; + SIN_DBG("delete...\n"); + free(s); + return 0; +} + +static int sin_run(struct dp *dp, void *in, void *out, int cnt) +{ + struct sin_state *s = dp->dp_data; + s16 *smpl = out; + int i; + //SIN_DBG("run...\n"); + for (i=0;iphase%SIN_PERIOD]; + s->phase = s->phase+1; + } + return DPSTAT_OK; +} + + +static struct dp_operations sin_operations = { + name : "Sinus DP driver", + create: sin_create, + delete: sin_delete, + process:sin_run +}; + + + +int dp_sinus_init(void) +{ + return modem_dp_register(DP_SINUS,&sin_operations); +} + +void dp_sinus_exit(void) +{ + modem_dp_deregister(DP_SINUS,&sin_operations); +} + + diff --git a/slmodemd/dsplibs.o b/slmodemd/dsplibs.o new file mode 100644 index 0000000..e64b4a7 Binary files /dev/null and b/slmodemd/dsplibs.o differ diff --git a/slmodemd/homolog_data.c b/slmodemd/homolog_data.c new file mode 100644 index 0000000..1e1872d --- /dev/null +++ b/slmodemd/homolog_data.c @@ -0,0 +1,131 @@ +/* generated at Jun 1 2004 19:11:22 */ + +#include +#include + +static const struct homolog_params params000 = {0x22,0x43,0x01,0x08,0x5a,0x28,0x3f,0x02,0x25,0x3f,0x00,0x1b,0x02,0x09,0x01,0x10,0x02,0x01,0x2b,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params001 = {0x24,0x40,0x01,0x06,0x64,0x12,0x3c,0x04,0x12,0x3c,0x00,0x32,0x02,0x0a,0x00,0x19,0x02,0x05,0x2b,0x00,0xff,0x06,0x50,0x02,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params002 = {0x21,0x43,0x01,0x08,0x5a,0x23,0x27,0x04,0x23,0x27,0x00,0x09,0x02,0x09,0x00,0x19,0x02,0x01,0x2b,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params003 = {0x28,0x3c,0x01,0x08,0x5a,0x00,0x00,0x02,0x00,0x00,0x00,0x09,0x04,0x09,0x01,0x08,0x02,0x06,0x2d,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params005 = {0x21,0x43,0x01,0x08,0x5a,0x00,0x00,0x04,0x00,0x00,0x00,0x0c,0x04,0x09,0x01,0x07,0x02,0x04,0x2b,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params006 = {0x24,0x40,0x01,0x06,0x64,0x12,0x50,0x04,0x12,0x50,0x00,0x32,0x02,0x0a,0x00,0x19,0x02,0x05,0x2b,0x00,0xff,0x00,0x50,0x02,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params007 = {0x21,0x43,0x01,0x06,0x69,0x2a,0x50,0x04,0x2a,0x50,0x00,0x3c,0x02,0x0a,0x00,0x19,0x02,0x01,0x2b,0x00,0x1e,0x00,0x50,0x03,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params008 = {0x28,0x3c,0x01,0x08,0x5a,0x00,0x00,0x04,0x00,0x00,0x00,0x07,0x04,0x09,0x00,0x02,0x02,0x03,0x2d,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params011 = {0x24,0x40,0x01,0x06,0x64,0x00,0x00,0x04,0x00,0x00,0x00,0x32,0x02,0x0a,0x00,0x19,0x02,0x01,0x2b,0x00,0x1e,0x00,0x50,0x02,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params012 = {0x21,0x43,0x01,0x08,0x5a,0x00,0x00,0x04,0x00,0x00,0x00,0x07,0x04,0x09,0x00,0x02,0x02,0x03,0x2d,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params013 = {0x21,0x43,0x01,0x08,0x5a,0x2a,0x50,0x04,0x2a,0x50,0x00,0x07,0x04,0x09,0x00,0x02,0x02,0x03,0x2d,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params014 = {0x28,0x3c,0x01,0x06,0x5a,0x06,0x2a,0x08,0x0d,0x3c,0x01,0x0a,0x04,0x09,0x01,0x0e,0x02,0x00,0x22,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params015 = {0x24,0x40,0x01,0x08,0x5a,0x00,0x00,0x04,0x00,0x00,0x00,0x09,0x02,0x09,0x01,0x19,0x02,0x00,0x26,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params016 = {0x21,0x43,0x01,0x09,0x5a,0x00,0x00,0x04,0x00,0x00,0x00,0x07,0x04,0x09,0x00,0x02,0x02,0x03,0x2d,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params018 = {0x28,0x3c,0x01,0x08,0x5a,0x0a,0x42,0x04,0x0a,0x41,0x00,0x09,0x04,0x09,0x01,0x19,0x02,0x01,0x2b,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params020 = {0x29,0x3c,0x01,0x08,0x5a,0x0f,0x3c,0x04,0x23,0x3c,0x00,0x12,0x04,0x09,0x01,0x19,0x02,0x05,0x2b,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params022 = {0x24,0x40,0x01,0x06,0x64,0x00,0x00,0x04,0x00,0x00,0x00,0x32,0x02,0x0a,0x00,0x19,0x02,0x01,0x2b,0x00,0x1e,0x06,0x50,0x02,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params023 = {0x21,0x43,0x01,0x06,0x5a,0x0b,0x3c,0x02,0x0b,0x3c,0x00,0x09,0x04,0x09,0x01,0x08,0x02,0x06,0x2d,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params025 = {0x24,0x40,0x01,0x06,0x64,0x41,0x55,0x04,0x41,0x55,0x00,0x32,0x02,0x0a,0x00,0x19,0x02,0x01,0x2b,0x00,0x2e,0x00,0x50,0x02,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params027 = {0x22,0x43,0x01,0x08,0x5a,0x00,0x00,0x04,0x00,0x00,0x00,0x07,0x04,0x09,0x00,0x19,0x02,0x02,0x2b,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params028 = {0x24,0x40,0x01,0x06,0x64,0x12,0x3c,0x04,0x12,0x3c,0x00,0x32,0x02,0x0a,0x00,0x19,0x02,0x05,0x2b,0x00,0xff,0x00,0x50,0x02,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params029 = {0x29,0x41,0x01,0x08,0x5a,0x00,0x00,0x02,0x00,0x00,0x00,0x0b,0x02,0x09,0x01,0x0f,0x02,0x04,0x28,0x00,0x1e,0x00,0x50,0x06,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params030 = {0x22,0x42,0x01,0x08,0x64,0x00,0x00,0x04,0x00,0x00,0x00,0x32,0x02,0x0e,0x00,0x19,0x02,0x01,0x2b,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params032 = {0x22,0x42,0x01,0x06,0x64,0x00,0x00,0x04,0x00,0x00,0x00,0x32,0x02,0x08,0x00,0x19,0x02,0x01,0x2b,0x00,0x1e,0x06,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params033 = {0x24,0x40,0x01,0x06,0x64,0x00,0x00,0x04,0x00,0x00,0x00,0x32,0x02,0x0a,0x00,0x19,0x02,0x00,0x2b,0x00,0xff,0x00,0x50,0x02,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params035 = {0x21,0x43,0x01,0x08,0x5a,0x21,0x30,0x04,0x0e,0x19,0x00,0x07,0x04,0x09,0x00,0x02,0x02,0x03,0x2d,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params036 = {0x28,0x3c,0x01,0x06,0x5a,0x00,0x00,0x04,0x00,0x00,0x00,0x12,0x04,0x09,0x01,0x19,0x02,0x05,0x2b,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params038 = {0x21,0x43,0x01,0x06,0x64,0x00,0x00,0x04,0x00,0x00,0x00,0x32,0x02,0x0a,0x00,0x19,0x02,0x01,0x2b,0x00,0x1e,0x00,0x50,0x03,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params039 = {0x21,0x43,0x01,0x08,0x5a,0x21,0x3c,0x04,0x21,0x3c,0x00,0x07,0x04,0x09,0x00,0x02,0x02,0x03,0x2d,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params040 = {0x24,0x40,0x01,0x06,0x64,0x00,0x00,0x04,0x00,0x00,0x00,0x32,0x02,0x0a,0x00,0x19,0x02,0x01,0x2b,0x00,0x2e,0x00,0x50,0x02,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params041 = {0x21,0x43,0x01,0x06,0x5a,0x00,0x00,0x04,0x00,0x00,0x00,0x07,0x04,0x09,0x00,0x02,0x02,0x03,0x2d,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params042 = {0x28,0x3c,0x01,0x08,0x5a,0x00,0x00,0x04,0x00,0x00,0x00,0x0b,0x02,0x09,0x01,0x0f,0x02,0x07,0x20,0x00,0x1e,0x00,0x50,0x05,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params043 = {0x21,0x43,0x03,0x07,0x5a,0x00,0x00,0x04,0x00,0x00,0x00,0x46,0x04,0x09,0x00,0x19,0x01,0x01,0x2b,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params044 = {0x24,0x40,0x01,0x08,0x5a,0x0a,0x42,0x02,0x0a,0x41,0x00,0x0a,0x04,0x09,0x01,0x0f,0x02,0x00,0x27,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params045 = {0x21,0x43,0x01,0x08,0x69,0x00,0x00,0x04,0x00,0x00,0x00,0x09,0x02,0x0a,0x00,0x19,0x02,0x01,0x2b,0x00,0x1e,0x00,0x50,0x03,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params049 = {0x21,0x43,0x01,0x06,0x5a,0x0b,0x3c,0x02,0x0b,0x3c,0x00,0x09,0x04,0x09,0x01,0x08,0x02,0x05,0x2d,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params050 = {0x21,0x43,0x01,0x08,0x5a,0x00,0x00,0x04,0x00,0x00,0x00,0x14,0x02,0x09,0x01,0x19,0x02,0x03,0x23,0x01,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params051 = {0x28,0x3c,0x01,0x07,0x5a,0x0c,0x16,0x04,0x0c,0x16,0x00,0x12,0x04,0x09,0x01,0x19,0x02,0x05,0x2b,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params052 = {0x26,0x3e,0x01,0x04,0x69,0x22,0x2e,0x04,0x22,0x2e,0x00,0x09,0x02,0x0a,0x00,0x19,0x03,0x01,0x2b,0x00,0x1e,0x00,0x32,0x03,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params054 = {0x21,0x43,0x01,0x07,0x69,0x48,0x4e,0x04,0x48,0x4e,0x00,0x09,0x02,0x0a,0x00,0x19,0x02,0x01,0x2b,0x00,0x1e,0x00,0x50,0x03,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params055 = {0x28,0x3c,0x01,0x07,0x5a,0x00,0x00,0x04,0x00,0x00,0x00,0x0a,0x04,0x09,0x01,0x19,0x02,0x05,0x2b,0x00,0x1e,0x00,0x55,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params056 = {0x28,0x3c,0x01,0x07,0x5a,0x00,0x00,0x04,0x00,0x00,0x00,0x12,0x04,0x09,0x01,0x19,0x02,0x05,0x2b,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params057 = {0x28,0x3c,0x01,0x09,0x5a,0x2a,0x50,0x04,0x2a,0x50,0x00,0x07,0x04,0x09,0x00,0x02,0x02,0x03,0x2d,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params059 = {0x21,0x43,0x01,0x08,0x5a,0x05,0x3c,0x04,0x05,0x3c,0x00,0x0a,0x05,0x09,0x01,0x0c,0x02,0x05,0x29,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params061 = {0x28,0x3c,0x02,0x08,0x5a,0x14,0x1e,0x04,0x14,0x55,0x00,0x09,0x04,0x09,0x01,0x0f,0x02,0x00,0x1f,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params062 = {0x28,0x3c,0x01,0x08,0x5a,0x08,0x50,0x02,0x08,0x50,0x00,0x0c,0x04,0x09,0x01,0x0f,0x02,0x00,0x25,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x01,}; +static const struct homolog_params params063 = {0x21,0x43,0x01,0x06,0x64,0x14,0x3c,0x04,0x14,0x3c,0x00,0x32,0x02,0x0a,0x00,0x0a,0x02,0x01,0x2b,0x00,0x1e,0x06,0x50,0x03,0x00,0x00,0x00,0x012c,0x00,}; +static const struct homolog_params params064 = {0x28,0x3c,0x01,0x06,0x64,0x00,0x00,0x04,0x00,0x00,0x00,0x09,0x02,0x0a,0x00,0x19,0x02,0x01,0x23,0x00,0x1e,0x00,0x50,0x02,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params067 = {0x21,0x43,0x01,0x07,0x5a,0x00,0x00,0x04,0x00,0x00,0x00,0x07,0x04,0x09,0x00,0x02,0x02,0x03,0x2d,0x00,0x1e,0x00,0x15,0x04,0x00,0x00,0x00,0x029a,0x00,}; +static const struct homolog_params params068 = {0x22,0x48,0x01,0x08,0x5a,0x23,0x27,0x04,0x23,0x27,0x00,0x07,0x04,0x09,0x00,0x19,0x02,0x01,0x2b,0x00,0x1e,0x00,0x50,0x04,0x00,0x00,0x00,0x029a,0x00,}; + +const struct homolog_set homolog_set[] = { + {0x0002,"ALGERIA",¶ms000}, + {0x0007,"ARGENTINA",¶ms001}, + {0x0009,"AUSTRALIA",¶ms002}, + {0x000a,"AUSTRIA",¶ms003}, + {0x000c,"BAHREIN",¶ms001}, + {0x000f,"BELGIUM",¶ms005}, + {0x0016,"BRAZIL",¶ms006}, + {0x001a,"BRUNEI",¶ms007}, + {0x001b,"BULGARIA",¶ms008}, + {0x0020,"CANADA",¶ms001}, + {0x0025,"CHILE",¶ms001}, + {0x0026,"CHINA",¶ms011}, + {0x0100,"CTR21EUROPE",¶ms012}, + {0x002d,"CYPRUS",¶ms013}, + {0x002e,"CZECH_REPUBLIC",¶ms014}, + {0x0031,"DENMARK",¶ms015}, + {0x0036,"EGYPT",¶ms016}, + {0x0101,"ESTONIA",¶ms012}, + {0x003c,"FINLAND",¶ms018}, + {0x003d,"FRANCE",¶ms000}, + {0x0042,"GERMANY",¶ms020}, + {0x0046,"GREECE",¶ms012}, + {0x0050,"HONG_KONG",¶ms022}, + {0x0051,"HUNGARY",¶ms023}, + {0x0052,"ICELAND",¶ms012}, + {0x0053,"INDIA",¶ms025}, + {0x0054,"INDONESIA",¶ms011}, + {0x0057,"IRELAND",¶ms027}, + {0x0058,"ISRAEL",¶ms028}, + {0x0059,"ITALY",¶ms029}, + {0x0000,"JAPAN",¶ms030}, + {0x005e,"JORDAN",¶ms013}, + {0x0061,"KOREA",¶ms032}, + {0x0062,"KUWAIT",¶ms033}, + {0x0103,"LATVIA",¶ms008}, + {0x0064,"LEBANON",¶ms035}, + {0x0104,"LITHUANIA",¶ms036}, + {0x0069,"LUXEMBOURG",¶ms012}, + {0x006c,"MALAYSIA",¶ms038}, + {0x0070,"MALTA",¶ms039}, + {0x0073,"MEXICO",¶ms040}, + {0x0077,"MOROCCO",¶ms041}, + {0x007b,"NETHERLANDS",¶ms042}, + {0x007e,"NEW_ZEALAND",¶ms043}, + {0x0082,"NORWAY",¶ms044}, + {0x0083,"OMAN",¶ms045}, + {0x0084,"PAKISTAN",¶ms040}, + {0x0088,"PERU",¶ms001}, + {0x0089,"PHILIPPINES",¶ms040}, + {0x008a,"POLAND",¶ms049}, + {0x008b,"PORTUGAL",¶ms050}, + {0x008e,"ROMANIA",¶ms051}, + {0x00b8,"RUSSIA",¶ms052}, + {0x0098,"SAUDIARABIA",¶ms001}, + {0x009c,"SINGAPORE",¶ms054}, + {0x00c5,"SLOVAKIA",¶ms055}, + {0x00c6,"SLOVENIA",¶ms056}, + {0x009f,"SOUTHAFRICA",¶ms057}, + {0x0107,"SOUTHKOREA",¶ms001}, + {0x00a0,"SPAIN",¶ms059}, + {0x00a1,"SRILANKA",¶ms054}, + {0x00a5,"SWEDEN",¶ms061}, + {0x00a6,"SWITZERLAND",¶ms062}, + {0x0108,"TAIWAN",¶ms063}, + {0x00a9,"THAILAND",¶ms064}, + {0x00ad,"TUNISIA",¶ms000}, + {0x00ae,"TURKEY",¶ms012}, + {0x00b3,"UAE",¶ms067}, + {0x00b4,"UK",¶ms068}, + {0x00b7,"URUGUAY",¶ms001}, + {0x00b5,"USA",¶ms001}, + {0x00bc,"VIETNAM",¶ms040}, + {}}; + diff --git a/slmodemd/modem.c b/slmodemd/modem.c new file mode 100644 index 0000000..3a4c711 --- /dev/null +++ b/slmodemd/modem.c @@ -0,0 +1,1973 @@ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * Copyright (c) 2021, Aon plc + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem.c -- modem core module. + * + * Author: Sasha K (sashak@smlink.com) + * + * + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + + +#define XMIT_SIZE 4096 + +#define MODEM_AUTHOR "Smart Link Ltd." +#define MODEM_NAME "SmartLink Soft Modem" +#define MODEM_VERSION "2.9.11" +#define MODEM_DATE __DATE__" "__TIME__ + +/* event mask */ +#define MDMEVENT_RING_CHECK 0x01 +#define MDMEVENT_ESCAPE 0x02 + +/* debug prints */ +#define MODEM_INFO(fmt,arg...) printf(fmt , ##arg) ; dprintf(fmt , ##arg) +#define MODEM_DBG(fmt,arg...) dprintf("%s: " fmt , m->name , ##arg) +#define MODEM_ERR(fmt,arg...) eprintf("%s: " fmt , m->name , ##arg) + +/* external symbols */ +extern int process_at_command(struct modem *m, char *buf); +extern void *dp_runtime_create(struct modem *m); +extern void dp_runtime_delete(void *runtime); +extern void *dcr_create(); +extern void dcr_delete(void *dcr); +extern void dcr_process(void *dcr, void *buf, int len); +#ifdef MODEM_CONFIG_RING_DETECTOR +extern void *RD_create(struct modem *m, unsigned rate); +extern void RD_delete(void *obj); +extern int RD_process(void *obj, void *in, int count); +extern void RD_ring_details(void *obj, long *freq, long *duration); +#endif +#ifdef MODEM_CONFIG_CID +extern void *CID_create(struct modem *m, unsigned rate, unsigned cid_val); +extern void CID_delete(void *cid); +extern int CID_process(void *cid, void *in, int count); +#endif +#ifdef MODEM_CONFIG_VOICE +extern void *VOICE_create(struct modem *m, unsigned srate); +extern void VOICE_delete(void *obj); +extern int VOICE_process(void *obj, void *in, void *out, int count); +extern int VOICE_command(void *obj, enum VOICE_CMD cmd); +#endif +#ifdef MODEM_CONFIG_FAX +extern void *FAX_create(struct modem *m, unsigned caller, unsigned srate); +extern int FAX_process(void *obj, void *in, void *out, int count); +extern void FAX_delete(void *obj); +#endif + +/* local prototypes */ +int modem_answer(struct modem *m); +static int sregs_init(unsigned char sregs[]); +static void do_modem_change_dp(struct modem *); +static int modem_start(struct modem *); +static int modem_stop (struct modem *); +static struct dp_operations *get_dp_operations(enum DP_ID id); +static int modem_get_chars(struct modem *m, char *buf, int n); +static int modem_put_chars(struct modem *m, const char *buf, int n); +static int modem_comp_get_chars(struct modem *m, char *buf, int n); +static int modem_comp_put_chars(struct modem *m, const char *buf, int n); +#ifdef MODEM_CONFIG_CID +static int modem_cid_start(struct modem *, unsigned timeout); +#endif +#ifdef MODEM_CONFIG_FAX +static int modem_fax_start(struct modem *m); +#endif + +/* global config data */ +const char *modem_default_country = NULL; + + +/* data definitions */ +const char modem_author[] = MODEM_AUTHOR; +const char modem_name[] = MODEM_NAME; +const char modem_version[]= MODEM_VERSION; +const char modem_date[] = MODEM_DATE; + + +/* + * misc macros + */ + +/* ring parameter */ +#define RING_ON_MIN(m) MODEM_HZ*3/20 /* 0.15 sec */ +#define RING_ON_MAX(m) MODEM_HZ*5/2 /* 2.5 sec */ +#define RING_OFF_MIN(m) MODEM_HZ*3/2 /* 1.5 sec */ +#define RING_OFF_MAX(m) MODEM_HZ*13/2 /* 6.5 sec */ +#define RING_COUNT_MIN(m) 10 + +#define TOTAL_RINGS_COUNT(m) ((m)->sregs[SREG_RING_COUNTER]) +#define ANSWER_AFTER_RINGS(m) ((m)->sregs[SREG_RINGS_TO_AUTO_ANSWER]) + +#define ESCAPE_CHAR(m) ((m)->sregs[SREG_ESCAPE_CHAR]) +#define CR_CHAR(m) ((m)->sregs[SREG_CR_CHAR]) +#define LF_CHAR(m) ((m)->sregs[SREG_LF_CHAR]) +#define BS_CHAR(m) ((m)->sregs[SREG_BS_CHAR]) + +#define IS_ECHO(m) ((m)->sregs[SREG_ECHO]) +#define IS_QUIET(m) ((m)->sregs[SREG_QUIET]) +#define IS_VERBOSE(m) ((m)->sregs[SREG_VERBOSE]) +#define IS_AUTOMODE(m) MODEM_AUTOMODE(m) +#define MODEM_EC_ENABLE(m) ((m)->sregs[SREG_EC]) +#define MODEM_EC_DETECTOR(m) ((m)->sregs[SREG_EC]) +#define MODEM_COMP_ENABLE(m) ((m)->sregs[SREG_COMP]&&MODEM_EC_ENABLE(m)) +#define ESCAPE_TIMEOUT(m) (MODEM_HZ/2) +#define ANSWER_DELAY(m) ((m)->sregs[SREG_ANS_DELAY]) +#define SPEAKER_CONTROL(m) ((m)->sregs[SREG_SPEAKER_CONTROL]) +#define SPEAKER_VOLUME(m) ((m)->sregs[SREG_SPEAKER_VOLUME]) + +#define QC_SKIP_EC_DETECTION(m) ((m)->caller && (m)->dsp_info.qc_lapm) + + +/* + * dp operations drivers + * + */ + +struct dp_driver modem_dp_drivers[] = { + {DP_CALLPROG,"CallProg"}, + {DP_DUMMY,"Dummy"}, + {DP_AUTOMODE,"Automode"}, + {DP_V8,"V8"}, + {DP_V17,"V17"}, + {DP_V21,"V21","21"}, + {DP_V22,"V22","22"}, + {DP_V23,"V23","23"}, + {DP_V22BIS,"V22bis","122"}, + {DP_V32,"V32","32"}, + {DP_V32BIS,"V32bis","132"}, + {DP_V34,"V34","34"}, + {DP_B103,"Bell103","103"}, + {DP_B212,"Bell212","212"}, + {DP_FAX,"VFax"}, + {DP_K56,"K56Flex","56"}, + {DP_V8BIS,"V8bis"}, + {DP_V90,"V90","90"}, + {DP_V92,"V92","92"}, + {DP_SINUS,"Sinus"}, + {} +}; + +static struct dp_driver *get_dp_driver(enum DP_ID id) +{ + struct dp_driver *p; + for(p = modem_dp_drivers ; p->id > 0 ; p++) + if (p->id == id) return p; + return NULL; +} + +static struct dp_operations *get_dp_operations(enum DP_ID id) +{ + struct dp_driver *p; + for(p = modem_dp_drivers ; p->id > 0 ; p++) + if (p->id == id) return p->op; + return NULL; +} + +int modem_dp_register(enum DP_ID id, struct dp_operations *op) +{ + struct dp_driver *p; + int ret = -1; + for(p = modem_dp_drivers ; p->id > 0 ; p++) { + if (p->id == id && !p->op) { + p->op = op; + ret = 0; + break; + } + } + return ret; +} + +void modem_dp_deregister(enum DP_ID id, struct dp_operations *op) +{ + struct dp_driver *p; + for(p = modem_dp_drivers ; p->id > 0 ; p++) + if (p->id == id) p->op = NULL; +} + + + +/* + * state and status handling + * + */ + +enum MODEM_RESULT { + RESULT_OK = 0, + RESULT_CONNECT = 1, + RESULT_RING = 2, + RESULT_NOCARRIER = 3, + RESULT_ERROR = 4, + RESULT_UNUSED_5 = 5, + RESULT_NODIALTONE = 6, + RESULT_BUSY = 7, + RESULT_NOANSWER = 8, +}; + +static void modem_report_result(struct modem *m, enum MODEM_RESULT code) +{ +#define MODEM_RESPONSE_TEXT(id) modem_responses[id].text +#define MODEM_RESPONSE_CODE(id) modem_responses[id].code + /* response codes : FIXME */ + static const struct modem_response { + enum MODEM_RESULT id; + char *code; + char *text; + } modem_responses[] = { + {RESULT_OK, "0", "OK"}, + {RESULT_CONNECT, "1", "CONNECT"}, + {RESULT_RING, "2", "RING"}, + {RESULT_NOCARRIER, "3", "NO CARRIER"}, + {RESULT_ERROR, "4", "ERROR"}, + {RESULT_UNUSED_5, "" , ""}, + {RESULT_NODIALTONE, "6", "NO DIALTONE"}, + {RESULT_BUSY, "7", "BUSY"}, + {RESULT_NOANSWER, "8", "NO ANSWER"}, + }; + static const char none_str[] = "NONE"; + const char *msg; + u8 msg_mask; + + MODEM_DBG("modem report result: %d (%s)\n",code,MODEM_RESPONSE_TEXT(code)); + if (IS_QUIET(m)) + return; + if (IS_VERBOSE(m)) { + if(code==RESULT_CONNECT) { + msg_mask = modem_get_sreg(m,SREG_CONNNECT_MSG_FORMAT); + if(msg_mask&1) { + struct dp_driver *dp_drv; + modem_put_chars(m,"Modulation: ",12); + dp_drv = get_dp_driver(m->dp->id); + msg = (dp_drv) ? dp_drv->name : none_str; + modem_put_chars(m,msg,strlen(msg)); + modem_put_chars(m,CRLF_CHARS(m),2); + } + if(msg_mask&2) { + modem_put_chars(m,"Protocol: ",10); + msg = m->cfg.ec ? "LAPM" : none_str; + modem_put_chars(m,msg,strlen(msg)); + modem_put_chars(m,CRLF_CHARS(m),2); + } + if((msg_mask&3) == 3) { + modem_put_chars(m,"Compression: ",13); + msg = (m->cfg.ec && m->cfg.comp)? "V42bis" : none_str; + modem_put_chars(m,msg,strlen(msg)); + modem_put_chars(m,CRLF_CHARS(m),2); + } + if(msg_mask&4 && m->tx_rate) { + char rate_str[16]; + modem_put_chars(m,"TxRate: ",8); + sprintf(rate_str,"%d",m->tx_rate); + modem_put_chars(m,rate_str,strlen(rate_str)); + modem_put_chars(m,CRLF_CHARS(m),2); + } + } + msg = MODEM_RESPONSE_TEXT(code); + modem_put_chars(m,msg,strlen(msg)); + if (code==RESULT_CONNECT && m->mode == MODEM_MODE_DATA + && m->rx_rate && modem_get_sreg(m,SREG_X_CODE) != 0) { + char rate_str[16]; + sprintf(rate_str," %d",m->rx_rate); + modem_put_chars(m,rate_str,strlen(rate_str)); + } + } + else { + msg = MODEM_RESPONSE_CODE(code); + modem_put_chars(m,msg,strlen(msg)); + } + modem_put_chars(m,CRLF_CHARS(m),2); +} + + +/* TDB: state lifecycle description */ + +/* modem state constants */ +#define STATE_MODEM_IDLE 0x1 +#define STATE_DP_ESTAB 0x2 +#define STATE_EC_ESTAB 0x4 +#define STATE_MODEM_ONLINE 0x5 +#define STATE_COMMAND_ONLINE 0x6 +#define STATE_EC_DISC 0x7 +#define STATE_DP_DISC 0x9 + +#define STATE_DISC 0x100 + +#define STATE_ESTAB STATE_DP_ESTAB + +#define IS_STATE_LINKED(stat) ((stat) > STATE_DP_ESTAB) + +#define IS_STATE_IDLE(stat) ((stat) == STATE_MODEM_IDLE) +#define IS_STATE_CONNECTING(stat) ((stat) > STATE_MODEM_IDLE && (stat) < STATE_MODEM_ONLINE) +#define IS_STATE_ONLINE(stat) ((stat) == STATE_MODEM_ONLINE || (stat) == STATE_COMMAND_ONLINE) +#define IS_STATE_DISC(stat) ((stat) == STATE_EC_DISC || (stat) == STATE_DP_DISC) + + +static int modem_set_state(struct modem *m, unsigned new_state) +{ + MODEM_DBG("modem set state: %x --> %x...\n", + m->state, new_state); + if(m->state == new_state) + return 0; + switch(new_state) { + case STATE_MODEM_IDLE: + MODEM_DBG("new state: MODEM_IDLE\n"); + m->command = 1; + m->get_chars = 0; + m->put_chars = 0; + m->get_bits = 0; + m->put_bits = 0; + break; + case STATE_DP_ESTAB: + MODEM_DBG("new state: DP_ESTAB\n"); + m->command = 0; + m->get_chars = 0; + m->put_chars = 0; + m->get_bits = 0; + m->put_bits = 0; + break; + case STATE_EC_ESTAB: + MODEM_DBG("new state: EC_ESTAB\n"); + m->command = 0; + m->get_chars = 0; + m->put_chars = 0; + break; + case STATE_MODEM_ONLINE: + MODEM_DBG("new state: MODEM_ONLINE\n"); + m->command = 0; + m->put_chars = (m->cfg.ec && m->cfg.comp&0x1) + ? modem_comp_put_chars : modem_put_chars; + m->get_chars = (m->cfg.ec && m->cfg.comp&0x2) + ? modem_comp_get_chars : modem_get_chars; + m->modem_info |= TIOCM_CD; + break; + case STATE_COMMAND_ONLINE: + MODEM_DBG("new state: COMMAND_ONLINE\n"); + m->command = 1; + m->get_chars = 0; + m->put_chars = 0; + break; + case STATE_EC_DISC: + MODEM_DBG("new state: EC_DISC\n"); + m->get_chars = 0; + m->put_chars = 0; + break; + case STATE_DP_DISC: + MODEM_DBG("new state: DP_DISC\n"); + m->get_chars = 0; + m->put_chars = 0; + m->get_bits = 0; + m->put_bits = 0; + break; + default: + MODEM_ERR("invalid state: %d\n", new_state); + return -1; + } + m->state = new_state; + return 0; +} + + +static void run_modem_stop(struct modem *m) +{ + modem_stop(m); +} + +/* FIXME */ +#define schedule_modem_stop(m) { m->sample_timer_func = run_modem_stop; \ + m->sample_timer = m->count + 48; } + + +static void modem_hup(struct modem *m, unsigned local) +{ + MODEM_DBG("modem_hup...%d\n",m->state); + switch(m->state) { + case STATE_MODEM_IDLE: + return; + case STATE_DP_ESTAB: + if(local && m->dp && m->dp->op->hangup ) + m->dp->op->hangup(m->dp); + modem_set_state(m,STATE_DP_DISC); + if (m->result_code == 0) + m->result_code = RESULT_NOCARRIER; + schedule_modem_stop(m); + break; + case STATE_EC_ESTAB: + case STATE_MODEM_ONLINE: + case STATE_COMMAND_ONLINE: + if(local && m->cfg.ec) { + modem_ec_stop(m); + modem_set_state(m,STATE_EC_DISC); + } + else { + if(local && m->dp && m->dp->op->hangup) + m->dp->op->hangup(m->dp); + modem_set_state(m,STATE_DP_DISC); + } + if (m->result_code == 0) + m->result_code = RESULT_NOCARRIER; + schedule_modem_stop(m); +#if ALREADY_DONE + if(m->modem_info&TIOCM_CD && m->tty && + !m->termios->c_cflag&CLOCAL /* !C_CLOCAL(m->tty) */) { + MODEM_DBG("tty_hangup...\n"); + tty_hangup(m->tty); + } +#endif + m->modem_info &= ~TIOCM_CD; + break; + case STATE_EC_DISC: + if(local && m->dp && m->dp->op->hangup ) + m->dp->op->hangup(m->dp); + modem_set_state(m,STATE_DP_DISC); + break; + case STATE_DP_DISC: + default: + return; + } +} + + +/* FIXME: find better place */ +#define NONEC_DP(id) ((id) == DP_V23 || (id) == DP_B103 || (id) == DP_V21) + +void modem_update_status(struct modem *m, unsigned status) +{ + MODEM_DBG("modem_update_status: %d\n", status); + switch(status) { + case STATUS_OK: + break; + case STATUS_DP_LINK: + MODEM_DBG("--> DP LINK\n"); + if(NONEC_DP(m->dp->id)) + m->cfg.ec = 0; + modem_set_state(m,STATE_EC_ESTAB); + /* start packer */ + if(m->cfg.ec && m->cfg.ec_detector && + !QC_SKIP_EC_DETECTION(m) ) { + modem_detector_start(m); + m->get_bits = modem_detector_get_bits; + m->put_bits = modem_detector_put_bits; + } + else { /* skip pack connect phase */ + modem_update_status(m,STATUS_PACK_LINK); + } + break; + case STATUS_PACK_LINK: + MODEM_DBG("--> PACK LINK\n"); + if(m->cfg.ec) { + /* start EC */ + modem_hdlc_start(m); + m->get_bits = modem_hdlc_get_bits; + m->put_bits = modem_hdlc_put_bits; + modem_ec_start(m); + } + else { + /* start async, pass EC connect phase */ + modem_async_start(m); + m->get_bits = modem_async_get_bits; + m->put_bits = modem_async_put_bits; + modem_update_status(m,STATUS_EC_LINK); + } + break; + /* case STATUS_CONNECT: */ + case STATUS_EC_LINK: + MODEM_DBG("--> EC LINK\n"); + modem_set_state(m,STATE_MODEM_ONLINE); + modem_report_result(m,RESULT_CONNECT); // fixme + if(SPEAKER_CONTROL(m) == 1) + m->driver.ioctl(m,MDMCTL_SPEAKERVOL,0); + break; + case STATUS_EC_RELEASE: + case STATUS_EC_ERROR: + MODEM_DBG("--> EC UNLINK\n"); + m->result_code = RESULT_NOCARRIER; + modem_hup(m,(m->state == STATE_EC_DISC)); + break; + case STATUS_ERROR: + case STATUS_DP_ERROR: + case STATUS_NOCARRIER: + case STATUS_NODIALTONE: + case STATUS_BUSY: + case STATUS_NOANSWER: + default: + MODEM_DBG("--> FINISH.\n"); + if(status == STATUS_NODIALTONE) + m->result_code = RESULT_NODIALTONE; + else if(status == STATUS_BUSY) + m->result_code = RESULT_BUSY; + else if(status == STATUS_NOANSWER) + m->result_code = RESULT_NOANSWER; + else + m->result_code = RESULT_NOCARRIER; + modem_hup(m,IS_STATE_DISC(m->state)); + break; + } +} + + + +void modem_update_config(struct modem *m, struct modem_config *cfg) +{ + MODEM_DBG("modem update config...\n"); +#if 1 +#define PRINT_CONFIG(prm) MODEM_DBG(#prm " = %d (%d)\n",cfg->prm,m->cfg.prm) + PRINT_CONFIG(ec); + PRINT_CONFIG(ec_detector); + PRINT_CONFIG(ec_tx_win_size); + PRINT_CONFIG(ec_rx_win_size); + PRINT_CONFIG(ec_tx_info_size); + PRINT_CONFIG(ec_rx_info_size); + PRINT_CONFIG(comp); + PRINT_CONFIG(comp_dict_size); + PRINT_CONFIG(comp_max_string); +#endif + // FIXME, FIXME, FIXME !!! +#if 0 + if(cfg->ec) ; /* TBD: now ec reconfig is handled internally in EC */ +#endif + if(cfg->comp && m->cfg.comp) { + m->cfg.comp = cfg->comp; + if(!modem_comp_config(m,cfg->comp_dict_size, + cfg->comp_max_string)) { + m->cfg.comp_dict_size = cfg->comp_dict_size; + m->cfg.comp_max_string = cfg->comp_max_string; + } + else { /* config failed */ + ; /* TBD: probably try to renegotiate */ + } + } + else + m->cfg.comp = 0; +} + + +/* + * Interrupt handlers and services + * + */ + +/* get/put bits */ +int modem_get_bits(struct modem *m, int nbits, u8 *buf, int n) +{ + if(m->get_bits) + n = m->get_bits(m,nbits,buf,n); + else + memset(buf,0xff,n); + modem_debug_log_data(m,MODEM_DBG_TX_BITS,buf,n); + /* process bit timer and packer */ + if (m->bit_timer && (m->bit_timer -= nbits*n) <= 0) { + m->bit_timer = 0; + m->bit_timer_func(m); + } + // FIXME NOW: remove packer_process from modem to EC + if(m->packer_process) + m->packer_process(m,nbits*n); + return n; +} + +int modem_put_bits(struct modem *m, int nbits, u8 *buf, int n) +{ + if(m->put_bits) + n = m->put_bits(m,nbits,buf,n); + modem_debug_log_data(m,MODEM_DBG_RX_BITS,buf,n); + return n; +} + + +static unsigned dpstat2status(unsigned dpstat) +{ + switch (dpstat) { + case DPSTAT_OK: return STATUS_OK; + case DPSTAT_CONNECT: return STATUS_DP_LINK; + case DPSTAT_ERROR: return STATUS_DP_ERROR; + case DPSTAT_NODIALTONE: return STATUS_NODIALTONE; + case DPSTAT_BUSY: return STATUS_BUSY; + case DPSTAT_NOANSWER: return STATUS_NOANSWER; + case DPSTAT_CHANGEDP: return STATUS_OK; + default: return STATUS_ERROR; + } +} + + +static void modem_dp_process(struct modem *m,void *in,void *out,int count) +{ + int ret; + unsigned cnt; + //MODEM_DBG("modem_process %d: %d...\n", m->count,count); + while(count && m->dp) { + cnt = count; + if (cnt > m->frag) + cnt = m->frag; + //MODEM_DBG("%d: running dp %s...\n", m->count,dp->name); + ret = m->dp->op->process(m->dp,in,out,cnt); + switch(ret) { + case DPSTAT_OK: + break; + case DPSTAT_CONNECT: + if(!IS_STATE_LINKED(m->state) && + !IS_STATE_DISC(m->state)) { + modem_update_status(m,STATUS_DP_LINK); + } + break; + case DPSTAT_CHANGEDP: + do_modem_change_dp(m); + break; + default: /* errors */ + modem_update_status(m,dpstat2status(ret)); + m->process = NULL; + break; + } + + count -= cnt; + out += cnt<format); + in += cnt<format); + } + if(count) + memset(out,0,count<format)); +} + + +void modem_process(struct modem *m,void *in,void *out,int count) +{ + /* clean DC */ + dcr_process(m->dcr,in,count); + modem_debug_log_data(m,MODEM_DBG_RX_SAMPLES,in,count<format)); + if(m->process) + m->process(m,in,out,count); + else /* mute output */ + memset(out,0,count<format)); + modem_debug_log_data(m,MODEM_DBG_TX_SAMPLES,out,count<format)); + m->count+=count; + if( m->sample_timer && m->count >= m->sample_timer ) { + void (*f)(struct modem *) = m->sample_timer_func ; + m->sample_timer = 0; + m->sample_timer_func = NULL; + if(f) f(m); + } +} + + +/* + * event processing + * + */ + + +static void timer_mark_event (void *data) +{ + struct modem *m = data; +#ifdef DEBUG_TIMERS + MODEM_DBG("timer_mark_event: %x | %x : now = %lu...\n", + m->event, m->new_event, get_time()); +#endif + m->event |= m->new_event; + m->new_event = 0; +} + +static void schedule_event(struct modem *m, unsigned mask, unsigned long when) +{ + m->new_event |= mask; + m->event_timer.data = m; + m->event_timer.func = timer_mark_event; + m->event_timer.expires = get_time() + when; +#ifdef DEBUG_TIMERS + MODEM_DBG("schedule_event: %x | %x : now %lu + %lu = %u...\n", + m->new_event, mask, + get_time(), when, m->event_timer.expires); +#endif + timer_add(&m->event_timer); +} + + +void modem_event(struct modem *m) +{ + unsigned event = m->event; + m->event = 0; + MODEM_DBG("modem_event: %x...\n", event); + + if(event&MDMEVENT_RING_CHECK) { + if(m->ring_count == 0) { + MODEM_DBG("ring cancel...\n"); + TOTAL_RINGS_COUNT(m) = 0; + } + else if ( time_before(m->ring_last,m->ring_first+RING_ON_MIN(m)) || + time_after(m->ring_last,m->ring_first+RING_ON_MAX(m)) || + m->ring_count < RING_COUNT_MIN(m)) { + MODEM_DBG("ring reject: count %d (%lu-%lu)\n", + m->ring_count,m->ring_first,m->ring_last); + TOTAL_RINGS_COUNT(m) = 0; + m->ring_count = 0; + } + else { + MODEM_DBG("ring valid.\n"); + m->ring_count = 0; + TOTAL_RINGS_COUNT(m)++; + if(TOTAL_RINGS_COUNT(m) == 1) + modem_put_chars(m,CRLF_CHARS(m),2); + modem_report_result(m,RESULT_RING); + if (ANSWER_AFTER_RINGS(m) && +#ifdef MODEM_CONFIG_RING_DETECTOR + (!m->started || m->rd_obj) && +#else + !m->started && +#endif + TOTAL_RINGS_COUNT(m) >= ANSWER_AFTER_RINGS(m)) { + TOTAL_RINGS_COUNT(m) = 0; + modem_answer(m); + } + else { + schedule_event(m,MDMEVENT_RING_CHECK, + RING_OFF_MAX(m) + 1); + } + } + } + if(event&MDMEVENT_ESCAPE) { + MODEM_DBG("modem_escape (count %d)...\n", m->escape_count); + if (m->state == STATE_MODEM_ONLINE && m->escape_count == 3) { + modem_set_state(m, STATE_COMMAND_ONLINE); + m->xmit.head = m->xmit.tail = m->xmit.count = 0; + modem_put_chars(m,CRLF_CHARS(m),2); + modem_report_result(m,RESULT_OK); + m->command = 1; + } + m->escape_count = 0; + } +} + +void modem_ring(struct modem *m) +{ + unsigned long now = get_time(); + if (m->state != STATE_MODEM_IDLE) + return; + m->ring_count++; + if(m->ring_count == 1) { + MODEM_DBG("modem_ring...\n"); + if(time_before(now,m->ring_last + RING_OFF_MIN(m))) { + MODEM_DBG("bad ring: now %lu, last %lu.\n", + now,m->ring_last); + m->ring_count = 0; + } + else { + m->ring_first = now; + schedule_event(m,MDMEVENT_RING_CHECK, + RING_ON_MAX(m) + 1); +#ifdef MODEM_CONFIG_CID + if (TOTAL_RINGS_COUNT(m) == 0 && m->cid_requested) + modem_cid_start(m, RING_ON_MAX(m) + RING_OFF_MIN(m)); +#endif + } + } + m->ring_last = now; +} + + +void modem_error(struct modem *m) +{ + MODEM_DBG("modem error...\n"); +} + + + +/* command mode processing */ +static void modem_at_process(void *data) +{ + struct modem *m = (struct modem *)data; + int echo = IS_ECHO(m); + char lf = LF_CHAR(m), cr = CR_CHAR(m), bs = BS_CHAR(m); + int ret; + char ch; + while(1) { + if(modem_get_chars(m,&ch,1) <= 0) + break; + if (ch == '/' && m->at_count == 1 && + toupper(m->at_line[0]) == 'A') { + m->at_count = strlen(m->at_line); + if(echo) + modem_put_chars(m,m->at_line+1,m->at_count-1); + ch = cr; + } + if (echo) + modem_put_chars(m,&ch,1); + if (ch == cr || ch == lf) { + int i; + char *p = m->at_cmd; + m->at_line[m->at_count] = '\0'; + for(i = 0 ; i < m->at_count ; i++) { + if( m->at_line[i] == ' ' || + m->at_line[i] == '\t' ) + continue; + *p++ = m->at_line[i]; + } + *p = '\0'; + if (strlen(m->at_cmd) < 2 || + toupper(m->at_cmd[0]) != 'A' || + toupper(m->at_cmd[1]) != 'T' ) { + memset(m->at_line,' ',m->at_count); + if(echo) { + modem_put_chars(m,&cr,1); + modem_put_chars(m,m->at_line,m->at_count); + modem_put_chars(m,&cr,1); + } + m->at_count = 0; + continue; + } + if (echo) + modem_put_chars(m,CRLF_CHARS(m),2); + MODEM_DBG("run cmd: %s\n",m->at_cmd); + ret = process_at_command(m, m->at_cmd); + if (ret < 0) + modem_report_result(m,RESULT_ERROR); + else if (ret==0) + modem_report_result(m,RESULT_OK); + m->at_line[m->at_count] = '\0'; + m->at_count = 0; + echo = IS_ECHO(m); + cr = CR_CHAR(m), lf = LF_CHAR(m), bs = BS_CHAR(m); + } + else if (ch == bs && m->at_count) { + m->at_count--; + if(echo) { + ch = ' '; + modem_put_chars(m,&ch,1); + modem_put_chars(m,&bs,1); + } + } + else if (m->at_count == sizeof(m->at_line) - 1) { + if (echo) + modem_put_chars(m,CRLF_CHARS(m),2); + m->at_count = 0; + m->at_line[1] = '\0'; + modem_report_result(m,RESULT_ERROR); + } + else { + m->at_line[m->at_count++] = ch; + } + } +} + + +/* + * TTY procedures + * + */ + + +/* get chars */ +static int modem_get_chars(struct modem *m, char *buf, int n) +{ + int ret = 0, cnt; + while(n) { + cnt = n; + if (cnt > m->xmit.count) + cnt = m->xmit.count; + if (cnt > m->xmit.size - m->xmit.tail) + cnt = m->xmit.size - m->xmit.tail; + if (cnt <= 0) { + break; + } + memcpy(buf, m->xmit.buf + m->xmit.tail, cnt); + ret += cnt; + n -= cnt; + buf += cnt; + m->xmit.count -= cnt; + m->xmit.tail = (m->xmit.tail+cnt)%m->xmit.size; + } + //MODEM_DBG("modem_get_chars: %d...\n", n); + return ret; +} + +/* put chars */ +static int modem_put_chars(struct modem *m, const char *buf, int n) +{ + int ret = write(m->pty,buf,n); + if(ret < 0) { + /* perror("write"); */ + ret = 0; + } +#if 0 + if(ret>0) { + //MODEM_DBG("modem_comp_put_chars: %d...\n",i); + modem_debug_log_data(m, MODEM_DBG_RX_CHARS,buf,i); + } +#endif + return ret; +} + +/* compressor get/put chars */ +/* fixme: unify interfaces: modem tx -> comp -> ec -> hdlc --> + modem tx -> ec -> hdlc --> + modem tx -> async --> + modem tx --> raw output +*/ +static int modem_comp_get_chars(struct modem *m, char *buf, int n) +{ + int ret = 0, cnt; + char ch; + while(ret < n) { + cnt = modem_get_chars(m,&ch,1); + if(cnt <= 0) + break; + cnt = modem_comp_encode(m,ch,buf+ret,n-ret); + if(cnt < 0) { + break; + } + ret += cnt; + } + if(ret < n) { + cnt = modem_comp_flush_encoder(m,buf+ret,n-ret); + ret += cnt; + } + if(ret > 0) { + //MODEM_DBG("modem_comp_get_chars: %d(%d)...\n",ret,count); + modem_debug_log_data(m,MODEM_DBG_TX_DATA,buf,ret); + } + return ret; +} + +static int comp_send_output(struct modem *m) +{ + int cnt; + if(m->comp.count > 0) { + cnt = modem_put_chars(m,m->comp.buf+m->comp.head,m->comp.count); + m->comp.count -= cnt; + m->comp.head += cnt; + if(m->comp.count > 0) + return 0; + else + m->comp.head = 0; + } + return 1; +} + +static int modem_comp_put_chars(struct modem *m, const char *buf, int n) +{ + int i=0, cnt; + if(!comp_send_output(m)) + return 0; + while(icomp.buf,sizeof(m->comp.buf)); + if(cnt < 0) { + MODEM_DBG("decoder error. %d(%d)\n",i,n); + modem_update_status(m,STATUS_ERROR); + break; + } + m->comp.count += cnt; + if(!comp_send_output(m)) + break; + } + if(i==n) { + cnt = modem_comp_flush_decoder(m,m->comp.buf,sizeof(m->comp.buf)); + m->comp.count += cnt; + comp_send_output(m); + } + if(i>0) { + //MODEM_DBG("modem_comp_put_chars: %d...\n",i); + modem_debug_log_data(m,MODEM_DBG_RX_DATA,buf,i); + } + return i; +} + + + + +/* + * internal procedures + * + */ + +#define IS_FAST_DP(id) (id == DP_V34 || id == DP_V90 || id == DP_V92) + +static void do_modem_change_dp (struct modem *m) +{ + struct dp_operations *op; + struct dp *old; + + old = m->dp; + + if (m->mode == MODEM_MODE_FAX) { + modem_fax_start(m); + m->dp = NULL; + } + else { + struct dp *dp = NULL; + int dp_id,id; + dp_id = m->dp_requested; + m->dp_requested = 0; + + id = dp_id; + if(dp_id == 0) { + dp_id = MODEM_DP(m); + id = IS_FAST_DP(dp_id) ? DP_V8 : dp_id; + } + + MODEM_DBG("%ld: change dp: --> %d...\n", m->count, id); + + op = get_dp_operations(id); + if (op && op->create) + dp = op->create(m,dp_id, + m->caller,m->srate, + m->frag,op); + if (!dp) { + MODEM_ERR("change dp -> %d error.\n", id); + modem_hup(m,1); + return; + } + + m->dp = dp; + m->process = modem_dp_process; + } + + if ( old ) { + old->op->delete(old); + } + +} + + +static int modem_set_hook(struct modem *m, unsigned hook_state) +{ + int ret; + MODEM_DBG("modem set hook: %d --> %d...\n", m->hook, hook_state); + if ( m->hook == hook_state ) + return 0; + ret = m->driver.ioctl(m, MDMCTL_HOOKSTATE,hook_state); + if (!ret) + m->hook = hook_state; + return ret; +} + +static void modem_setup_config(struct modem *m) +{ + m->cfg.ec = MODEM_EC_ENABLE(m); + m->cfg.ec_detector = MODEM_EC_DETECTOR(m); + m->cfg.ec_tx_win_size = LAPM_MAX_WIN_SIZE; + m->cfg.ec_rx_win_size = LAPM_MAX_WIN_SIZE; + m->cfg.ec_tx_info_size = LAPM_MAX_INFO_SIZE; + m->cfg.ec_rx_info_size = LAPM_MAX_INFO_SIZE; + if(m->cfg.ec && MODEM_COMP_ENABLE(m)) + m->cfg.comp = 0x3; /* bi-directional v42bis */ + else + m->cfg.comp = 0; + m->cfg.comp_dict_size = COMP_MAX_CODEWORDS; + m->cfg.comp_max_string = COMP_MAX_STRING; + + /* setup dsp data */ + m->dsp_info.qc_lapm = m->cfg.ec && m->cfg.ec_detector ; +} + + +static int do_modem_start(struct modem *m) +{ + int ret; + ret = m->driver.ioctl(m, MDMCTL_SPEED, m->srate); + ret = m->driver.ioctl(m, MDMCTL_SETFRAG, m->frag); + m->count = 0; + ret = m->driver.start(m); + m->started = !ret; + return ret; +} + +static int modem_start (struct modem *m) +{ + int ret; + + MODEM_DBG("modem_start..\n"); + if(m->started && modem_stop(m)) + return -1; + + m->result_code = 0; + modem_setup_config(m); + modem_set_state(m, STATE_ESTAB); + + if(SPEAKER_CONTROL(m) == 1) + m->driver.ioctl(m,MDMCTL_SPEAKERVOL,SPEAKER_VOLUME(m)); + ret = modem_set_hook(m, MODEM_HOOK_OFF); + if (ret) + goto error; + + m->xmit.head = m->xmit.tail = m->xmit.count = 0; + m->command = 0; + + if( !(m->dcr= dcr_create()) || + !(m->dp_runtime = dp_runtime_create(m))) { + ret = -1; + goto error; + } + + if ( m->cfg.ec && m->cfg.comp && + (ret = modem_comp_init(m)) ) + goto error; + if ( m->cfg.ec && + (ret = modem_ec_init(m))) + goto error; + + /* clear rings and all events */ + TOTAL_RINGS_COUNT(m) = 0; + m->ring_count = 0; + m->event = m->new_event = 0; + timer_del(&m->event_timer); + + ret = do_modem_start(m); + if (!ret) + return 0; + + error: + MODEM_ERR("modem start = %d: cannot start device.\n",ret); + m->result_code = RESULT_NOCARRIER; + modem_stop(m); + return ret; +} + + +static int modem_stop (struct modem *m) +{ + int ret = 0; + MODEM_DBG("modem_stop..\n"); + + m->process = NULL; + + if(m->started) { + ret = m->driver.stop(m); + m->started = ret; + if ( ret ) { + MODEM_ERR("modem stop = %d: cannot stop device.\n",ret); + } + } + modem_set_hook(m, MODEM_HOOK_ON); + if(SPEAKER_CONTROL(m) == 1) + m->driver.ioctl(m,MDMCTL_SPEAKERVOL,0); + m->caller = 0; + m->command = 1; + + // FIXME: If ec,comp were allocated handled inside _exit() - improve? + modem_ec_exit(m); + modem_comp_exit(m); + + if (m->dp) { + struct dp *dp; + dp = m->dp; + m->dp = 0; + if(dp) dp->op->delete(dp); + } + if (m->dp_runtime) { + dp_runtime_delete(m->dp_runtime); + m->dp_runtime = NULL; + } + if (m->dcr) { + dcr_delete(m->dcr); + m->dcr = NULL; + } +#ifdef MODEM_CONFIG_RING_DETECTOR + if(m->rd_obj) { + RD_delete(m->rd_obj); + m->rd_obj = NULL; + } +#endif +#ifdef MODEM_CONFIG_CID + if(m->cid) { + CID_delete(m->cid); + m->cid = NULL; + } +#endif +#ifdef MODEM_CONFIG_VOICE + if(m->voice_obj) { + VOICE_delete(m->voice_obj); + m->voice_obj = NULL; + } +#endif +#ifdef MODEM_CONFIG_FAX + if(m->fax_obj) { + FAX_delete(m->fax_obj); + m->fax_obj = NULL; + } +#endif + modem_set_state(m, STATE_MODEM_IDLE); + if (m->result_code) { + modem_report_result(m, m->result_code); + m->result_code = 0; + } + + m->count = 0; + return m->started; +} + + +/* + * Caller ID + * + */ + +#ifdef MODEM_CONFIG_CID + +static void modem_cid_stop(struct modem *m) +{ + MODEM_DBG("modem_cid_stop...\n"); + m->sample_timer = 0; + m->sample_timer_func = NULL; +#ifdef MODEM_CONFIG_RING_DETECTOR + if(!m->rd_obj) { + m->process = NULL; + modem_stop(m); + } + else { + CID_delete(m->cid); + m->cid = NULL; + } +#else + m->process = NULL; + modem_stop(m); +#endif + /* continue with answer if need */ + if (ANSWER_AFTER_RINGS(m) && + TOTAL_RINGS_COUNT(m) >= ANSWER_AFTER_RINGS(m)) { + TOTAL_RINGS_COUNT(m) = 0; + modem_answer(m); + } +} + +static void modem_cid_process(struct modem *m, void *in, void *out, int count) +{ + int status; + //MODEM_DBG("modem_cid_process: %d...\n", count); + memset(out,0,count*2); + status = CID_process(m->cid, in, count); + if(status) { + if(status < 0) + MODEM_DBG("CID failed.\n"); + modem_cid_stop(m); + } +} + +static int modem_cid_start(struct modem *m, unsigned timeout) +{ + MODEM_DBG("modem_cid_start: timeout = %d...\n", timeout); +#ifdef MODEM_CONFIG_RING_DETECTOR + if(m->started && !m->rd_obj) +#else + if(m->started) +#endif + return -1; + m->cid = CID_create(m, m->srate, m->cid_requested); + if(!m->cid) + return -1; + m->sample_timer = m->count + m->srate*timeout/MODEM_HZ ; + m->sample_timer_func = modem_cid_stop; +#ifdef MODEM_CONFIG_RING_DETECTOR + if(m->started && m->rd_obj) + return 0; +#endif + m->process = modem_cid_process; + modem_set_hook(m, MODEM_HOOK_SNOOPING); + return do_modem_start(m); +} + +#endif /* MODEM_CONFIG_CID */ + + +/* + * Ring detector (internal) + * + */ + +#ifdef MODEM_CONFIG_RING_DETECTOR +static void modem_ring_detector_process(struct modem *m, void *in, void *out, int count) +{ + int ret; + memset(out, 0, count*2); + ret = RD_process(m->rd_obj, in, count); + if (ret) { + long freq, duration; + RD_ring_details(m->rd_obj, &freq, &duration); + MODEM_DBG("ring details: freq = %ld, duration = %ld\n", + freq, duration); + if(freq == 0) { + MODEM_DBG("report ring start...\n"); + modem_ring(m); + } + else if (freq > 0) { + MODEM_DBG("report ring end...\n"); + /* ring finishing */ + m->event |= MDMEVENT_RING_CHECK; + if (m->ring_count <= 1) + m->ring_count = duration * freq / 1000 ; + m->ring_last = get_time(); + } + else + MODEM_ERR("RD returns %ld freq. (duration %ld)\n", + freq, duration); + } +#ifdef MODEM_CONFIG_CID + if(m->cid) + modem_cid_process(m, in, out, count); +#endif +} + +int modem_ring_detector_start(struct modem *m) +{ + MODEM_DBG("modem_ring_detector_start...\n"); + if(m->rd_obj) { + MODEM_ERR("modem_ring_detector_start: rd_obj already exists!\n"); + return -1; + } + m->rd_obj = RD_create(m, m->srate); + m->process = modem_ring_detector_process; + modem_set_hook(m, MODEM_HOOK_SNOOPING); + return do_modem_start(m); +} +#endif /* MODEM_CONFIG_RING_DETECTOR */ + + +/* + * Voice modem + * + */ + +#ifdef MODEM_CONFIG_VOICE +extern void modem_voice_stop(struct modem *m); + +static void modem_voice_process(struct modem *m, void *in, void *out, int count) +{ + int status; + //MODEM_DBG("modem_voice_process: %d...\n", count); + status = VOICE_process(m->voice_obj, in, out, count); + if(status) { + MODEM_DBG("modem_voice_process: status %d\n", status); + switch(status) { + case VOICE_STATUS_OK: + modem_report_result(m, RESULT_OK); + m->command = 1; + break; + case VOICE_STATUS_CONNECT: + modem_report_result(m, RESULT_CONNECT); + m->command = 0; + break; + case VOICE_STATUS_ERROR: + modem_report_result(m, RESULT_ERROR); + m->command = 1; + break; + default: + break; + } + if(status < 0) { + MODEM_DBG("VOICE failed.\n"); + modem_voice_stop(m); + } + } +} + +int modem_voice_command(struct modem *m, enum VOICE_CMD cmd) +{ + MODEM_DBG("modem_voice_command: %u...\n", cmd); + switch(cmd) { + case VOICE_CMD_BEEP: + case VOICE_CMD_DTMF: + case VOICE_CMD_STATE_RX: + case VOICE_CMD_STATE_TX: + if(!m->voice_obj) + return -1; + m->command = 0; + VOICE_command(m->voice_obj, cmd); + return 1; + default: + return -1; + } + return 0; +} + +int modem_voice_start(struct modem *m) +{ + MODEM_DBG("modem_voice_start...\n"); + if(m->voice_obj) + return 0; + if(m->started) { +#ifdef MODEM_CONFIG_RING_DETECTOR + if(m->rd_obj) + modem_stop(m); + else +#endif + return -1; + } + m->voice_obj = VOICE_create(m, m->srate); + if(!m->voice_obj) + return -1; + m->sample_timer = 0 /* m->srate*timeout/MODEM_HZ */ ; + m->sample_timer_func = NULL /* modem_voice_stop */ ; + m->process = modem_voice_process; + modem_set_hook(m, MODEM_HOOK_OFF); + return do_modem_start(m); +} + +void modem_voice_stop(struct modem *m) +{ + MODEM_DBG("modem_voice_stop...\n"); + m->process = NULL; + m->sample_timer = 0; + m->sample_timer_func = NULL; + if(m->voice_obj) { + VOICE_delete(m->voice_obj); + m->voice_obj = NULL; + } + modem_stop(m); + modem_set_hook(m, MODEM_HOOK_ON); +} + +int modem_voice_set_device(struct modem *m, unsigned device) +{ + MODEM_DBG("modem_voice_set_device: dev = %u...\n", device); + if (device == VOICE_DEVICE_NONE) { + if(m->voice_obj) + modem_voice_stop(m); + return 0; + } + else if (device == VOICE_DEVICE_LINE) { + if(m->voice_obj) + return 0; + else if(modem_voice_start(m)) + return -1; + return 1; + } + return -1; +} + +int modem_voice_init(struct modem *m) +{ + m->voice_info.comp_method = 1; + m->voice_info.sample_rate = 8000; + m->voice_info.rx_gain = 128; + m->voice_info.tx_gain = 128; + m->voice_info.dtmf_symbol = 0; + m->voice_info.tone1_freq = 933; + m->voice_info.tone2_freq = 0; + m->voice_info.tone_duration = 150; + m->voice_info.inactivity_timer = 0; + m->voice_info.silence_detect_sensitivity = 128; + m->voice_info.silence_detect_period = 50; + return 0; +} + +#endif /* MODEM_CONFIG_VOICE */ + + +/* + * Fax modem + * + */ + +#ifdef MODEM_CONFIG_FAX + +static void modem_fax_process(struct modem *m, void *in, void *out, int count) +{ + int ret; + //MODEM_DBG("modem_fax_process: %d...\n", count); + ret = FAX_process(m->fax_obj, in, out, count); + if(ret) { + MODEM_DBG("fax_process: %d\n", ret); + switch(ret) { + case FAX_STATUS_OK: + modem_set_state(m, STATE_COMMAND_ONLINE); + modem_report_result(m, RESULT_OK); + m->command = 1; + break; + case FAX_STATUS_CONNECT: + modem_set_state(m,STATE_MODEM_ONLINE); + modem_report_result(m, RESULT_CONNECT); + m->command = 0; + break; + case FAX_STATUS_NOCARRIER: + modem_set_state(m, STATE_COMMAND_ONLINE); + modem_report_result(m, RESULT_NOCARRIER); + m->command = 1; + break; + case FAX_STATUS_ERROR: + modem_update_status(m, STATUS_ERROR); + break; + default: + break; + } + if(ret < 0) { + MODEM_DBG("FAX failed.\n"); + modem_stop(m); + } + } +} + +static int modem_fax_start(struct modem *m) +{ + MODEM_DBG("modem_fax_start...\n"); + m->fax_obj = FAX_create(m, m->caller, m->srate); + if(!m->fax_obj) + return -1; + m->sample_timer = 0; + m->sample_timer_func = NULL; + m->process = modem_fax_process; + return 0; +} + +#endif /* MODEM_CONFIG_FAX */ + + +/* + * Commands + * + */ + +int modem_send_to_tty(struct modem *m, const char *buf, int n) +{ + return modem_put_chars(m, buf, n); +} + +int modem_recv_from_tty(struct modem *m, char *buf, int n) +{ + return modem_get_chars(m, buf, n); +} + +int modem_answer(struct modem *m) +{ + MODEM_DBG("modem answer...\n"); + if ( m->dp ) { + MODEM_ERR("dp %d is already exists.\n", m->dp->id); + return -1; + } + if(m->started) + modem_stop(m); + m->dp_requested = 0; + m->automode_requested = 0; /* MODEM_AUTOMODE(m) */ + m->sample_timer = ANSWER_DELAY(m) ? + ANSWER_DELAY(m)*m->srate : m->srate/100; + m->sample_timer_func = do_modem_change_dp; + return modem_start(m); +} + + +static int modem_dial_start(struct modem *m) +{ + struct dp_operations *op; + struct dp *dp = NULL; + MODEM_DBG("modem_dial_start...\n"); + if(m->dp) { + return -1; + } + if (m->started) + modem_stop(m); + m->caller = 1; + op = get_dp_operations(DP_CALLPROG); + char save = m->dial_string[0]; // hide the dial string so no DTMF is generated + m->dial_string[0] = 0; + if (op && op->create) + dp = op->create(m,DP_CALLPROG, + m->caller,m->srate, + m->frag,op); + m->dial_string[0] = save; + if (!dp) { + MODEM_ERR("cannot create CALLPROG.\n"); + return -1; + } + m->dp = dp; + m->process = modem_dp_process; + return 0; +} + +int modem_dial(struct modem *m) +{ + int ret; + MODEM_DBG("modem dial: %s...\n", m->dial_string); + m->dp_requested = 0; + m->automode_requested = 0; + ret = modem_dial_start(m); + if(ret) + return -1; + return modem_start(m); +} + + +int modem_hook(struct modem *m, unsigned hook_state) +{ + MODEM_DBG("modem hook...\n"); + if ( m->hook == hook_state ) + return 0; + if (!IS_STATE_IDLE(m->state)) + modem_hup(m,1); + return modem_set_hook(m,hook_state); +} + +int modem_online(struct modem *m) +{ + MODEM_DBG("modem online...\n"); + if (m->state != STATE_COMMAND_ONLINE) + return -1; + m->command = 0; + modem_set_state(m, STATE_MODEM_ONLINE); + modem_report_result(m,RESULT_CONNECT); // fixme + return 0; +} + +void modem_update_speaker(struct modem *m) +{ + //MODEM_DBG("modem update speaker...\n"); + m->driver.ioctl(m,MDMCTL_SPEAKERVOL, + SPEAKER_CONTROL(m) == 2 ? SPEAKER_VOLUME(m):0); +} + +int modem_get_sreg(struct modem *m, unsigned int num) +{ + if (num >= sizeof(m->sregs)) + return -1; + return m->sregs[num]; +} + +int modem_set_sreg(struct modem *m, unsigned int num, int val) +{ + if (num >= sizeof(m->sregs)) + return -1; + m->sregs[num] = val; + return 0; +} + +/* homolog set initialization */ +int modem_homolog_init(struct modem *m, int id, const char *name) +{ + const struct homolog_set *set; + for(set=homolog_set;set->name;set++) { + if(set->id == id || + (name && *name && !strcmp(name,set->name))) { + m->homolog = set; + modem_set_sreg(m,SREG_DIAL_PAUSE_TIME, + set->params->DialPauseTime); + modem_set_sreg(m,SREG_FLASH_TIMER, + set->params->HookFlashTime); + return 0; + } + } + return -1; +} + + +int modem_set_mode(struct modem *m, enum MODEM_MODE mode) +{ + MODEM_DBG("modem set mode: -> %d...\n", mode); + if (m->mode == mode) + return 0; +#ifdef MODEM_CONFIG_VOICE + if (m->mode == MODEM_MODE_VOICE && m->voice_obj) { + modem_voice_stop(m); + } +#endif + m->mode = mode; + return 0; +} + + +int modem_reset(struct modem *m) +{ + MODEM_DBG("modem reset...\n"); + if(m->state != STATE_MODEM_IDLE) + modem_hup(m,1); + else if(m->started) + modem_stop(m); + else if(m->hook) + modem_set_hook(m,MODEM_HOOK_ON); + modem_set_state(m, STATE_MODEM_IDLE); + m->command = 1; + m->min_rate = MODEM_MIN_RATE; + m->max_rate = MODEM_MAX_RATE; + sregs_init(m->sregs); + modem_homolog_init(m,m->homolog->id,NULL); + modem_set_mode(m, MODEM_MODE_DATA); + return 0; +} + + +/* + * Init functions + * + */ + +/* set default init values */ +static int sregs_init(unsigned char sregs[]) +{ + sregs[SREG_ESCAPE_CHAR] = '+' ; /* escape char */ + sregs[SREG_CR_CHAR] = '\r'; /* cr char */ + sregs[SREG_LF_CHAR] = '\n'; /* lf char */ + sregs[SREG_BS_CHAR] = '\b'; /* bs char */ + sregs[SREG_DIAL_TONE_WAIT_TIME] = 2; /* seconds */ + sregs[SREG_WAIT_CARRIER_AFTER_DIAL] = 60; /* seconds */ + sregs[SREG_DIAL_PAUSE_TIME] = 2; /* seconds */ + sregs[SREG_CARRIER_DETECT_RESPONSE_TIME] = 6; /* 0.1 sec */ + sregs[SREG_CARRIER_LOSS_DISCONNECT_TIME] = 7; /* 0.1 sec */ + sregs[SREG_DTMF_DURATION] = 100; /* ms */ + sregs[SREG_ESCAPE_PROMPT_DELAY] = 50; /* ms */ + sregs[SREG_FLASH_TIMER] = 20; /* 10ms */ + sregs[SREG_ECHO] = 1; /* yes */ + sregs[SREG_QUIET] = 0; /* no */ + sregs[SREG_VERBOSE] = 1; /* yes */ + sregs[SREG_TONE_OR_PULSE] = 1; /* tone */ + + sregs[SREG_X_CODE] = 4; + + sregs[SREG_SPEAKER_CONTROL] = 1; /* yes */ + sregs[SREG_SPEAKER_VOLUME] = 3; /* max */ + sregs[SREG_AUTOMODE] = 1; /* yes */ + sregs[SREG_DP] = DP_V92; + + sregs[SREG_ANS_DELAY] = 2; /* seconds */ + + sregs[SREG_LINE_QUALITY_CONTROL] = 0; + sregs[SREG_CD] = 0; + sregs[SREG_FLOW_CONTROL] = 0; + sregs[SREG_CONNNECT_MSG_FORMAT] = 0; + sregs[SREG_CONNNECT_MSG_SPEED_SRC] = 0; + + /* new sregs */ + sregs[SREG_EC] = 1; + sregs[SREG_COMP] = 0x3; + + return 0; +} + + + +/* ---------------------------------------------------------------- */ + +void modem_hangup(struct modem *m) +{ + modem_hup(m,1); +} + + +void modem_update_termios(struct modem *m, struct termios *tios) +{ + MODEM_DBG("update termios...\n"); + if( cfgetispeed(tios) == B0 || + cfgetospeed(tios) == B0 ) { + MODEM_DBG("modem_update_termios: hangup.\n"); + if(m->state!=STATE_MODEM_IDLE) + modem_hup(m,1); + // TBD: drop DTR? + } + else + m->modem_info |= TIOCM_DTR; + m->termios = *tios; +} + + +/* + * + * modem_write() + * + */ + + +static int modem_check_escape(struct modem *m, const char *buf, int count) +{ + unsigned long now = get_time(); + int i; + if(count + m->escape_count > 3 ) + goto noescape_out; + for( i = 0 ; i < count ; i++) { + if(buf[i] != ESCAPE_CHAR(m)) + goto noescape_out; + } + + if(m->escape_count == 0) { + if(time_before(now, m->last_esc_check + ESCAPE_TIMEOUT(m))) + goto noescape_out; + } + else if (time_after(now, m->last_esc_check + ESCAPE_TIMEOUT(m))) + goto noescape_out; + + m->escape_count += count; + if(m->escape_count == 3) + schedule_event(m,MDMEVENT_ESCAPE,ESCAPE_TIMEOUT(m)); + + m->last_esc_check = now; + return m->escape_count; + + noescape_out: + m->escape_count = 0; + m->last_esc_check = now; + return 0; +} + + + +int modem_write(struct modem *m, const char *buffer, int count) +{ + const char *buf; + int cnt, ret = 0; + if(IS_STATE_CONNECTING(m->state)) { + MODEM_DBG("modem_tty_write: hangup...\n"); + modem_hup(m,1); + return count; + } + + if(m->state == STATE_MODEM_ONLINE) + modem_check_escape(m,buffer,count); + + while(count) { + cnt = count; + if(cnt > m->xmit.size - m->xmit.count) + cnt = m->xmit.size - m->xmit.count; + if(cnt > m->xmit.size - m->xmit.head) + cnt = m->xmit.size - m->xmit.head; + if(cnt <= 0) { + MODEM_DBG("modem_write: overflow!\n"); + break; + } + buf = buffer; + memcpy(m->xmit.buf + m->xmit.head, buf, cnt); + m->xmit.count += cnt; + m->xmit.head = (m->xmit.head + cnt)%m->xmit.size; + ret += cnt; + buffer += cnt; + count -= cnt; + } + if(m->command) + modem_at_process(m); + return ret; +} + + + +void modem_print_version() +{ + MODEM_INFO("%s: version %s %s\n", + modem_name,modem_version,modem_date); +} + + +struct modem *modem_create(struct modem_driver *drv, const char *name) +{ + struct modem *m; + + modem_print_version(); + + m = malloc(sizeof(*m)); + if (!m) + return NULL; + memset(m,0,sizeof(*m)); + + m->name = name; + m->driver = *drv; + m->modem_info = 0; + m->state = STATE_MODEM_IDLE; + m->command= 1; + m->hook = MODEM_HOOK_ON; + m->caller = 0; + m->min_rate = MODEM_MIN_RATE; + m->max_rate = MODEM_MAX_RATE; + + m->modem_info |= (TIOCM_DSR|TIOCM_CTS); + + sregs_init(m->sregs); + + if(modem_homolog_init(m, MODEM_DEFAULT_COUNTRY_CODE, NULL)) { + MODEM_ERR("bad default country code `%x'!\n", + MODEM_DEFAULT_COUNTRY_CODE); + free(m); + return NULL; + } + if(modem_default_country && + modem_homolog_init(m, -1, modem_default_country)) { + MODEM_INFO("bad country name `%s', using default by code!\n", + modem_default_country); + } + + m->ring_last = get_time(); + + timer_init(&m->event_timer); + + /* setup config */ + modem_setup_config(m); + /* packer initializations */ + // fixme: TBD + + /* dp initialization */ + m->format = MODEM_FORMAT; + m->srate = MODEM_RATE; + m->frag = MODEM_FRAG; /* in samples */ + m->dp = NULL; + + MODEM_DBG("startup modem...\n"); + m->xmit.buf = malloc(XMIT_SIZE); + if ( !m->xmit.buf ) { + free(m); + return NULL; + } + m->xmit.size = XMIT_SIZE; + m->xmit.head = m->xmit.tail = m->xmit.count = 0; + m->modem_info |= TIOCM_DTR|TIOCM_RTS; + // TODO: update speed,DTR according to termios +#ifdef MODEM_CONFIG_VOICE + modem_voice_init(m); +#endif + + return m; +} + + + +void modem_delete(struct modem *m) +{ + MODEM_DBG("modem_delete...\n"); + if(m->started) { + MODEM_DBG("shutdown modem...\n"); + if(m->state != STATE_MODEM_IDLE) + m->result_code = RESULT_NOCARRIER; + modem_stop(m); + } + m->xmit.size = 0; + m->xmit.count = m->xmit.tail = m->xmit.head = 0; + free(m->xmit.buf); + m->xmit.buf = 0; + + timer_del(&m->event_timer); + free(m); +} + + + + diff --git a/slmodemd/modem.h b/slmodemd/modem.h new file mode 100644 index 0000000..3550d83 --- /dev/null +++ b/slmodemd/modem.h @@ -0,0 +1,460 @@ +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem.h - modem definitions + * + * Author: sashak@smlink.com + */ + +#ifndef __MODEM_H__ +#define __MODEM_H__ + +#include +#include +#include +#include + +#include +#include +#include +#include + + +/* modem modes */ +enum MODEM_MODE { + MODEM_MODE_DATA = 0, + MODEM_MODE_FAX = 1, + MODEM_MODE_VOICE = 8 +}; + + +/* modem status */ +#define STATUS_OK 0x0 +#define STATUS_NOCARRIER 0x0002 // 3 +#define STATUS_ERROR 0x0004 // 4 +#define STATUS_NODIALTONE 0x0010 // 6 +#define STATUS_BUSY 0x0020 // 7 +#define STATUS_NOANSWER 0x0040 // 8 +#define STATUS_DP_LINK 0x0100 // 13 +#define STATUS_DP_ERROR 0x0200 // 14 +#define STATUS_PACK_LINK 0x0400 // 15 +#define STATUS_PACK_ERROR 0x0800 // 16 +#define STATUS_EC_LINK 0x1000 // 17 +#define STATUS_EC_RELEASE 0x2000 // 18 +#define STATUS_EC_ERROR 0x4000 // 19 + + +/* + * parameters + * + */ + +#define MODEM_FORMAT MFMT_S16_LE +#define MODEM_RATE 9600 /* 8000 */ +#define MODEM_FRAG (MODEM_RATE/200) + + +#define MODEM_MIN_RATE 300 +#define MODEM_MAX_RATE 56000 + +#define MODEM_DEFAULT_COUNTRY_CODE 0xb5 /* USA */ + +#define MODEM_CONFIG_CID 1 +#define MODEM_CONFIG_VOICE 1 +#define MODEM_CONFIG_FAX 1 +#define MODEM_CONFIG_FAX_CLASS1 1 + +#define MODEM_CONFIG_RING_DETECTOR 1 + +/* + * type definitions + * + */ + + +/* modem driver struct */ +struct modem_driver { + const char *name; + int (*start)(struct modem *m); + int (*stop )(struct modem *m); + int (*ioctl)(struct modem *m,unsigned cmd, unsigned long arg); +}; + +/* modem data pumps driver struct */ +struct dp_driver { + const enum DP_ID id; + const char *name; + const char *code; + struct dp_operations *op; +}; + + +/* + * + * compressor definitions + * + */ + +#define COMP_MAX_CODEWORDS 2048 /* dictionary size */ +#define COMP_MAX_STRING 34 /* max string length */ + +/* encoder and decoder states */ +struct comp_state { + const char *name; + enum COMP_MODE {TRANSPARENT,COMPRESSED} mode; + int escape; /* escape state: decoder only */ + u16 update_at; /* update dict. at node */ + u16 next_free; /* next free dict entry */ + u16 last_matched; /* last matched dict entry */ + u16 last_added; /* last added dict entry */ + u16 cw_size; /* cw size */ + u16 threshold; /* cw size threshold */ + u8 escape_char; /* escape char value */ + int max_string; /* max string length */ + int dict_size; /* dictionary size */ + struct dict { + u8 ch; + u16 parent; + u16 child; + u16 next; + } *dict; /* dictionary */ + /* fixme: union may be used? */ + int bit_len; + u32 bit_data; + int flushed_len; /* string length already sent */ + int str_len; /* string length */ + u8 str_data[COMP_MAX_STRING]; + /* test statistics info : encoder only */ + u16 cmp_last; /* compressed bits per last TEST_SLICE chars */ + u32 cmp_bits; /* total compressed bits */ + u32 raw_bits; /* total non-compressed bits */ + /* temporary */ + int olen; + int ohead; + char obuf[1024]; +}; + + +extern int modem_comp_init(struct modem *m); +extern int modem_comp_config(struct modem *m, int dict_size, int max_str); +extern void modem_comp_exit(struct modem *m); + +extern int modem_comp_encode(struct modem *m, u8 ch, char *buf, int n); +extern int modem_comp_decode(struct modem *m, u8 ch, char *buf, int n); +extern int modem_comp_flush_encoder(struct modem *m, char *buf, int n); +extern int modem_comp_flush_decoder(struct modem *m, char *buf, int n); + +/* + * + * HDLC definitions + * + */ + +typedef struct hdlc_frame { + struct hdlc_frame *next; + int count; + int size; + //u16 addr; + //u16 ctrl; + u16 fcs; + u8 *buf; +} frame_t; + + + +/* + * LAPM definitions + * + */ + +#define LAPM_MAX_WIN_SIZE 15 /* max supported winsize */ +#define LAPM_MAX_INFO_SIZE 128 /* max supported infosize */ + +#define LAPM_INFO_FRAMES LAPM_MAX_WIN_SIZE + 1 /* number of info frames */ +#define LAPM_CTRL_FRAMES 8 /* number of ctrl frames */ + +/* lapm state */ +struct lapm_state { + /* modem link */ + struct modem *modem; + int state; + /* sub-states: may be optimized */ + int config; + /* those DATA sub-states may be optimized */ + int reject; + int busy; + int peer_busy; + u8 cmd_addr; + u8 rsp_addr; + u8 vs; + u8 va; + u8 vr; + int rtx_count; /* retransmission counter () */ + unsigned int tx_win_size; + unsigned int rx_win_size; + unsigned int tx_info_size; + unsigned int rx_info_size; + frame_t *sent_info; + frame_t *tx_info; + frame_t *info_list; + frame_t *tx_ctrl; + frame_t *ctrl_list; + /* temporary: internal buffs */ + /* rx buf (used when enter busy state) */ + int rx_count; + int rx_head; + u8 rx_buf[LAPM_MAX_INFO_SIZE]; + /* temporary: frames bufs */ + struct { + frame_t frame; + u8 ctrl[4]; + u8 info[LAPM_MAX_INFO_SIZE]; + } info_buf[LAPM_INFO_FRAMES]; + struct { + frame_t frame; + u8 ctrl[4]; + u8 info[LAPM_MAX_INFO_SIZE]; + } ctrl_buf[LAPM_CTRL_FRAMES]; + /* temporary: debug counters: remove it */ + int info_count; // debug + int tx_count; // debug + int sent_count; // debug + int ctrl_count; // debug +}; + + +/* modem struct */ +struct modem { + const char *name; + int pty; /* pty descriptor */ + const char *dev_name, *pty_name; /* and names */ + struct termios termios; + /* device driver */ + struct modem_driver driver; + void *dev_data; + /* modem states */ + unsigned modem_info; + unsigned state; + unsigned started; + unsigned command; + unsigned result_code; + unsigned hook; + unsigned caller; + unsigned rx_rate; + unsigned tx_rate; + enum MODEM_MODE mode; /* data,fax,voice */ + /* modem events (ring,escape,waiting for connect,etc) */ + unsigned event; + unsigned new_event; + struct timer event_timer; + /* modem parameters */ + unsigned min_rate; + unsigned max_rate; + unsigned char sregs[256]; /* s-registers */ + const struct homolog_set *homolog; /* homologation parameters */ + /* at processor */ + unsigned int at_count; + char at_line[64]; + char at_cmd[64]; + /* ring detector */ + unsigned int ring_count; + unsigned long ring_first; + unsigned long ring_last; +#ifdef MODEM_CONFIG_RING_DETECTOR + void *rd_obj; +#endif + /* cid */ +#ifdef MODEM_CONFIG_CID + unsigned cid_requested; + void *cid; +#endif + /* dialer */ + char dial_string[128]; + /* escape counter */ + unsigned escape_count; + unsigned long last_esc_check; + /* xmit queue */ + struct xmit_queue { + int count; + unsigned int head; + unsigned int tail; + unsigned int size; + unsigned char *buf; + } xmit; + /* run time configuration */ + struct modem_config { + /* ec params */ + u8 ec; + u8 ec_detector; + u8 ec_tx_win_size; + u8 ec_rx_win_size; + u16 ec_tx_info_size; + u16 ec_rx_info_size; + /* compressor params */ + u8 comp; + int comp_dict_size; + int comp_max_string; + } cfg; + /* modem packer */ + int (*get_chars)(struct modem *m, char *buf, int n); + int (*put_chars)(struct modem *m, const char *buf, int n); + //int tx_window; + //int rx_window; + int bit_timer; + void (*bit_timer_func)(struct modem *m); + void (*packer_process)(struct modem *m, int bits); + struct bits_state { + int bit; + u32 data; + } pack,unpack; + int (*get_bits)(struct modem *m, int nbits, u8 *buf, int n); + int (*put_bits)(struct modem *m, int nbits, u8 *buf, int n); + union packer_union { + struct async_state { + struct packer *packer; + int data_bits; + int stop_bits; + int parity; + int char_size; + } async; + struct detect_state { + int tx_count; + u8 tx_pattern[2]; + int rx_count; + u8 rx_pattern[2]; + int ec_enable; + } detector; + struct hdlc_state { + struct hdlc_frame *tx_frame; + struct hdlc_frame *rx_frame; + int rx_error; + int rx_ones,tx_ones; + /* framer interface */ + struct hdlc_frame *(*get_tx_frame)(void *framer); + void (*tx_complete)(void *framer, frame_t *fr); + void (*rx_complete)(void *framer, frame_t *fr); + void *framer; + /* temporary: internal bufs */ + struct hdlc_frame _rx_frame; + u8 _rx_buf[512]; + } hdlc; + } packer; + /* error corrector */ + union { + struct lapm_state lapm; + } ec; + /* compressor */ + struct comp_struct { + // fixme: redo interface + int head,count; + char buf[256]; + struct comp_state encoder; + struct comp_state decoder; + } comp; + /* modem data pump interface */ + unsigned srate; + unsigned format; + unsigned frag; + unsigned dp_requested; + unsigned automode_requested; + int update_delay; + void (*process)(struct modem *m,void *in,void *out,int cnt); + /* process counter and sample timer */ + unsigned long count; + unsigned long sample_timer; + void (*sample_timer_func)(struct modem *); + /* data pump */ + struct dp_operations **dp_ops; + struct dp *dp; + void *dp_runtime; + /* dc evaluator and cleaner */ + void *dcr; + /* dsp info data */ + struct dsp_info dsp_info; + /* voice info */ +#ifdef MODEM_CONFIG_VOICE + void *voice_obj; + struct voice_info voice_info; +#endif +#ifdef MODEM_CONFIG_FAX + void *fax_obj; +#endif +}; + + + +/* + * prototypes + * + */ + +/* device driver --> modem */ +extern struct modem *modem_create(struct modem_driver *drv, const char *dev_name); +extern void modem_delete(struct modem *m); +extern int modem_write(struct modem *m, const char *buf, int n); +extern void modem_hangup(struct modem *m); +extern void modem_update_termios(struct modem *m, struct termios *tios); +extern void modem_error (struct modem *m); +extern void modem_ring (struct modem *m); +extern void modem_event (struct modem *m); +extern void modem_process(struct modem *m,void *in,void *out,int cnt); + +/* packers && EC */ // FIXME: improve interface +extern void modem_async_start(struct modem *m); +extern int modem_async_get_bits(struct modem *m,int nbits,u8 *buf,int cnt); +extern int modem_async_put_bits(struct modem *m,int nbits,u8 *buf,int cnt); +extern void modem_detector_start(struct modem *m); +extern int modem_detector_get_bits(struct modem *m,int nbits,u8 *buf,int cnt); +extern int modem_detector_put_bits(struct modem *m,int nbits,u8 *buf,int cnt); +extern void modem_hdlc_start(struct modem *m); +extern int modem_hdlc_get_bits(struct modem *m,int nbits,u8 *buf,int cnt); +extern int modem_hdlc_put_bits(struct modem *m,int nbits,u8 *buf,int cnt); + +extern int modem_ec_init(struct modem *m); +extern void modem_ec_exit(struct modem *m); +extern void modem_ec_start(struct modem *m); +extern void modem_ec_stop(struct modem *m); + +/* status & config */ +extern void modem_update_status(struct modem *m, unsigned status); +extern void modem_update_config(struct modem *m, struct modem_config *cfg); + +/* modem parameters access macros */ +#define CRLF_CHARS(m) ((char *)((m)->sregs+SREG_CR_CHAR)) +#define MODEM_DP(m) ((m)->sregs[SREG_DP]) +#define MODEM_AUTOMODE(m) ((m)->sregs[SREG_AUTOMODE]) + +#endif /* __MODEM_H__ */ + diff --git a/slmodemd/modem_at.c b/slmodemd/modem_at.c new file mode 100644 index 0000000..a573bfc --- /dev/null +++ b/slmodemd/modem_at.c @@ -0,0 +1,1204 @@ + +/* + * + * Copyright (c) 2001, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem_at.c -- modem at command processor. + * + * Author: Sasha K (sashak@smlink.com) + * Seva (seva@smlink.com) + * + */ + +/******************************************************************** + * + * AT commands status. (p) - partiatly + * + * 1. Implemented: + * + * AT : A B C D E H I L M N O P Q S T V X Y Z + * AT&: C D E F H P R S F W + * AT\: A N + * AT%: C E + * AT+: MS FCLASS GCI GMI GMM GMR + * AT#: CID + * + ******************************************************************** + * + * 2. Not implemented yet: + * + * AT+: DSC DS DS44 DR + * FAE FTS FRS FTM FRM FRH FTH + * AT&: A K V Z + * AT\: B K + * AT*: B + * AT#: BDR RG TL CLS SPK UD + * VBS VBT VIP VIT VLS VRA VRN + * VRX VSD VSP VSR VSS VTD VTM + * VTS VGT VTX + * + *****************************************************************************/ + +#include +#include +#include +#include + +#include +#include + +#define AT_DBG(fmt...) // dprintf("at: " fmt) + + +/* ------------------------------------------------------------ */ +/* prototypes from modem.c */ +extern const char modem_author[]; +extern const char modem_name[]; +extern const char modem_version[]; +extern const char modem_date[]; + +extern struct dp_driver modem_dp_drivers[]; + +extern int modem_send_to_tty(struct modem *m, const char *buf, int n); +extern int modem_answer(struct modem *m); +extern int modem_dial(struct modem *m); +extern int modem_hook(struct modem *m,unsigned hook_state); +extern int modem_online(struct modem *m); +extern int modem_reset(struct modem *m); +extern void modem_update_speaker(struct modem *m); +extern int modem_homolog_init(struct modem *m, int id, const char *name); +extern int modem_set_mode(struct modem *m, enum MODEM_MODE mode); + +/* ------------------------------------------------------------ */ +/* + * local util functions + */ + +/* simple toupper + strncmp */ +static int toupper_strncmp(char *s1, char *s2, int n) +{ + int i; + for(i = 0 ; i < n ; i++) + if(toupper(s1[i]) != s2[i]) + return s1[i] - s2[i]; + return 0; +} + + +static int set_sreg(struct modem *m, int num, char c, int low, int hi, int *len) +{ + if (!isdigit(c)) { + *len = 0; + c = '0'; + } + else + *len = 1; + if ( c >= low + '0' && c <= hi + '0' ) + return modem_set_sreg(m,num,c - '0'); + return -1; +} + +/* ------------------------------------------------------------ */ + + +static int process_A(struct modem *m, char *p, int *len) +{ + int ret; + AT_DBG("AT A command...\n"); + ret = modem_answer(m); + if (ret) + return -1; + return 1; +} + +static int process_B(struct modem *m, char *p, int *len) +{ + AT_DBG("AT B command...\n"); + MODEM_DP(m) = DP_V22; + MODEM_AUTOMODE(m) = 0; + m->min_rate = 1200; + m->max_rate = 1200; + return 0; +} + +static int process_D(struct modem *m, char *p, int *len) +{ + int ret; + AT_DBG("AT D command...\n"); + switch (toupper(*p)) { + case 'T': + modem_set_sreg(m,SREG_TONE_OR_PULSE,1); + break; + case 'P': +#ifdef NO_PULSE_DIAL + return -1; +#endif + modem_set_sreg(m,SREG_TONE_OR_PULSE,0); + break; + case 'L': + if(m->dial_string) { + modem_send_to_tty(m,"Dialing ",8); + modem_send_to_tty(m,m->dial_string, + strlen(m->dial_string)); + modem_send_to_tty(m,"...",3); + modem_send_to_tty(m,CRLF_CHARS(m),2); + } + p = 0; + break; + default: + break; + } + if (p) + strncpy(m->dial_string,p,sizeof(m->dial_string)); + ret = modem_dial(m); + if (ret) + return -1; + return 1; +} + +static int process_H(struct modem *m, char *p, int *len) +{ + int ret; + AT_DBG("AT H command...\n"); + switch(*p) { + case '1': + *len = 1; + ret = modem_hook(m, MODEM_HOOK_OFF); + break; + case '0': + *len = 1; + p++; + default: + if (isdigit(*p)) + return -1; + ret = modem_hook(m, MODEM_HOOK_ON); + break; + } + return ret ? -1 : 0; +} + +static int process_I(struct modem *m, char *p, int *len) +{ + const char *s; + int c,i; + char *end; + AT_DBG("AT I command...\n"); + c = strtoul (p,&end,0); + *len = end - p; + switch(c) { + case 1: + case 2: + modem_send_to_tty(m,modem_name,strlen(modem_name)); + modem_send_to_tty(m,", ",2); + modem_send_to_tty(m,modem_version,strlen(modem_version)); + modem_send_to_tty(m,CRLF_CHARS(m),2); + modem_send_to_tty(m,modem_author,strlen(modem_author)); + modem_send_to_tty(m,CRLF_CHARS(m),2); + break; +#if 0 + case 2: + s = "Modem Manufacturer: unknown (TBD)"; + modem_send_to_tty(m,s,strlen(s)); + modem_send_to_tty(m,CRLF_CHARS(m),2); + s = "Modem Provider: unknown (TBD)"; + modem_send_to_tty(m,s,strlen(s)); + modem_send_to_tty(m,CRLF_CHARS(m),2); + break; +#endif + case 3: + s = m->dev_name ? m->dev_name : "unknown"; + modem_send_to_tty(m, s, strlen(s)); + modem_send_to_tty(m, CRLF_CHARS(m),2); + s = m->driver.name ? m->driver.name : "unknown"; + modem_send_to_tty(m, s, strlen(s)); + modem_send_to_tty(m, CRLF_CHARS(m),2); + break; + case 4: + for (i=0;i<24;i++) { + char str[24]; + snprintf(str,sizeof(str),"s%.2d=%.3d ",i,m->sregs[i]); + modem_send_to_tty(m,str,strlen(str)); + if (!((i+1)%8)) + modem_send_to_tty(m, CRLF_CHARS(m),2); + } + modem_send_to_tty(m,CRLF_CHARS(m),2); + break; + case 5: + modem_send_to_tty(m,"Stored Profile 0:",17); + modem_send_to_tty(m,CRLF_CHARS(m),2); +#if 0 + s = load_profile(m,0); + if (s!=NULL) + ret = print_sregs(m,s); +#endif + break; + case 6: + modem_send_to_tty(m, "Stored Profile 1:",17); + modem_send_to_tty(m, CRLF_CHARS(m),2); +#if 0 + s = load_profile(m,1); + if (s!=NULL) + ret = print_sregs (m,s); +#endif + break; + case 7: + s = m->homolog->name; + modem_send_to_tty(m,"Country: ",9); + modem_send_to_tty(m,s,strlen(s)); + modem_send_to_tty(m, CRLF_CHARS(m),2); + break; + case 0: + modem_send_to_tty(m,modem_name,strlen(modem_name)); + modem_send_to_tty(m,CRLF_CHARS(m),2); + break; + default: + return -1; + } + return 0; +} + +static int process_O(struct modem *m, char *p, int *len) +{ + int ret; + AT_DBG("AT O command...\n"); + ret = modem_online(m); + if (ret) + return -1; + return 1; +} + +static int process_S(struct modem *m, char *p, int *len) +{ + unsigned n = 0; + int val; + char *end; + AT_DBG("AT S command...\n"); + n = strtoul(p,&end,0); + *len = end - p + 1; + p = end; + if ( n >= sizeof(m->sregs)/sizeof(m->sregs[0]) ) + return -1; + switch(*p++) { + case '?': + val = modem_get_sreg(m,n); + if (val < 0) + return -1; + else { + char strval[16]; + int l = snprintf(strval,sizeof(strval),"%d",val); + modem_send_to_tty(m, strval,l); + modem_send_to_tty(m, CRLF_CHARS(m),2); + } + return 0; + case '=': + val = strtoul(p, &end, 0); + *len += end - p; + return modem_set_sreg(m,n,val); + break; + default: + return -1; + } + return 0; +} + +static int process_Z(struct modem *m, char *p, int *len) +{ + AT_DBG("AT Z command...\n"); +#if 1 + switch(*p) { + case '1': + case '2': + case '3': + case '0': + *len = 1; + break; + default: + *len = 0; + break; + } + modem_reset(m); + return 0; +#else + char *s; + int set_num; + set_num = strtoul (p,&s,0); + *len = s-p; + if (set_num < 0 || set_num > 4 ) + return -1; + + if (set_num == 0) { /* ATZ0 - load value defined by ATYn */ + set_num = m->sregs[SREG_DEFAULT_SETTING]; + } + else { + set_num--; + } + + AT_DBG("AT Z command - going to load set %d\n",set_num); + s = load_profile (m,set_num); + AT_DBG("AT Z command - done\n"); + if (s != NULL) { + /* FIXME: modem reset must be done instead */ + /* ... */ + memcpy (m->sregs,s,sizeof (m->sregs)); + return 0; + } + return -1; +#endif +} + + +/* + * AT+ commands + */ + +static int process_plus_GCI(struct modem *m, char *p, int *len) +{ + static const char gci_string[] = "+GCI:"; + char strval[8]; + const struct homolog_set *h; + char *end; + unsigned long n; + AT_DBG ("AT+GCI...\n"); + switch (*p) { + case '=': + p++; + *len = 1; + if (*p == '?') { /* show all country codes */ + *len += 1; + modem_send_to_tty(m,gci_string,strlen(gci_string)); + modem_send_to_tty(m,"(",1); + for(h=homolog_set;h->name;h++) { + n = sprintf(strval,"%x,",h->id); + modem_send_to_tty(m,strval,n); + } + modem_send_to_tty(m,")",1); + modem_send_to_tty(m, CRLF_CHARS(m),2); + } + else { + n = strtoul (p,&end,16); + if(end == p) { + return -1; + } + *len += end - p; p = end; + /* set country n */ + if(modem_homolog_init(m,n,NULL)) + return -1; + } + break; + case '?': + n = sprintf(strval,"%x",m->homolog->id); + modem_send_to_tty(m, "+GCI:",5); + modem_send_to_tty(m, strval, n); + modem_send_to_tty(m, CRLF_CHARS(m), 2); + *len = 1; + break; + default: + *len = 0; + return -1; + } + return 0; +} + + +static int process_plus_MS(struct modem *m, char *p, int *len) +{ + char strval[32]; + struct dp_driver *drv; + char *end; + unsigned long n; + unsigned int dp_id; + int auto_mode,min_rate,max_rate; + int is_found=0; + + AT_DBG ("AT+MS...\n"); + switch (*p) { + case '=': + p++; + *len = 1; + if (*p == '?') { + *len += 1; + modem_send_to_tty(m,"(",1); + for(drv = modem_dp_drivers ; drv->id ; drv++ ) { + if(!drv->code || !drv->op) continue; + if(is_found++>0) modem_send_to_tty(m,",",1); + sprintf(strval,"%d",drv->id); + modem_send_to_tty(m,strval,strlen(strval)); + } + modem_send_to_tty(m,"),(0,1),",1+7); + sprintf(strval,"(%u-%u),",MODEM_MIN_RATE,MODEM_MAX_RATE); + modem_send_to_tty(m,strval,strlen(strval)); + modem_send_to_tty(m,strval,strlen(strval)-1); + modem_send_to_tty(m, CRLF_CHARS(m),2); + break; + } + +#define PARSE_MS_ITEM(p,len,item) { \ + n = strtoul (p,&end,0); \ + if (end != p) { item = n; } \ + *len += end - p; p = end; \ + if (*p != ',') goto setup_ms; \ + *len += 1; p++; \ + } + + dp_id = MODEM_DP(m); + auto_mode= MODEM_AUTOMODE(m); + min_rate = m->min_rate; + max_rate = m->max_rate; + + PARSE_MS_ITEM(p,len,dp_id); + PARSE_MS_ITEM(p,len,auto_mode); + PARSE_MS_ITEM(p,len,min_rate); + PARSE_MS_ITEM(p,len,max_rate); + setup_ms: + if(dp_id != MODEM_DP(m)) { + for(drv = modem_dp_drivers ; drv->id ; drv++ ) { + if(drv->op && drv->code && drv->id == dp_id) { + is_found++; + break; + } + } + if(!is_found) return -1; + } + if((auto_mode != 0 && auto_mode != 1) || min_rate > max_rate || + min_rate < MODEM_MIN_RATE || max_rate > MODEM_MAX_RATE ) + return -1; + MODEM_DP(m) = dp_id; + MODEM_AUTOMODE(m) = auto_mode; + m->min_rate = min_rate; + m->max_rate = max_rate; + break; + case '?': + n = sprintf(strval,"%d,%d,%u,%u",MODEM_DP(m),MODEM_AUTOMODE(m), + m->min_rate,m->max_rate); + modem_send_to_tty(m, strval, n); + modem_send_to_tty(m, CRLF_CHARS(m), 2); + *len = 1; + break; + default: + *len = 0; + return -1; + } + return 0; +} + + +static int process_plus_FCLASS(struct modem *m, char *p, int *len) +{ + char ch; + if(*p == '=' ) { + p++; + *len += 2; + if(*p == '?') { + modem_send_to_tty(m, "0" , 1); +#ifdef MODEM_CONFIG_FAX_CLASS1 + modem_send_to_tty(m, ",1" , 2); +#endif +#ifdef MODEM_CONFIG_VOICE + modem_send_to_tty(m, ",8" , 2); +#endif + modem_send_to_tty(m, CRLF_CHARS(m), 2); + } + else if (isdigit(*p)) { + int val = *p - '0'; + if ( val != 0 +#ifdef MODEM_CONFIG_FAX_CLASS1 + && val != 1 +#endif +#ifdef MODEM_CONFIG_VOICE + && val != 8 +#endif + ) + return -1; + return modem_set_mode(m, val); + } + else + return -1; + } + else if (*p == '?') { + *len += 1; + ch = '0' + m->mode; + modem_send_to_tty(m, &ch , 1); + modem_send_to_tty(m, CRLF_CHARS(m), 2); + } + else + return -1; + return 0; +} + +/* + * Caller ID + */ + +#ifdef MODEM_CONFIG_CID +static int process_CID(struct modem *m, char *p, int *len) +{ + char ch; + if(*p == '=' ) { + p++; + *len += 2; + if(*p == '?') { + modem_send_to_tty(m, "0,1,2" , 5); + modem_send_to_tty(m, CRLF_CHARS(m), 2); + } + else if (isdigit(*p) && *p - '0' < 3) { + m->cid_requested = *p - '0'; + } + else + return -1; + } + else if (*p == '?') { + *len += 1; + ch = '0' + m->cid_requested; + modem_send_to_tty(m, &ch , 1); + modem_send_to_tty(m, CRLF_CHARS(m), 2); + } + else + return -1; + return 0; +} +#endif + + +/* + * Voice commands + */ + +#ifdef MODEM_CONFIG_VOICE + +extern int modem_voice_set_device(struct modem *m, unsigned device); +extern int modem_voice_command(struct modem *m, enum VOICE_CMD cmd); +extern int modem_voice_init(struct modem *m); + + + +struct voice_param { + unsigned *val; + unsigned min, max; +}; + +static int set_voice_params(struct modem *m, char *p, const char *cmd, + struct voice_param *param, int *len, + const char *prefix, const char *suffix) +{ + char strval[32]; + unsigned val[3]; + struct voice_param *prm; + int i; + char *end; + + *len += 1; + if( *p == '=' ) { + p++; + if(*p == '?') { + *len += 1; + sprintf(strval, "+%s=", cmd); + modem_send_to_tty(m, strval, strlen(strval)); + if(prefix) + modem_send_to_tty(m, prefix, strlen(prefix)); + prm = param; + while(prm->val) { + sprintf(strval, "%d-%d", prm->min, prm->max); + modem_send_to_tty(m, strval, strlen(strval)); + prm++; + if(prm->val) + modem_send_to_tty(m, ",", 1); + } + if(suffix) + modem_send_to_tty(m, suffix, strlen(suffix)); + modem_send_to_tty(m, CRLF_CHARS(m), 2); + return 0; + } + + if(prefix) { + if(strncmp(p,prefix,strlen(prefix))) + return -1; + p += strlen(prefix); + *len += strlen(prefix); + } + + prm = param; + for (i = 0; prm->val && i < sizeof(val)/sizeof(val[0]) ; i++ ) { + val[i] = strtoul(p,&end,0); + if( (prm->min && val[i] < prm->min) || + (prm->max && val[i] > prm->max) ) + return -1; + *len += end - p; + p = end; + prm++; + if(prm->val) { + if(*p != ',') + return -1; + *len += 1; + p++; + } + } + + if(suffix) { + if(strncmp(p,suffix,strlen(suffix))) + return -1; + *len += strlen(suffix); + } + + prm = param; + for (i = 0; prm->val && i < sizeof(val)/sizeof(val[0]) ; i++ ) { + *prm->val = val[i]; + prm++; + } + return 0; + } + else if ( *p == '?' ) { + sprintf(strval, "+%s=", cmd); + modem_send_to_tty(m, strval, strlen(strval)); + if(prefix) + modem_send_to_tty(m, prefix, strlen(prefix)); + prm = param; + while(prm->val) { + sprintf(strval, "%d", *prm->val); + modem_send_to_tty(m, strval, strlen(strval)); + prm++; + if(prm->val) + modem_send_to_tty(m, ",", 1); + } + if(suffix) + modem_send_to_tty(m, suffix, strlen(suffix)); + modem_send_to_tty(m, CRLF_CHARS(m), 2); + return 0; + } + else + return -1; +} + + + +static int process_voice_command(struct modem *m, char *p, int *len) +{ + AT_DBG("voice cmd: %s\n", p); + *len += 2; + /* AT+VIP */ + if(!toupper_strncmp(p,"IP",2)) { + return modem_voice_init(m); + } + /* AT+VNH=0,1 */ + else if(!toupper_strncmp(p,"NH",2)) { + unsigned val = 0; + struct voice_param params[] = { + {&val,0,1}, {} }; + return set_voice_params(m,p+2,"VNH",params,len,NULL,NULL); + } + /* AT+VGT=127 */ + else if(!toupper_strncmp(p,"GT",2)) { + struct voice_param params[] = { + {&m->voice_info.tx_gain,0,128}, {} }; + return set_voice_params(m,p+2,"VGT",params,len,NULL,NULL); + } + /* AT+VGR=127 */ + else if(!toupper_strncmp(p,"GR",2)) { + struct voice_param params[] = { + {&m->voice_info.rx_gain,0,128}, {} }; + return set_voice_params(m,p+2,"VGR",params,len,NULL,NULL); + } + /* AT+VIT= */ + else if(!toupper_strncmp(p,"IT",2)) { + struct voice_param params[] = { + {&m->voice_info.inactivity_timer,0,255}, {} }; + return set_voice_params(m,p+2,"VIT",params,len,NULL,NULL); + } + /* AT+VSD=128,50 */ + else if(!toupper_strncmp(p,"SD",2)) { + struct voice_param params[] = { + {&m->voice_info.silence_detect_sensitivity,0,255}, + {&m->voice_info.silence_detect_period,0,255}, + {} + }; + return set_voice_params(m,p+2,"VSD",params,len,NULL,NULL); + } + /* AT+VSM=1,8000 */ + else if(!toupper_strncmp(p,"SM",2)) { + struct voice_param params[] = { + {&m->voice_info.comp_method,0,1}, + {&m->voice_info.sample_rate,8000,8000}, + {} + }; + return set_voice_params(m,p+2,"VSM",params,len,NULL,NULL); + } + /* AT+VLS=1 */ + else if(!toupper_strncmp(p,"LS",2)) { + unsigned dev = (m->voice_obj != NULL); + struct voice_param params[] = { + {&dev,0,1}, {} }; + int ret = set_voice_params(m,p+2,"VLS",params,len,NULL,NULL); + if(ret) + return ret; + return modem_voice_set_device(m, dev); + } + /* AT +VRX, +VTX, +VTR */ + else if(!toupper_strncmp(p,"TX",2)) + return modem_voice_command(m,VOICE_CMD_STATE_TX); + else if(!toupper_strncmp(p,"RX",2)) + return modem_voice_command(m,VOICE_CMD_STATE_RX); + else if(!toupper_strncmp(p,"TR",2)) + return modem_voice_command(m,VOICE_CMD_STATE_DUPLEX); + /* AT+VTS=[933,,150] */ + else if(!toupper_strncmp(p,"TS",2)) { + unsigned orig_len; + int ret; + p += 2; + orig_len = *len; + { + struct voice_param params[] = { + {&m->voice_info.tone1_freq,0,0}, + {&m->voice_info.tone2_freq,0,0}, + {&m->voice_info.tone_duration,0,6000}, + {} }; + if(*p == '?' || (*p == '=' && *(p+1) == '?' )) + return set_voice_params(m,p,"VTS",params,len,NULL,NULL); + + ret = set_voice_params(m,p,"VTS",params,len,"[","]"); + if(!ret) + return modem_voice_command(m, VOICE_CMD_BEEP); + } + { + struct voice_param params[] = { + {&m->voice_info.dtmf_symbol,0,0}, + {&m->voice_info.tone_duration,0,100}, + {} }; + *len = orig_len; + ret = set_voice_params(m,p,"VTS",params,len,"{","}"); + if(!ret) + return modem_voice_command(m, VOICE_CMD_DTMF); + } + { + struct voice_param params[] = { + {&m->voice_info.dtmf_symbol,0,0}, {} }; + *len = orig_len; + ret = set_voice_params(m,p,"VTS",params,len,NULL,NULL); + if(!ret) + return modem_voice_command(m, VOICE_CMD_DTMF); + } + return -1; + } + else + return -1; +} +#else +#define process_voice_command(m,p,plen) (-1) +#endif /* MODEM_CONFIG_VOICE */ + + +/* + * Fax commands + */ + +#ifdef MODEM_CONFIG_FAX +extern int FAX_class1_command(void *obj, unsigned cmd, unsigned param); + + +static int process_fax_command(struct modem *m, char *p, int *len) +{ + unsigned val; char *end; + AT_DBG("fax cmd: %s\n", p); + *len += 2; + /* +FTS= */ + if(!toupper_strncmp(p,"TS=",3)) { + *len += 1; + p += 3; + val = strtoul(p,&end,0); + if(p == end) + return -1; + *len += end - p; + p = end; + return FAX_class1_command(m->fax_obj, FAX_CMD_FTS, val); + } + /* +FRS= */ + else if(!toupper_strncmp(p,"RS=",3)) { // FIXME: abort on tty input + *len += 1; + p += 3; + val = strtoul(p,&end,0); + if(p == end) + return -1; + *len += end - p; + p = end; + return FAX_class1_command(m->fax_obj, FAX_CMD_FRS, val); + } + /* +FTM= */ + else if(!toupper_strncmp(p,"TM=",3)) { + *len += 2; + p+= 3; + if(*p == '?') { + modem_send_to_tty(m,"24,48,72,73,74,96,97,98,121,122,145,146",39); + modem_send_to_tty(m, CRLF_CHARS(m), 2); + return 0; + } + else { + val = strtoul(p,&end,0); + if(p == end) + return -1; + *len += end - p - 1; + p = end; + return FAX_class1_command(m->fax_obj, FAX_CMD_FTM, val); + } + } + /* +FRM= */ + else if(!toupper_strncmp(p,"RM=",3)) { + *len += 2; + p+= 3; + if(*p == '?') { + modem_send_to_tty(m,"24,48,72,73,74,96,97,98,121,122,145,146",39); + modem_send_to_tty(m, CRLF_CHARS(m), 2); + } + else { + val = strtoul(p,&end,0); + if(p == end) + return -1; + *len += end - p - 1; + p = end; + return FAX_class1_command(m->fax_obj, FAX_CMD_FRM, val); + } + return 0; + } + /* +FRH= */ + else if(!toupper_strncmp(p,"RH=",3)) { + *len += 2; + p+= 3; + if(*p == '?') { + modem_send_to_tty(m,"3",1); + modem_send_to_tty(m, CRLF_CHARS(m), 2); + return 0; + } + else if (isdigit(*p)) + return FAX_class1_command(m->fax_obj, FAX_CMD_FRH, *p - '0'); + return -1; + } + /* +FTH= */ + else if(!toupper_strncmp(p,"TH=",3)) { + *len += 2; + p+= 3; + if(*p == '?') { + modem_send_to_tty(m,"3",1); + modem_send_to_tty(m, CRLF_CHARS(m), 2); + return 0; + } + else if (isdigit(*p)) + return FAX_class1_command(m->fax_obj, FAX_CMD_FTH, *p - '0'); + return -1; + } + else + return -1; +} +#else +#define process_fax_command(m,p,plen) (-1) +#endif /* MODEM_CONFIG_FAX */ + + +/* ------------------------------------------------------------ */ + +/* + * Main AT processor + * + */ + +int process_at_command(struct modem *m, char *cmd) +{ + char c, *p = cmd; + int len = 0, ret = -1; + + /* verify 'AT' */ + if (toupper(*p++) != 'A' || toupper(*p++) != 'T') + return -1; + + while(*p) { + c = toupper(*p++); + len = 0; + switch(c) { + + case 'A': /* ATA */ + ret = process_A(m,p,&len); + return ret; + case 'B': /* ATB */ + ret = process_B(m,p,&len); + break; + case 'D': /* ATD */ + ret = process_D(m,p,&len); + return ret; + case 'E': /* ATE */ + ret = set_sreg(m,SREG_ECHO,*p,0,1,&len); + break; + case 'H': /* ATH */ + ret = process_H(m,p,&len); + break; + case 'I': /* ATI */ + ret = process_I(m,p,&len); + break; + case 'L': /* ATL */ + ret = set_sreg(m,SREG_SPEAKER_VOLUME,*p,0,3,&len); + if(!ret) modem_update_speaker(m); + break; + case 'M': /* ATM */ + ret = set_sreg(m,SREG_SPEAKER_CONTROL,*p,0,2,&len); + if(!ret) modem_update_speaker(m); + break; + case 'N': /* ATN */ + ret = set_sreg(m,SREG_AUTOMODE,*p,0,1,&len); + break; + case 'O': /* ATO */ + ret = process_O(m,p,&len); + break; + case 'P': /* ATP */ +#ifdef NO_PULSE_DIAL + return -1; +#endif + ret = modem_set_sreg(m,SREG_TONE_OR_PULSE,0); + break; + case 'Q': /* ATQ */ + ret = set_sreg(m,SREG_QUIET,*p,0,1,&len); + break; + case 'S': /* ATS */ + ret = process_S(m,p,&len); + break; + case 'T': /* ATT */ + ret = modem_set_sreg(m,SREG_TONE_OR_PULSE,1); + break; + case 'V': /* ATV */ + ret = set_sreg(m,SREG_VERBOSE,*p,0,1,&len); + break; + case 'X': /* ATX */ + ret = set_sreg(m,SREG_X_CODE,*p,0,4,&len); + break; + case 'Y': /* ATY */ + ret = set_sreg(m,SREG_DEFAULT_SETTING,*p,0,3,&len); + break; + case 'Z': /* ATZ */ + ret = process_Z(m,p,&len); + return ret; + + case '#': /* AT# */ +#ifdef MODEM_CONFIG_CID + if(!toupper_strncmp(p,"CID",3)) { + p+= 3; + ret = process_CID(m, p, &len); + } + else +#endif + ret = -1; + break; + case '%': /* AT% */ + c = toupper(*p++); + switch (c) { + case 'C': /* AT%C */ + ret = set_sreg(m,SREG_COMP,*p,0,3,&len); + break; + case 'E': /* AT%E */ + ret = set_sreg(m,SREG_LINE_QUALITY_CONTROL,*p,0,2,&len); + break; + default: + return -1; + } /* end AT% */ + break; + case '&': + c = toupper(*p++); + switch (c) { + case 'A': /* AT&A */ + ret = set_sreg(m,SREG_CONNNECT_MSG_FORMAT,*p,0,7,&len); + break; + case 'C': /* AT&C */ + ret = set_sreg(m,SREG_CD,*p,0,1,&len); + break; + case 'D': /* AT&D */ + case 'R': /* AT&R */ + case 'S': /* AT&S */ + len = isdigit(*p)?1:0; ret = 0; + break; + case 'E': /* AT&E */ + ret = set_sreg(m,SREG_CONNNECT_MSG_SPEED_SRC,*p,0,1,&len); + break; + case 'F': /* AT&F */ + len = isdigit(*p)?1:0; ret = 0; + break; + case 'H': /* AT&H */ + ret = set_sreg(m,SREG_FLOW_CONTROL,*p,0,1,&len); + break; + case 'K': /* AT&K */ + ret = set_sreg(m,SREG_COMP,*p,0,3,&len); + break; + case 'P': /* AT&P */ + ret = set_sreg(m,SREG_PULSE_RATIO,*p,0,3,&len); + break; + case 'V': /* AT&V */ + case 'W': /* AT&W */ + ret = -1; + break; +#if 0 + case 'Z': /* AT&Z */ + c = toupper(*p++); + if (c == 'L'){ + ret = print_last_dial_string (m); + break; /* ZL */ + } + break; /* Z */ +#endif + default: + return -1; + } + break; + case '*': /* AT* */ + c = toupper(*p++); + switch(c) { + case 'B': /* AT*B */ + break; + default: + return -1; + } + break; + case '+': + c = toupper(*p++); + switch (c) { +#if 0 + case 'D': /* AT+D */ + c = toupper(*p++); + switch (c) { + case 'C': /* AT+DC */ + break; + case 'S': /* AT+DS */ + break; + case 'R': /* AT+DR */ + break; + default: + return -1; + } + break; +#endif + case 'G': /* AT+G - generic DCE cntrl */ + c = toupper(*p++); + switch (c) { + case 'C': /* AT+GCI[=|?|=?] */ + if (toupper(*p++) == 'I') + ret = process_plus_GCI(m,p,&len); + else + return -1; + break; + case 'M': /* AT+GM[I|M|R] */ + c = toupper(*p++); + switch (c) { + case 'I': /* AT+GMI */ + modem_send_to_tty(m,modem_author,strlen(modem_author)); + modem_send_to_tty(m,CRLF_CHARS(m),2); + break; + case 'M': /* AT+GMM */ + modem_send_to_tty(m,modem_name,strlen(modem_name)); + modem_send_to_tty(m,CRLF_CHARS(m),2); + break; + case 'R': /* AT+GMR */ + modem_send_to_tty(m,modem_version,strlen(modem_version)); + modem_send_to_tty(m,CRLF_CHARS(m),2); + break; + default: + return -1; + } + ret = 0; + break; + default: + return -1; + } + break; + case 'F': /* AT+F */ + if(!toupper_strncmp(p,"CLASS",5)) { + p+= 5; + ret = process_plus_FCLASS(m, p, &len); + } + else + ret = process_fax_command(m, p, &len); + break; +#ifdef MODEM_CONFIG_VOICE + /* AT+IFC=2,2 */ /* TBD: flow control - not voice command */ + case 'I': + // FIXME + if(!toupper_strncmp(p,"FC=2,2",6)) { + p+= 6; + ret = 0; + } + else + ret = -1; + break; +#endif + case 'M': /* AT+M */ + c = toupper (*p++); + if (c == 'S') + ret = process_plus_MS(m,p,&len); + break; + case 'V': + if(m->mode != MODEM_MODE_VOICE) + return -1; +#ifdef MODEM_CONFIG_CID + if(!toupper_strncmp(p,"CID",3)) { + p+= 3; + ret = process_CID(m, p, &len); + } + else +#endif + ret = process_voice_command(m, p, &len); + break; + default: + return -1; + } + break; + case '\\': + c = toupper(*p++); + switch (c) { + case 'A': /* AT\A */ + if(isdigit(*p)) len++; + // ret = set_sreg(m,SREG_V42_BASEREG,*p,0,5,&len); + break; +#if 0 + case 'B': /* AT\B */ + break; + case 'K': /* AT\K */ + break; +#endif + case 'N': /* AT\N */ + ret = set_sreg(m,SREG_EC,*p,0,5,&len); + break; + default: + return -1; + } + break; + default: + AT_DBG("unknown command `%c` (%x).\n",c,c); + return -1; + } + if (ret) return ret; + p += len; + } + return 0; +} + diff --git a/slmodemd/modem_cmdline.c b/slmodemd/modem_cmdline.c new file mode 100644 index 0000000..9f80619 --- /dev/null +++ b/slmodemd/modem_cmdline.c @@ -0,0 +1,296 @@ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * Copyright (c) 2021, Aon plc + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem_cmdline.c -- simple command line processor, + * define config parameters. + * + * Author: Sasha K (sashak@smlink.com) + * + * + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#define PR_INFO(fmt...) fprintf(stderr, fmt ) + + +/* global config data */ + +/* modem.c */ +extern const char *modem_default_country; + +/* modem_debug.c */ +extern unsigned int modem_debug_level; +extern unsigned int modem_debug_logging; + +/* config parameters */ +const char *modem_dev_name = NULL; +const char *modem_default_dev_name = "/dev/slamr0"; +const char *modem_alsa_dev_name = "modem:1"; +const char *modem_exec = NULL; +unsigned int need_realtime = 1; +#ifdef MODEM_CONFIG_RING_DETECTOR +unsigned int ring_detector = 0; +#endif +unsigned int use_alsa = 0; +const char *modem_group = "dialout"; +unsigned int use_short_buffer = 0; +mode_t modem_perm = 0660; + + +enum { + OPT_HELP = 0, + OPT_USAGE, + OPT_VERSION, + OPT_COUNTRY, + OPT_COUNTRYLIST, + OPT_ALSA, + OPT_GROUP, + OPT_PERM, +#ifdef MODEM_CONFIG_RING_DETECTOR + OPT_RINGDET, +#endif + OPT_USER, + OPT_SHORTBUF, + OPT_DEBUG, + OPT_LOG, + OPT_EXEC, + OPT_LAST +}; + +static struct opt { + int ch; + const char *name; + const char *desc; + enum {NONE=0,MANDATORY,OPTIONAL} arg; + enum {INTEGER,STRING} arg_type; + const char *arg_val; + unsigned found; +} opt_list[] = { + {'h',"help","this usage"}, + {'u',"usage","this usage"}, + {'v',"version","show version and exit"}, + {'c',"country","default modem country name",MANDATORY,STRING,"USA"}, + { 0 ,"countrylist","show list of supported countries"}, + {'a',"alsa","ALSA mode (see README for howto)"}, + {'g',"group","Modem TTY group",MANDATORY,STRING,"dialout"}, + {'p',"perm","Modem TTY permission",MANDATORY,INTEGER,"0660"}, +#ifdef MODEM_CONFIG_RING_DETECTOR + {'r',"ringdetector","with internal ring detector (software)"}, +#endif + {'n',"nortpriority","run with regular priority"}, + {'s',"shortbuffer","use short buffer (4 periods length)"}, + {'d',"debug","debug level (developers only, for ./sl...)",OPTIONAL,INTEGER,"0"}, + {'l',"log","logging mode",OPTIONAL,INTEGER,"5"}, + {'e',"exec","path to external application that transmits audio over the socket (required)"}, + {} +}; + + + +static void usage(const char *prog_name) +{ + struct opt *opt; + PR_INFO("Usage: %s [option...] \n" + "Where 'device' is name of modem device (default `%s')\n" + " and 'option' may be:\n", prog_name, modem_default_dev_name); + for (opt = opt_list ; opt->name ; opt++ ) { + int n = 0; + if(opt->ch) + n = PR_INFO(" -%c, ",opt->ch); + else + n = PR_INFO(" "); + n += PR_INFO("--%s%s ",opt->name,opt->arg?"=VAL":""); + n += PR_INFO("%*s%s",24-n,"",opt->desc); + if(opt->arg) { + n+= PR_INFO(" (default `%s')",opt->arg_val); + } + PR_INFO("\n"); + } + exit(1); +} + + +static void opt_parse(int argc, char *argv[]) +{ + const char *prog_name; + const char *dev_name = NULL; + struct opt *opt; + char *p, *arg; + int found, i; + + prog_name = argv[0]; + + for( i = 1 ; i < argc ; i++ ) { + p = argv[i]; + if(*p != '-') { + if(dev_name) + usage(prog_name); + dev_name = p; + continue; + } + found = 0; + arg = NULL; + do { p++; } while( *p == '-' ); + for (opt = opt_list ; opt->name ; opt++ ) { + if(!strncmp(p,opt->name,strlen(opt->name)) || + (opt->ch && *p == opt->ch) ) { + char *q; + if(!strncmp(p,opt->name,strlen(opt->name))) + q = p + strlen(opt->name); + else + q = p + 1; + if( *q == '\0' ) + found = 1; + else if (*q == '=' && opt->arg ) { + arg = q + 1; + found = 1; + } + else if(isdigit(*q) && opt->arg ) { + arg = q; + found = 1; + } + } + + if ( !found ) + continue; + if ( arg && !opt->arg ) + usage(prog_name); + + if (!arg && opt->arg && + (i < argc - 1 && *argv[i+1] != '-') && + (!opt->arg_type == INTEGER || isdigit(*argv[i+1]))) + arg = argv[++i]; + + if(!arg && opt->arg == MANDATORY) + usage(prog_name); + + opt->found++; + if(opt->arg && arg) + opt->arg_val = arg; + break; + } + if(!found) + usage(prog_name); + } + + if(dev_name) + modem_dev_name = dev_name; +} + + + +void modem_cmdline(int argc, char *argv[]) +{ + const char *prog_name = argv[0]; + int val; + + opt_parse(argc,argv); + + if(opt_list[OPT_HELP].found || + opt_list[OPT_USAGE].found ) + usage(prog_name); + + if(opt_list[OPT_VERSION].found) { + extern void modem_print_version(); + modem_print_version(); + exit(0); + } + + if(opt_list[OPT_COUNTRYLIST].found) { + const struct homolog_set *s ; + for( s = homolog_set; s->name ; s++ ) { + PR_INFO("%02x: %s\n",s->id,s->name); + } + exit(0); + } + if(opt_list[OPT_COUNTRY].found) + modem_default_country = opt_list[OPT_COUNTRY].arg_val; + if(opt_list[OPT_ALSA].found) { +#ifndef SUPPORT_ALSA + PR_INFO("ALSA support is not compiled in (see README for howto).\n"); + exit(1); +#endif + use_alsa = 1; + } + if(opt_list[OPT_GROUP].found) + modem_group = opt_list[OPT_GROUP].arg_val; + if(opt_list[OPT_PERM].found) { + val = strtol(opt_list[OPT_PERM].arg_val,NULL,8); + if (val <= 0) + usage(prog_name); + modem_perm = val; + } +#ifdef MODEM_CONFIG_RING_DETECTOR + if(opt_list[OPT_RINGDET].found) + ring_detector = 1; +#endif + if(opt_list[OPT_USER].found) + need_realtime = 0; + if(opt_list[OPT_SHORTBUF].found) + use_short_buffer = 1; + if(opt_list[OPT_DEBUG].found) { + modem_debug_level = 1 ; + if(opt_list[OPT_DEBUG].arg_val && + (val= strtol(opt_list[OPT_DEBUG].arg_val,NULL,0)) > 0 ) + modem_debug_level = val; + } + if(opt_list[OPT_LOG].found) { + modem_debug_logging = 5; + if(opt_list[OPT_LOG].arg_val && + (val= strtol(opt_list[OPT_LOG].arg_val,NULL,0)) > 0 ) + modem_debug_logging = val; + } + if(opt_list[OPT_EXEC].found) { + modem_exec = opt_list[OPT_EXEC].arg_val; + } else { + usage(prog_name); + } + if(!modem_dev_name) { + modem_dev_name = use_alsa ? modem_alsa_dev_name : modem_default_dev_name; + } +} + diff --git a/slmodemd/modem_comp.c b/slmodemd/modem_comp.c new file mode 100644 index 0000000..f8f98b1 --- /dev/null +++ b/slmodemd/modem_comp.c @@ -0,0 +1,887 @@ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem_comp.c -- modem compressor module. + * + * Author: Sasha K (sashak@smlink.com) + * + * + */ + + +#include +#include + + +/* + * TODO list: + * - modify interface: clean temporary out buffs + * - char char encoding/decoding + * - simplify and clean code: + * - decoder + * - encoder test compression case, do it after string finishing + * - preformance trace and optimize + * + */ + +//#define COMP_TEST 1 +//#define COMP_DEBUG 1 + +/* V42bis parameters limitation */ +#define MIN_DICT_SIZE 512 /* min dictionary size enabled by protocol */ +#define MIN_STR_SIZE 6 /* min string size enabled by protocol */ +#define MAX_STR_SIZE 250 /* max string size enabled by protocol */ + +/* V42bis constants */ +#define CHAR_SIZE 8 /* char size (bits) N3 */ +#define TOTAL_CHARS 256 /* number of chars N4 */ +#define TOTAL_CTRLS 3 /* number of control cw N6 */ +#define FIRST_ENTRY TOTAL_CTRLS /* first dictionary entry */ +#define FIRST_FREE TOTAL_CHARS+FIRST_ENTRY /* initial val of free entry N5 */ + +/* control codewords */ +#define CCW_ETM 0 /* Enter transparent mode */ +#define CCW_FLUSH 1 /* Flash data */ +#define CCW_STEPUP 2 /* Step up codeword size */ +/* command codes */ +#define CC_ECM 0 /* Enter compression mode */ +#define CC_EID 1 /* Escape charactrer in data */ +#define CC_RESET 2 /* Force reinitialization */ + +#define ESCAPE_STEP 51 /* escape char value step */ +#define TEST_SLICE 256 /* compression test slice (bytes) */ + + +/* fixme: use get pages */ +#define COMP_ALLOC(size) malloc(size) +#define COMP_FREE(mem) free(mem) + +/* debug stuff */ +#if COMP_DEBUG +#define INLINE_FUNC static +#define COMP_DBG(fmt,arg...) dprintf("comp %d/%d: " fmt , \ + c->cmp_bits , c->raw_bits , ##arg) +#if 1 +#define COMP_DBG1(fmt,arg...) +#else +#define COMP_DBG1(fmt,arg...) COMP_DBG(fmt , ##arg) +static char *show_string(struct comp_state *c, u16 cw) +{ + static char _str[COMP_MAX_STRING+1]; + int j; + _str[COMP_MAX_STRING] = 0; + for(j = COMP_MAX_STRING-1; cw && j >= 0 ; j--) { + _str[j] = c->dict[cw].ch; + cw = c->dict[cw].parent; + } + return _str+j+1; +} +#endif // 0 +#else /* !COMP_DEBUG */ +#define INLINE_FUNC extern inline +#define COMP_DBG(fmt,arg...) +#define COMP_DBG1(fmt,arg...) +#endif /* !COMP_DEBUG */ + +#define COMP_ERR(fmt,arg...) eprintf("err: " fmt , ##arg) + + +/* + * common procedures + * + */ + +/* initialize dictionary and params */ +static void dict_init(struct comp_state *c) +{ + int i; + for(i=0;idict_size;i++) { + c->dict[i].parent = 0; + c->dict[i].child = 0; + c->dict[i].next = 0; + } + c->next_free = FIRST_FREE; + c->last_matched = 0; + c->update_at = 0; + c->last_added = 0; + c->cw_size = CHAR_SIZE + 1; + c->threshold = TOTAL_CHARS<<1; + c->bit_len = 0; + c->flushed_len = 0; + c->str_len = 0; + c->escape_char = 0; + c->cmp_last = TEST_SLICE<<3; + c->mode = TRANSPARENT; + c->escape = 0; +} + +/* match one char */ +INLINE_FUNC u16 match_char(struct comp_state *c, u16 at, u8 ch) +{ + register u16 e; + if (!at) + return ch + FIRST_ENTRY; + e = c->dict[at].child; + while(e) { + if (c->dict[e].ch == ch) + return e; + e = c->dict[e].next; + } + return 0; +} + +/* add one char */ +INLINE_FUNC u16 add_char(struct comp_state *c, u16 at, u8 ch) +{ + register u16 new = c->next_free; + register u16 next; + /* add */ + c->dict[new].ch = ch; + c->dict[new].parent = at; + c->dict[new].child = 0; + c->dict[new].next = c->dict[at].child; + c->dict[at].child = new; + /* update next free */; + next = new; + do { + if (++next == c->dict_size) + next = FIRST_FREE; + } while(c->dict[next].child); + if (c->dict[next].parent) { + u16 e = c->dict[next].parent; + if(c->dict[e].child == next) + c->dict[e].child = c->dict[next].next; + else { + e = c->dict[e].child; + while(c->dict[e].next != next) + e = c->dict[e].next; + c->dict[e].next = c->dict[next].next; + } + } + c->next_free = next; + return new; +} + + + + +/* + * decoder + * + */ + +/* out decoded string */ +INLINE_FUNC int send_string(struct comp_state *c) +{ + int ret; +#if 0 + c->str_data[c->str_len] = 0; + COMP_DBG("out string %d: '%s'\n",c->last_matched,c->str_data); +#endif + memcpy(c->obuf+c->olen,c->str_data,c->str_len); + ret = c->str_len; + c->olen += ret; + c->str_len = 0; + c->flushed_len = 0; + return ret; +} + +/* receive encoded data */ +INLINE_FUNC int recv_data(struct comp_state *c, u16 cw) +{ + int i,ret = 0; + u16 p = cw; + COMP_DBG1("dec recv %d: '%s'\n",cw,show_string(c,cw)); + for (ret = 0 ; p ; ret++) { + p = c->dict[p].parent; + } + p = cw; + i = c->str_len + ret - 1; + while(p) { + c->str_data[i--] = c->dict[p].ch; + p = c->dict[p].parent; + } + c->str_len += ret; + return ret; +} + +/* flush decoder */ +int comp_flush_decoder(struct comp_state *c) +{ + int ret, total_len; + total_len = c->flushed_len + c->str_len; + ret = send_string(c); + c->flushed_len = total_len; + if (ret) { + COMP_DBG("flush_decoder: %d...\n", ret); + } + return ret; +} + +/* decoder */ +int comp_decode(struct comp_state *c, u8 *in, int n) +{ + register int i, ret = 0; + register u16 cw, p; + u8 ch; + for (i = 0 ; imode) { + case COMPRESSED: + /* get cw from input */ + while (c->bit_len < c->cw_size && ibit_data |= *in++ << c->bit_len; + c->bit_len += 8; + i++; + } + if (c->bit_len < c->cw_size) + break; + + cw = c->bit_data&((1<cw_size)-1); + c->bit_data >>= c->cw_size; + c->bit_len -= c->cw_size; + + /* process cw */ + switch (cw) { + /* control cw */ + case CCW_ETM: /* enter transparent mode */ + COMP_DBG("C decoder: ETM\n"); + c->bit_len = 0; + c->mode = TRANSPARENT; + c->last_matched = 0; + c->last_added = 0; + break; + case CCW_FLUSH: /* flush signal */ + COMP_DBG("C decoder: FLUSH\n"); + c->bit_len = 0; + break; + case CCW_STEPUP: /* increase cw size */ + c->cw_size++; + c->threshold <<= 1; + COMP_DBG("C decoder: STEPUP %d\n", c->cw_size); + if (c->cw_size > (c->dict_size>>3)) { /* C-ERROR */ + COMP_ERR("fatal: cw size too big!\n"); + return -1; + } + break; + default: /* regular codeword */ + if (cw == c->next_free) { /* C-ERROR */ + COMP_ERR("fatal: next free!\n"); + return -1; + } + + ret += recv_data(c,cw); + if (c->update_at) { + ch = c->str_data[0]; + p = match_char(c,c->update_at,ch); + if (!p) { + // fixme: prevent case add 303 at 303 + c->last_added = add_char(c,c->update_at,ch); + COMP_DBG1("C dec add %d at %d: %d(%c) '%s'\n", + c->last_added,c->update_at, + ch,ch,show_string(c,c->last_added)); + if (cw == c->next_free) { /* C-ERROR */ + COMP_ERR("fatal: empty cw!\n"); + return -1; + } + } + else if (p == c->last_added) + c->last_added = 0; + } + if (c->str_len + c->flushed_len == c->max_string) { + c->update_at = 0; + } + else { + c->update_at = cw; + } + /* process escape */ + // fixme: separate it in func (send_string ?) + { int j; + for (j=0;jstr_len;j++) { + if(c->str_data[j]==c->escape_char) { + COMP_DBG("C dec: ESCAPE %d\n", c->escape_char); + c->escape_char+=ESCAPE_STEP; + } + } + } + send_string(c); + break; + } + break; + case TRANSPARENT: + if (c->escape) { /* command */ + c->escape = 0; + switch(*in) { + case CC_ECM: /* enter compressed mode */ + COMP_DBG("T decoder: ECM\n"); + ret += send_string(c); + c->mode = COMPRESSED; + c->update_at = c->last_matched; + c->last_matched = 0; + in++;i++; + continue; + //break; + case CC_EID: /* escape symbol */ + COMP_DBG("T decoder: EID\n"); + // fixme: don't rewrite in buf + *in = c->escape_char; + c->escape_char += ESCAPE_STEP; + break; + case CC_RESET: /* reset dict */ + COMP_DBG("T decoder: RESET\n"); + // TBD + ret += send_string(c); + dict_init(c); + in++;i++; + continue; + //break; + default: /* C-ERROR */ + COMP_ERR("fatal: invalid cmd!\n"); + return -1; + } + } + else if (*in == c->escape_char) { + COMP_DBG("T dec ESCAPE %d\n", *in); + c->escape = 1; + in++; i++; + break; + } + + //COMP_DBG1("dec rcv: %d(%c)\n", *in, *in); + + if (c->update_at) { + if(!match_char(c,c->update_at,*in)) { + c->last_added = add_char(c,c->update_at,*in); + COMP_DBG1("T dec add %d at %d: %d(%c) '%s'\n", + c->last_added,c->update_at, + *in,*in,show_string(c,c->last_added)); + } + c->update_at = 0; + } + + cw = match_char(c,c->last_matched,*in); + if(!cw) { + c->update_at = c->last_matched; + /* out string */ + ret += send_string(c); + c->last_matched = 0; + } + else if (cw == c->last_added) { + c->last_added = 0; + /* out string */ + ret += send_string(c); + c->last_matched = 0; + } + else { + c->last_matched = cw; + c->str_data[c->str_len++] = *in++; + if (c->str_len + c->flushed_len == c->max_string) { + /* out string */ + ret += send_string(c); + c->last_matched = 0; + } + i++; + } + break; + default: + return -1; + } + } + return ret; +} + + +/* + * encoder + * + */ + +#define SEND_CW(c,cw) { (c)->bit_data |= (cw) << (c)->bit_len; \ + (c)->bit_len += (c)->cw_size; } +#define ALIGN_BITS(c) { if((c)->bit_len%8) \ + (c)->bit_len += 8 - (c)->bit_len%8; } +#define SEND_BITS(c) { while((c)->bit_len >= 8) { \ + (c)->obuf[c->olen++]=(c)->bit_data&0xff; \ + (c)->bit_data >>= 8; \ + (c)->bit_len -= 8; ret++; \ + } } + + + +/* send encoded data */ +static int send_data(struct comp_state *c, u16 cw) +{ + register int i, ret = 0; + + /* update test info */ + c->raw_bits += c->str_len<<3; + c->cmp_bits += c->cw_size; + c->cmp_last += c->cw_size - c->cmp_last*c->str_len/TEST_SLICE; + + switch(c->mode) { + case TRANSPARENT: + for (i = 0;istr_len;i++) { + c->obuf[c->olen++] = c->str_data[i]; + ret++; + if (c->str_data[i] == c->escape_char) { + COMP_DBG("T enc ESCAPE %d\n", c->escape_char); + c->obuf[c->olen++] = CC_EID; + ret++; + c->escape_char += ESCAPE_STEP; + } + COMP_DBG1("enc send: %d(%c)\n",c->str_data[i],c->str_data[i]); + } + break; + case COMPRESSED: + /* process escape */ + for (i = 0;istr_len;i++) { + if (c->str_data[i] == c->escape_char) { + COMP_DBG("C enc ESCAPE %d\n", c->escape_char); + c->escape_char += ESCAPE_STEP; + } + } + /* send codeword */ + /* check cw size and send STEPUP if need */ + while (cw >= c->threshold) { + SEND_CW(c,CCW_STEPUP); + SEND_BITS(c); + c->threshold <<= 1; + c->cw_size++; + COMP_DBG("C enc STEPUP %d\n",c->cw_size); + } + SEND_CW(c,cw); + SEND_BITS(c); + COMP_DBG1("enc send %d: '%s'\n",cw,show_string(c,cw)); + break; + } + c->str_len = 0; + c->flushed_len = 0; + return ret; +} + +/* test compression */ +static int test_mode(struct comp_state *c) +{ + int ret = 0; + switch(c->mode) { + case TRANSPARENT: + /* fixme: why 11 ? */ + if (c->cmp_last < (TEST_SLICE<<3) - 11) { + /* switch to compressed mode */ + COMP_DBG("encoder %d/%d %d: --> COMPRESSED mode.\n", + c->cmp_bits,c->raw_bits,c->cmp_last); + if (c->last_matched) { + c->update_at = c->last_matched; + ret += send_data(c,c->last_matched); + c->last_matched = 0; + } + c->obuf[c->olen++] = c->escape_char; + c->obuf[c->olen++] = CC_ECM; + ret += 2; + c->bit_data = 0; + c->mode = COMPRESSED; + } +#if 0 + else if (0) { /* fixme: when RESET? */ + COMP_DBG("encoder RESET\n"); + } +#endif + break; + case COMPRESSED: + if (c->cmp_last > (TEST_SLICE<<3)) { + /* switch to transparent mode */ + COMP_DBG("encoder %d/%d %d: --> TRANSPARENT mode.\n", + c->cmp_bits,c->raw_bits,c->cmp_last); + if (c->last_matched) { + c->update_at = c->last_matched; + ret += send_data(c,c->last_matched); + c->last_matched = 0; + } + c->last_added = 0; + SEND_CW(c,CCW_ETM); + ALIGN_BITS(c); + SEND_BITS(c); + c->mode = TRANSPARENT; + } + break; + } + return ret; +} + +/* flush encoder data */ +int comp_flush_encoder(struct comp_state *c) +{ + int ret = 0; + //COMP_DBG1("flush_encoder...\n"); +#if 1 /* fixme: use something better */ + if (c->update_at) { + return 0; + } +#endif + if (c->last_matched) { + int total_len = c->flushed_len + c->str_len; + ret = send_data(c,c->last_matched); + c->flushed_len = total_len; + } + if(c->mode == COMPRESSED) { + c->update_at = c->last_matched; + c->last_matched = 0; + c->flushed_len = 0; + //if (c->bit_len > 0) { + COMP_DBG("flush_encoder: send FLUSH\n"); + /* send FLUSH and align by zeros */ + SEND_CW(c,CCW_FLUSH); + ALIGN_BITS(c); + SEND_BITS(c); + //} + } + if (ret) + COMP_DBG("flush_encoder %d...\n", ret); + return ret; +} + + +/* encoder */ +#define NEW_ENCODER 1 +int comp_encode(struct comp_state *c, u8 *in, int n) +{ + register int i, ret=0; + register u16 cw = 0; + + for(i=0;iupdate_at) { + if (!match_char(c,c->update_at,*in)) { + c->last_added = add_char(c,c->update_at,*in); + COMP_DBG1("enc add %d at %d: %d(%c) '%s'\n", + c->last_added,c->update_at, + *in,*in,show_string(c,c->last_added)); + } + c->update_at = 0; + } +#if NEW_ENCODER + /* match string */ + while(ilast_matched,*in); + if (!cw) { + c->update_at = c->last_matched; + ret += send_data(c,c->last_matched); + c->last_matched = 0; + break; + } + if (cw == c->last_added) { + c->last_added = 0; + ret += send_data(c,c->last_matched); + c->last_matched = 0; + break; + } + c->last_matched = cw; + /* collect char */ + c->str_data[c->str_len++] = *in++; i++; + if ( c->str_len + c->flushed_len == c->max_string ) { + ret += send_data(c,c->last_matched); + c->last_matched = 0; + break; + } + } + ret += test_mode(c); + } +#else + /* match char */ + cw = match_char(c,c->last_matched,*in); + if (!cw) { + /* add char */ + c->update_at = c->last_matched; + /* send and reset string */ + ret += send_data(c,c->last_matched); + c->last_matched = 0; + } + else if (cw == c->last_added) { + c->last_added = 0; + /* send and reset string */ + ret += send_data(c,c->last_matched); + c->last_matched = 0; + } + else { + c->last_matched = cw; + /* collect char */ + c->str_data[c->str_len++] = *in++; + if ( c->str_len + c->flushed_len == c->max_string ) { + /* send and reset string */ + ret += send_data(c,c->last_matched); + c->last_matched = 0; + } + i++; + } + } + ret += test_mode(c); +#endif + return ret; +} + + +#if COMP_TEST +/* + * Test encoder procedures + * + */ + +/* force reset */ +int comp_force_reset(struct comp_state *c) +{ + int ret = 0; + if (c->mode != TRANSPARENT) + return 0; + COMP_DBG("comp_reset...\n"); + if (c->last_matched) { + ret = send_data(c,c->last_matched); + c->last_matched = 0; + } + c->obuf[c->olen++] = c->escape_char; + c->obuf[c->olen++] = CC_RESET; + ret += 2; + c->bit_data = 0; + dict_init(c); + return ret; +} + +/* force change compression mode */ +int comp_force_change_mode(struct comp_state *c, enum COMP_MODE mode) +{ + int ret = 0; + if (mode == c->mode) + return 0; + COMP_DBG("change_mode...\n"); + if (c->last_matched) { + c->update_at = c->last_matched; + ret += send_data(c,c->last_matched); + c->last_matched = 0; + } + /* switch to compressed mode */ + if (c->mode == TRANSPARENT) { + COMP_DBG("encoder %ld/%ld %d: switch to COMPRESSED mode.\n", + c->cmp_bits,c->raw_bits,c->cmp_last); + c->obuf[c->olen++] = c->escape_char; + c->obuf[c->olen++] = CCW_ECM; + ret += 2; + c->bit_data = 0; + c->mode = COMPRESSED; + } + /* switch to transparent mode */ + else if (c->mode == COMPRESSED) { + COMP_DBG("encoder %ld/%ld %d: switch to TRANSPARENT mode.\n", + c->cmp_bits,c->raw_bits,c->cmp_last); + SEND_CW(c,CCW_ETM); + ALIGN_BITS(c); + SEND_BITS(c); + c->mode = TRANSPARENT; + } + return ret; +} +#endif + + +/* + * init procedures + * + */ + + +int comp_init(struct comp_state *c,int dict_size,int max_str) +{ + struct dict *d; + int i; + memset(c,0,sizeof(*c)); + if (dict_size < MIN_DICT_SIZE || + max_str < MIN_STR_SIZE || max_str > MAX_STR_SIZE) + return -1; + /* alloc dict */ + d = COMP_ALLOC(dict_size*sizeof(*d)); + if (!d) + return -1; + COMP_DBG("comp_init: dict size %d, max str %d (dict %d bytes).\n", + dict_size,max_str,dict_size*sizeof(*d)); + memset(d,0,dict_size*sizeof(*d)); + c->max_string= max_str; + c->dict_size = dict_size; + c->dict = d; + /* init dict */ + for(i=0;idict[i+FIRST_ENTRY].ch = i; + } + dict_init(c); + /* temporary */ + c->olen = 0; + return 0; +} + +int comp_config(struct comp_state *c,int dict_size,int max_str) +{ + if (dict_size < MIN_DICT_SIZE || + max_str < MIN_STR_SIZE || max_str > MAX_STR_SIZE) + return -1; + if (dict_size > c->dict_size || max_str > sizeof(c->str_data)) + return -1; + c->max_string= max_str; + c->dict_size = dict_size; + //dict_init(c); + /* temporary */ + //c->olen = 0; + return 0; +} + +int comp_exit(struct comp_state *c) +{ + COMP_DBG("comp exit: %d/%d %d\n", + c->cmp_bits,c->raw_bits,c->cmp_last); + c->dict_size = 0; + if(c->dict) { + COMP_FREE(c->dict); + c->dict = NULL; + } + return 0; +} + +/* + * modem init procedures + * + */ + + +/* exported functions prototypes */ +extern int comp_init(struct comp_state *c,int dict_size,int max_str); +extern int comp_config(struct comp_state *c,int dict_size,int max_str); +extern int comp_exit(struct comp_state *c); +extern int comp_encode(struct comp_state *c, u8 *in, int n); +extern int comp_decode(struct comp_state *c, u8 *in, int n); +extern int comp_flush_encoder(struct comp_state *c); +extern int comp_flush_decoder(struct comp_state *c); + + +int modem_comp_init(struct modem *m) +{ + int ret; + ret = comp_init(&m->comp.encoder, + m->cfg.comp_dict_size,m->cfg.comp_max_string); + if(ret) + return ret; + ret = comp_init(&m->comp.decoder, + m->cfg.comp_dict_size,m->cfg.comp_max_string); + if (ret) { + comp_exit(&m->comp.encoder); + return ret; + } + return 0; +} + +int modem_comp_config(struct modem *m,int dict_size,int max_str) +{ + int ret = 0; + if ((ret = comp_config(&m->comp.encoder,dict_size,max_str)) || + (ret = comp_config(&m->comp.decoder,dict_size,max_str)) ) + COMP_ERR("modem_comp_config: setup failed (%d/%d).\n", + dict_size,max_str); + return ret; +} + + +void modem_comp_exit(struct modem *m) +{ + comp_exit(&m->comp.encoder); + comp_exit(&m->comp.decoder); + // temproary + m->comp.head = m->comp.count = 0; +} + + +// FIXME: remove this stupest things +static int get_odata(struct comp_state *c, char *buf, int n) +{ + int ret = 0; + if(c->olen > 0) { + ret = c->olen - c->ohead < n ? + c->olen - c->ohead : n; + memcpy(buf,c->obuf+c->ohead,ret); + c->ohead += ret; + if (c->ohead == c->olen) { + c->ohead = 0; + c->olen = 0; + } + } + return ret; +} + +int modem_comp_encode(struct modem *m, u8 ch, char *buf, int n) +{ + int ret; + ret = get_odata(&m->comp.encoder,buf,n); + if (ret == n) return ret; + if(comp_encode(&m->comp.encoder,&ch,1)<0) + return -1; + ret += get_odata(&m->comp.encoder,buf+ret,n-ret); + return ret; +} + +int modem_comp_decode(struct modem *m, u8 ch, char *buf, int n) +{ + int ret; + ret = get_odata(&m->comp.decoder,buf,n); + if(ret == n) return ret; + if(comp_decode(&m->comp.decoder,&ch,1)<0) + return -1; + ret += get_odata(&m->comp.decoder,buf+ret,n-ret); + return ret; +} + +int modem_comp_flush_encoder(struct modem *m, char *buf, int n) +{ + int ret; + ret = get_odata(&m->comp.encoder,buf,n); + if (ret == n) return ret; + if(comp_flush_encoder(&m->comp.encoder) < 0) + return -1; + ret += get_odata(&m->comp.encoder,buf+ret,n-ret); + return ret; +} + +int modem_comp_flush_decoder(struct modem *m, char *buf, int n) +{ + int ret; + ret = get_odata(&m->comp.decoder,buf,n); + if (ret == n) return ret; + if(comp_flush_decoder(&m->comp.decoder) < 0) + return -1; + ret += get_odata(&m->comp.decoder,buf+ret,n-ret); + return ret; +} diff --git a/slmodemd/modem_datafile.c b/slmodemd/modem_datafile.c new file mode 100644 index 0000000..be8a592 --- /dev/null +++ b/slmodemd/modem_datafile.c @@ -0,0 +1,137 @@ +/*****************************************************************************/ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem_datafile.c -- modem data file stuff. + * + * Author: Sasha K (sashak@smlink.com) + * + */ + +/*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#define DBG(fmt,args...) dprintf( fmt , ##args ); + + +struct datafile_record { + unsigned minor; + struct dsp_info dsp_info; + unsigned size; +}; + + + +int datafile_load_info(char *file_name,struct dsp_info *info) +{ + struct datafile_record *dr; + int ret = -1; + int fd; + + DBG("open file: %s...\n",file_name); + fd = open(file_name, 0, 0); + if(fd < 0) { + DBG("cannot open '%s': %s\n", + file_name,strerror(errno)); + return -errno; + } + + dr = (struct datafile_record *)malloc(sizeof(*dr)); + if (!dr) { + close(fd); + return -errno; + } + + ret = read(fd,(char *)dr,sizeof(*dr)); + if (ret < 0) { + free(dr); + close(fd); + return -errno; + } + + /* simple validation */ + if(dr->size != sizeof(*dr)) { + free(dr); + close(fd); + return -1; + } + + memcpy(info,&dr->dsp_info,sizeof(*info)); + + free(dr); + close(fd); + return ret; +} + + +int datafile_save_info(char *file_name,struct dsp_info *info) +{ + struct datafile_record *dr; + int ret = -1; + int fd; + + fd = open(file_name,O_CREAT|O_WRONLY,(S_IRUSR|S_IWUSR)); + if(fd < 0) + return -errno; + + dr = (struct datafile_record *)malloc(sizeof(*dr)); + if (!dr) { + return -errno; + close(fd); + } + + memcpy(&dr->dsp_info,info,sizeof(*info)); + dr->size = sizeof(*dr); + + ret = write(fd,(char *)dr,sizeof(*dr)); + + free(dr); + close(fd); + return ret; +} + + + diff --git a/slmodemd/modem_debug.c b/slmodemd/modem_debug.c new file mode 100644 index 0000000..f2bc47e --- /dev/null +++ b/slmodemd/modem_debug.c @@ -0,0 +1,169 @@ +/*****************************************************************************/ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem_debug.c -- modem debug module (dummy). + * + * Author: Sasha K (sashak@smlink.com) + * + * + */ + +/*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +unsigned int modem_debug_level=0; +unsigned int modem_debug_logging=0; +unsigned int dsplibs_debug_level=0; + +static const char *modem_debug_logfile = "slmodem.log"; + +static int modem_log_fd; + +/* logging */ + +int modem_debug_log_data(struct modem *m, unsigned id, const void *data, int count) +{ + struct sllog_header hdr; + int ret = 0; + if(id <= modem_debug_logging && modem_log_fd > 0) { + hdr.modem_id = (unsigned)m ; + hdr.id = id; + hdr.length = count; + ret = write(modem_log_fd,&hdr,sizeof(hdr)); + if(ret < 0) { + fprintf(stderr,"log_data: cannot write header: %s\n", + strerror(errno)); + return ret; + } + ret = write(modem_log_fd,data,count); + if(ret < 0) { + fprintf(stderr,"log_data: cannot write data: %s\n", + strerror(errno)); + return ret; + } + } + return ret; +} + + + +/* printing */ + +static int debug_vprintf(unsigned level, const char *fmt, va_list args) +{ + static char debug_temp[512]; + struct timeval tv; + int i, len; + gettimeofday(&tv,NULL); + i = snprintf(debug_temp,sizeof(debug_temp),"<%03ld.%06ld> ", + (tv.tv_sec % 1000), tv.tv_usec); + len = vsnprintf(debug_temp + i, sizeof(debug_temp) - i, fmt, args); + if(modem_debug_logging) + modem_debug_log_data(0, + MODEM_DBG_PRINT_MSG,debug_temp,len + i); + if(level <= modem_debug_level) + fprintf( stderr, "%s", debug_temp); + return len; +} + + +int dsplibs_debug_printf(const char *fmt, ...) +{ + va_list args; + int len; + va_start(args, fmt); + len = debug_vprintf(dsplibs_debug_level, fmt, args); + va_end(args); + return len; +} + +int modem_debug_printf(const char *fmt, ...) +{ + va_list args; + int len; + va_start(args, fmt); + len = debug_vprintf(1, fmt, args); + va_end(args); + return len; +} + + +int modem_debug_init(const char *suffix) +{ + dsplibs_debug_level = modem_debug_level; + if(modem_debug_logging) { + char path_name[PATH_MAX]; + const char *name; + if(suffix) { + snprintf(path_name, sizeof(path_name), + "%s.%s", modem_debug_logfile, suffix); + name = path_name; + } + else + name = modem_debug_logfile; + modem_log_fd = creat(name,S_IREAD|S_IWRITE); + if(modem_log_fd < 0) { + fprintf(stderr,"cannot create `%s': %s\n", + name,strerror(errno)); + return -1; + } + if(dsplibs_debug_level < 3) + dsplibs_debug_level = 3; + } + return 0; +} + +void modem_debug_exit() +{ + if(modem_log_fd > 0) { + close(modem_log_fd); + modem_log_fd = 0; + } +} + diff --git a/slmodemd/modem_debug.h b/slmodemd/modem_debug.h new file mode 100644 index 0000000..279da63 --- /dev/null +++ b/slmodemd/modem_debug.h @@ -0,0 +1,104 @@ +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem_debug.h - modem debug definitions. + * + * Author: SashaK + * + * Change History: + * + */ + +#ifndef __MODEM_DEBUG_H__ +#define __MODEM_DEBUG_H__ + + +/* constant definitions */ +enum MODEM_LOG_CATEGORIES { + /* 0-3 */ + MODEM_DBG_PRINT_MSG = 0, + MODEM_DBG_RX_SAMPLES, + MODEM_DBG_TX_SAMPLES, + MODEM_DBG_ECHOC_SAMPLES, + /* 4-5 */ + MODEM_DBG_MISC_DATA, + MODEM_DBG_MISC1_DATA, + /* 6-9 */ + MODEM_DBG_RX_BITS, + MODEM_DBG_TX_BITS, + MODEM_DBG_RX_DATA, + MODEM_DBG_TX_DATA, + /* 10-11 */ + MODEM_DBG_RX_CHARS, + MODEM_DBG_TX_CHARS, + /* 'overflow marker' */ + MODEM_DBG_OVERFLOW +}; + + +struct sllog_header { + unsigned modem_id; + unsigned id; + unsigned length; + char data[0]; +}; + +struct modem; + +#ifdef CONFIG_DEBUG_MODEM + +extern unsigned modem_debug_level; +extern int modem_debug_printf(const char *fmt,...) + __attribute__ ((format (printf, 1, 2))); + +#define eprintf(args...) { modem_debug_printf("err: " args) ; } +#define dprintf(args...) { modem_debug_printf(args) ; } + +extern int modem_debug_log_data(struct modem *m, unsigned id, const void *, int); + +#else /* not CONFIG_DEBUG_MODEM */ + +#define eprintf(fmt...) +#define dprintf(fmt...) +#define modem_debug_log_data(m,id,data,cnt) + +#endif /* not CONFIG_DEBUG_MODEM */ + +extern int modem_debug_init(const char *suffix); +extern void modem_debug_exit(); + + +#endif /* __MODEM_DEBUG_H__ */ + diff --git a/slmodemd/modem_defs.h b/slmodemd/modem_defs.h new file mode 100644 index 0000000..f8acedd --- /dev/null +++ b/slmodemd/modem_defs.h @@ -0,0 +1,443 @@ +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem_defs.h - modem common definitions + * + * Author: sashak@smlink.com + */ + +#ifndef __MODEM_DEFS_H__ +#define __MODEM_DEFS_H__ + +#ifdef __KERNEL__ +#include +#else + +#include + +typedef __uint8_t u8; +typedef __uint16_t u16; +typedef __uint32_t u32; + +typedef __int8_t s8; +typedef __int16_t s16; +typedef __int32_t s32; +#endif /* !__KERNEL__ */ + +/* hook states */ +#define MODEM_HOOK_ON 0 +#define MODEM_HOOK_OFF 1 +#define MODEM_HOOK_SNOOPING 2 + +/* modem device ctrl interface */ +#define MDMCTL_CAPABILITIES 0x01 +#define MDMCTL_HOOKSTATE 0x02 +#define MDMCTL_SPEED 0x04 +#define MDMCTL_GETFMTS 0x05 +#define MDMCTL_SETFMT 0x06 +#define MDMCTL_SETFRAG 0x07 +#define MDMCTL_SETFRAGMENT MDMCTL_SETFRAG +#define MDMCTL_SPEAKERVOL 0x08 +#define MDMCTL_IODELAY 0x10 +#define MDMCTL_CODECTYPE 0x11 +#define MDMCTL_PULSEDIAL 0x12 +#define MDMCTL_GETSTAT 0x20 +#define MDMCTL_START 0x21 +#define MDMCTL_STOP 0x22 + + +/* modem device status mask */ +#define MDMSTAT_ERROR 0x1 +#define MDMSTAT_RING 0x2 +#define MDMSTAT_DATA 0x4 + + +/* codec types - numbers important */ +enum codec_types { + CODEC_UNKNOWN = 0, + CODEC_AD1821 = 1, + CODEC_STLC7550= 4, + CODEC_SILABS = 9, + CODEC_SIL3052 = 10, + CODEC_SIL3054 = 11, + CODEC_AD1803 = 12, + CODEC_ALC545A = 13, +}; + +/* sample formats + extensions */ +#define MFMT_SIZE_MASK 0x000f +#define MFMT_SIZE_8 0x0000 +#define MFMT_SIZE_16 0x0001 +#define MFMT_SIGN_MASK 0x00f0 +#define MFMT_SIGNED 0x0010 +#define MFMT_UNSIGNED 0x0000 +#define MFMT_ORDER_MASK 0x0f00 +#define MFMT_ORDER_LE 0x0100 +#define MFMT_ORDER_BE 0x0000 + +#define MFMT_QUERY 0x0 + +#define MFMT_S8 (MFMT_SIZE_8|MFMT_SIGNED) +#define MFMT_U8 (MFMT_SIZE_8|MFMT_UNSIGNED) +#define MFMT_S16_LE (MFMT_SIZE_16|MFMT_SIGNED|MFMT_ORDER_LE) +#define MFMT_S16_BE (MFMT_SIZE_16|MFMT_SIGNED|MFMT_ORDER_BE) +#define MFMT_U16_LE (MFMT_SIZE_16|MFMT_UNSIGNED|MFMT_ORDER_LE) +#define MFMT_U16_BE (MFMT_SIZE_16|MFMT_UNSIGNED|MFMT_ORDER_BE) + +#define MFMT_IS_16BIT(x) ((x)&MFMT_SIZE_16) +#define MFMT_IS_LE(x) ((x)&MFMT_ORDER_LE) +#define MFMT_BYTESSHIFT(x) ((x)&MFMT_SIZE_MASK) +#define MFMT_SHIFT(x) (MFMT_BYTESSHIFT(x)) +#define MFMT_BYTES(x) (1< + + +/* + * type definitions + * + */ + + +/* data pump operations structure */ +struct dp_operations { + const char *name; + int use_count; + /* dp interface */ + struct dp *(*create)(struct modem *, enum DP_ID id, + int caller, int srate, int max_frag, + struct dp_operations *); + int (*delete)(struct dp *); + int (*process)(struct dp *, void *in, void *out, int cnt); + int (*hangup)(struct dp *); +}; + +/* data pump structure */ +struct dp { + enum DP_ID id; + struct modem *modem; + unsigned status; + struct dp_operations *op; + void *dp_data; +}; + + +/* + * prototypes + * + */ + +/* bit interface */ +extern int modem_get_bits(struct modem *m, int nbits, u8 *buf, int n); +extern int modem_put_bits(struct modem *m, int nbits, u8 *buf, int n); + +/* modem dp registration */ +extern int modem_dp_register(enum DP_ID id, struct dp_operations *op); +extern void modem_dp_deregister(enum DP_ID id, struct dp_operations *op); + + +#endif /* __MODEM_DP_H__ */ + diff --git a/slmodemd/modem_ec.c b/slmodemd/modem_ec.c new file mode 100644 index 0000000..2a72b1a --- /dev/null +++ b/slmodemd/modem_ec.c @@ -0,0 +1,1425 @@ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem_ec.c -- modem error corrector (lapm like) implementation. + * + * Author: Sasha K (sashak@smlink.com) + * + * + */ + +#include +#include + +//#define EC_DEBUG 1 + +/* LAPM default parameters */ +#define LAPM_DFLT_WIN_SIZE 15 /* default win size */ +#define LAPM_DFLT_INFO_SIZE 128 /* default info size */ + +#define LAPM_MAX_RTX 5 /* max num of retransmissions (N400) */ + +/* timeouts */ +// fixme: speed is parameter +#define _TMP_SPEED 28800 +// fixme: what is timeout vals should be (2sec?)??? +#define T401_TIMEOUT _TMP_SPEED*2 /* noacks timeout (in ???) */ +#define T403_TIMEOUT _TMP_SPEED*2 /* no frames timeout */ + +/* LAPM definitions */ + +/* frame types */ +#define FRAME_I 0x00 +#define FRAME_S 0x01 +#define FRAME_U 0x03 + +/* supervisory headers */ +#define FRAME_S_RR 0x01 /* cr */ +#define FRAME_S_RNR 0x05 /* cr */ +#define FRAME_S_REJ 0x09 /* cr */ +#define FRAME_S_SREJ 0x0d /* cr */ +/* unnumbered headers */ +#define FRAME_U_SABME 0x6f /* c */ +#define FRAME_U_DM 0x0f /* r */ +#define FRAME_U_UI 0x03 /* cr */ +#define FRAME_U_DISC 0x43 /* c */ +#define FRAME_U_UA 0x63 /* r */ +#define FRAME_U_FRMR 0x87 /* r */ +#define FRAME_U_XID 0xaf /* cr */ +#define FRAME_U_TEST 0xe3 /* c */ + +/* useful macros */ +#define FRAME_ADDR(f) ((f)->buf[0]) +#define FRAME_CTRL(f) ((f)->buf[1]) +#define FRAME_TYPE(f) ((f)->buf[1]&0x1 ? ((f)->buf[1]&0x3) : FRAME_I) +#define RX_IS_COMMAND(f) ((f)->buf[0] == l->rsp_addr) +#define TX_IS_COMMAND(f) ((f)->buf[0] == l->cmd_addr) +#define FRAME_I_PF(f) ((f)->buf[2]&0x1) +#define FRAME_S_PF(f) ((f)->buf[2]&0x1) +#define FRAME_U_PF(f) ((f)->buf[1]&0x10) +#define FRAME_NS(f) ((f)->buf[1]>>1) +#define FRAME_NR(f) ((f)->buf[2]>>1) + +/* tx unnumbered */ +#define TX_SABME(l) tx_unnum(l,l->cmd_addr,FRAME_U_SABME|0x10,0,0) +#define TX_DISC(l) tx_unnum(l,l->cmd_addr,FRAME_U_DISC|0x10,0,0) +#define TX_UA(l,pf_mask) tx_unnum(l,l->rsp_addr,FRAME_U_UA|pf_mask,0,0) +#define TX_DM(l,pf_mask) tx_unnum(l,l->rsp_addr,FRAME_U_DM|pf_mask,0,0) +/* tx supervisory */ +#define TX_RR(l,addr,pf_mask) tx_super(l,addr,FRAME_S_RR,pf_mask) +#define TX_RNR(l,addr,pf_mask) tx_super(l,addr,FRAME_S_RNR,pf_mask) +#define TX_REJ(l,addr,pf_mask) tx_super(l,addr,FRAME_S_REJ,pf_mask) + +/* timers */ +#define T401_START(l) { EC_DBG("T401 start.\n");\ + (l)->rtx_count = 0; \ + (l)->modem->bit_timer = T401_TIMEOUT; \ + (l)->modem->bit_timer_func = t401_timeout; } +#define T401_STOP(l) { EC_DBG("T401 stop.\n"); \ + (l)->modem->bit_timer = 0; (l)->rtx_count = 0; } +#if T403_IMPLEMENTED +#define TIMER_START(l) { EC_DBG("T403 stop, T401 start.\n"); \ + (l)->rtx_count = 0; \ + (l)->modem->bit_timer = T401_TIMEOUT; \ + (l)->modem->bit_timer_func = t401_timeout; } +#define TIMER_STOP(l) { EC_DBG("T401 stop, T403 start.\n"); \ + (l)->rtx_count = 0; \ + (l)->modem->bit_timer = T403_TIMEOUT; \ + (l)->modem->bit_timer_func = t403_timeout; } +#else /* !T403 */ +#define TIMER_START(l) T401_START(l) +#define TIMER_STOP(l) T401_STOP(l) +#endif /* !T403 */ + +/* xid sub-fields definitions */ +#define FI_GENERAL 0x82 +#define GI_PARAM_NEGOTIATION 0x80 +#define GI_PRIVATE_NEGOTIATION 0xf0 +#define GI_USER_DATA 0xff +/* param negotiation */ +#define PI_HDLC_OPTFUNCS 0x03 +#define PI_TX_INFO_MAXSIZE 0x05 +#define PI_RX_INFO_MAXSIZE 0x06 +#define PI_TX_WINDOW_SIZE 0x07 +#define PI_RX_WINDOW_SIZE 0x08 +/* private param negotiation */ +#define PI_PARAMETER_SET_ID 0x00 +#define PI_V42BIS_REQUEST 0x01 +#define PI_V42BIS_CW_NUMBER 0x02 +#define PI_V42BIS_MAX_STRING 0x03 +/* user data */ +/* fixme: ??? */ + + +/* type definitions */ +enum LAPM_STATES { LAPM_IDLE, LAPM_ESTAB, LAPM_DATA, LAPM_DISC }; + +/* prototypes */ +static int lapm_connect(struct lapm_state *l); +static int lapm_disconnect(struct lapm_state *l); +static void reset(struct lapm_state *l); + +/* + * service functions + * + */ + +/* le/be value parsing */ +extern inline u32 lapm_get_le_val(u8 *buf, int len) +{ + u32 val = 0; + while(len--) { + val <<= 8; + val |= buf[len]; + } + return val; +} + +extern inline u32 lapm_get_be_val(u8 *buf, int len) +{ + u32 val = 0; + while(len--) { + val <<= 8; + val |= *buf++; + } + return val; +} + +/* debug stuffs */ +#define EC_ERR(fmt,arg...) eprintf("%s ec err: " fmt , \ + l->modem->name , ##arg) + +#ifdef EC_DEBUG +#define EC_DBG(fmt,arg...) dprintf("%s ec: " fmt , \ + l->modem->name , ##arg) +#define EC_DBG1(fmt...) // EC_DBG(fmt) + +static char print_buf[(LAPM_MAX_INFO_SIZE+3)*2]; + +/* frame debug prints */ +static const char *get_frame_name(frame_t *f) +{ + if (!(f->buf[1]&0x1)) + return "INFO"; + switch(f->buf[1]&0xef) { + case FRAME_S_RR: return "RR"; + case FRAME_S_RNR: return "RNR"; + case FRAME_S_REJ: return "REJ"; + case FRAME_S_SREJ: return "SREJ"; + case FRAME_U_SABME: return "SABME"; + case FRAME_U_DM: return "DM"; + case FRAME_U_UI: return "UI"; + case FRAME_U_DISC: return "DISC"; + case FRAME_U_UA: return "UA"; + case FRAME_U_FRMR: return "FRMR"; + case FRAME_U_XID: return "XID"; + case FRAME_U_TEST: return "TEST"; + default: + break; + } + return "invalid frame"; +} + +static void print_frame(struct lapm_state *l, char *title, int cmd, frame_t *f) +{ + int i; + i = sprintf(print_buf,"(va/vs/vr %d/%d/%d) %s: %s %s", + l->va,l->vs,l->vr, + title,get_frame_name(f),cmd?"cmd":"rsp"); + switch (FRAME_TYPE(f)) { + case FRAME_I: + EC_DBG("%s[%d] cnt=%d, (ns/nr %d/%d)...\n",print_buf, + FRAME_I_PF(f),f->count-3,FRAME_NS(f),FRAME_NR(f)); + break; + case FRAME_S: + EC_DBG("%s[%d], (nr %d)...\n",print_buf, + FRAME_S_PF(f), FRAME_NR(f)); + break; + case FRAME_U: + EC_DBG("%s[%d]...\n",print_buf, FRAME_U_PF(f)); + break; + default: + EC_DBG("%s: unknown frame.\n", print_buf); + break; + } +} + +#define LAPM_PRINT_FRAME(str,cmd,f) print_frame(l,str,cmd,f) + +/* XID debug prints */ +static int print_xid_params(char *str_buf, u8 *buf, int len) +{ + u8 pid, plen; + u32 pval; + int i = 0; + while (len > 0) { + pid = buf[0]; + plen = buf[1]; + buf += 2; + len -= 2 + plen; + if (len < 0) + break; + switch (pid) { + case PI_HDLC_OPTFUNCS: + i += sprintf(str_buf + i,"HDLC_OPTFUNC = 0x%x, ", + lapm_get_le_val(buf,plen)); + break; + case PI_TX_INFO_MAXSIZE: + pval = lapm_get_be_val(buf,plen); + i += sprintf(str_buf + i,"TX_INFOSIZE = %u, ",pval>>3); + break; + case PI_RX_INFO_MAXSIZE: + pval = lapm_get_be_val(buf,plen); + i += sprintf(str_buf + i,"RX_INFOSIZE = %u, ",pval>>3); + break; + case PI_TX_WINDOW_SIZE: + i += sprintf(str_buf + i,"TX_WINSIZE = %u, ", + lapm_get_be_val(buf,plen)); + break; + case PI_RX_WINDOW_SIZE: + i += sprintf(str_buf + i,"RX_WINSIZE = %u, ", + lapm_get_be_val(buf,plen)); + break; + default: + i += sprintf(str_buf + i,"??, "); + break; + } + buf += plen; + } + i += sprintf(str_buf+i,"\n"); + return i; +} + +static int print_xid_private_params(char *str_buf, u8 *buf, int len) +{ + u8 pid, plen; + int i = 0; + while (len > 0) { + pid = buf[0]; + plen = buf[1]; + buf += 2; + len -= 2 + plen; + if (len < 0) + break; + switch (pid) { + case PI_PARAMETER_SET_ID: + i += sprintf(str_buf + i,"PARAM_SETID = 0x%x, ", + lapm_get_be_val(buf,plen)); + break; + case PI_V42BIS_REQUEST: + i += sprintf(str_buf + i,"V42BIS_REQUEST = 0x%x, ", + lapm_get_be_val(buf,plen)); + break; + case PI_V42BIS_CW_NUMBER: + i += sprintf(str_buf + i,"V42BIS_CWNUM = %d, ", + lapm_get_be_val(buf,plen)); + break; + case PI_V42BIS_MAX_STRING: + i += sprintf(str_buf + i,"V42BIS_MAXSTR = %d, ", + lapm_get_be_val(buf,plen)); + break; + default: + i += sprintf(str_buf + i,"??, "); + break; + } + buf += plen; + } + i += sprintf(str_buf+i,"\n"); + return i; +} + +static int print_xid(struct lapm_state *l,char *str,frame_t *f, int len) +{ + u8 *buf = f->buf + 2; + int i = 0; + + i = sprintf(print_buf,"XID: FID %02x;\n",*buf); + + buf++; len--; + while(len > 0) { + u8 gid = buf[0]; + u16 glen = buf[1]; + glen = glen << 8 | buf[2]; + buf += 3; + len -= 3 + glen; + if (len < 0) + break; + switch (gid) { + case GI_PARAM_NEGOTIATION: + i += sprintf(print_buf+i,"GI_PARAMS(%d): ",glen); + i += print_xid_params(print_buf+i,buf,glen); + break; + case GI_PRIVATE_NEGOTIATION: + i += sprintf(print_buf+i,"GI_PRIVATE_PARAMS(%d): ",glen); + i += print_xid_private_params(print_buf+i,buf,glen); + break; + default: + i += sprintf(print_buf+i,"unknown GI = 0x%x (%d) ??\n", + gid,glen); + break; + } + buf += glen; + } + EC_DBG("%s : %s\n", str, print_buf); + return 0; +} + +#define LAPM_PRINT_XID(str,f,len) print_xid(l,str,f,len); + +#else /* !LAPM_DEBUG */ + +#define EC_DBG(fmt...) +#define EC_DBG1(fmt...) +#define LAPM_PRINT_FRAME(str,cmd,f) +#define LAPM_PRINT_XID(str,f,len) + +#endif /* !LAPM_DEBUG */ + + + +/* + * service functions + * + */ + +/* get frame from ctrl list */ +static inline frame_t *get_ctrl_frame(struct lapm_state *l) +{ + frame_t *f; + if ( l->ctrl_list->next == l->tx_ctrl ) { + return 0; + } + f = l->ctrl_list; + l->ctrl_list = l->ctrl_list->next; + l->ctrl_count--; // debug only + return f; +} + + + +/* U transmission */ +static int tx_unnum(struct lapm_state *l, u8 addr, u8 ctrl, u8 *info, int len) +{ + frame_t *f = get_ctrl_frame(l); + if (!f) { + EC_ERR("tx_unnum: cannot alloc frame.\n"); + return -1; + } + f->buf[0] = addr; + f->buf[1] = ctrl; + if (info && len) + memcpy(f->buf+2,info,len); + f->size = 2 + len; + return 0; +} + +/* S transmission */ +static int tx_super(struct lapm_state *l, u8 addr, u8 ctrl, u8 pf_mask) +{ + frame_t *f = get_ctrl_frame(l); + if (!f) { + EC_ERR("tx_super: cannot alloc frame.\n"); + return -1; + } + f->buf[0] = addr; + f->buf[1] = ctrl; + f->buf[2] = (l->vr << 1)|pf_mask; + f->size = 3; + return 0; +} + + +/* parse xid */ +#define SET_PARAM(param,value,default) { \ + if (((value)<(default) && (param)>=(default)) || \ + ((value)>=(default) && (param)<(default))) \ + (param) = (default); \ + else if (((value)<(default) && (param)<(value)) || \ + ((value)>=(default) && (param)>(value))) \ + (param) = (value); } + +static int parse_xid_params(struct lapm_state *l, u8 *buf, int len) +{ + u32 pval; + u8 pid, plen; + while (len > 0) { + pid = buf[0]; + plen = buf[1]; + buf += 2; + len -= 2 + plen; + if (len < 0) + break; + switch (pid) { + case PI_HDLC_OPTFUNCS: + pval = lapm_get_le_val(buf,plen); + break; + case PI_TX_INFO_MAXSIZE: + pval = lapm_get_be_val(buf,plen); + pval >>= 3; + SET_PARAM(l->tx_info_size,pval,LAPM_DFLT_INFO_SIZE); + break; + case PI_RX_INFO_MAXSIZE: + pval = lapm_get_be_val(buf,plen); + pval >>= 3; + SET_PARAM(l->rx_info_size,pval,LAPM_DFLT_INFO_SIZE); + break; + case PI_TX_WINDOW_SIZE: + pval = lapm_get_be_val(buf,plen); + SET_PARAM(l->tx_win_size,pval,LAPM_DFLT_WIN_SIZE); + break; + case PI_RX_WINDOW_SIZE: + pval = lapm_get_be_val(buf,plen); + SET_PARAM(l->rx_win_size,pval,LAPM_DFLT_WIN_SIZE); + break; + default: + break; + } + buf += plen; + } + return 0; +} + + +static int parse_xid_private_params(struct lapm_state *l, struct modem_config *cfg, u8 *buf, int len) +{ + u8 pid, plen; + while (len > 0) { + pid = buf[0]; + plen = buf[1]; + buf += 2; + len -= 2 + plen; + if (len < 0) + break; + switch (pid) { + case PI_PARAMETER_SET_ID: + //pval = lapm_get_be_val(buf,plen); + break; + case PI_V42BIS_REQUEST: + cfg->comp = lapm_get_le_val(buf,plen); + break; + case PI_V42BIS_CW_NUMBER: + cfg->comp_dict_size = lapm_get_be_val(buf,plen); + break; + case PI_V42BIS_MAX_STRING: + cfg->comp_max_string = lapm_get_be_val(buf,plen); + break; + default: + break; + } + buf += plen; + } + return 0; +} + +#define DEFAULT_MODEM_EC_CONFIG {1,1,15,15,128,128,0,512,6} + +static int rx_xid(struct lapm_state *l, frame_t *f) +{ + struct modem_config cfg = DEFAULT_MODEM_EC_CONFIG; + u8 *buf = f->buf; + int len = f->count; + + /* skip addr and ctrl */ + buf += 2; len -= 2; + + LAPM_PRINT_XID("rx_xid",f,len); + if (*buf != FI_GENERAL) + return -1; + buf++; len--; + while(len > 0) { + u8 gid = buf[0]; + u16 glen = buf[1]; + glen = glen << 8 | buf[2]; + buf += 3; + len -= 3 + glen; + if (len < 0) + break; + switch (gid) { + case GI_PARAM_NEGOTIATION: + parse_xid_params(l,buf,glen); + break; + case GI_PRIVATE_NEGOTIATION: + parse_xid_private_params(l,&cfg,buf,glen); + break; + default: + break; + } + buf += glen; + } + cfg.ec_tx_win_size = l->tx_win_size; + cfg.ec_rx_win_size = l->rx_win_size; + cfg.ec_tx_info_size = l->tx_info_size; + cfg.ec_rx_info_size = l->rx_info_size; + modem_update_config(l->modem,&cfg); + return 0; +} + +static int tx_xid(struct lapm_state *l, u8 addr) +{ + u8 *buf; + int size = 2 + 1 + (3+19) + (3+15); + int len = 0; + u32 pval; + int glen; + frame_t *f = get_ctrl_frame(l); + if (!f) { + EC_ERR("tx_xid: cannot alloc frame.\n"); + return -1; + } + + buf = f->buf; + + *buf++ = addr; /* addr */ + *buf++ = FRAME_U_XID; /* ctrl */ + *buf++ = FI_GENERAL; /* fid */ + len += 3; + /* param negotiation group */ + *buf++ = GI_PARAM_NEGOTIATION; /* group id */ + glen = 19; /* group length */ // v42vmi: 19 + *buf++ = (glen>>8)&0xff; + *buf++ = glen&0xff; + len += 3; + *buf++ = PI_HDLC_OPTFUNCS; + *buf++ = 3; /* p length */ // v42vmi : 3 + *buf++ = 0x8a; /* p value */ + *buf++ = 0x89; + *buf++ = 0x00; + //*buf++ = 0x00; + *buf++ = PI_TX_INFO_MAXSIZE; + pval = l->tx_info_size<<3; + *buf++ = 2; /* p length */ + *buf++ = (pval>>8)&0xff; /* p value */ + *buf++ = (pval&0xff); + *buf++ = PI_RX_INFO_MAXSIZE; + pval = l->rx_info_size<<3; + *buf++ = 2; /* p length */ + *buf++ = (pval>>8)&0xff; /* p value */ + *buf++ = (pval&0xff); + *buf++ = PI_TX_WINDOW_SIZE; + *buf++ = 1; /* p length */ + *buf++ = l->tx_win_size; /* p value */ + *buf++ = PI_RX_WINDOW_SIZE; + *buf++ = 1; /* p length */ + *buf++ = l->rx_win_size; /* p value */ + len += glen; + +#if 1 /* v42bis-like compressor */ + if(l->modem->cfg.comp) { + /* private param negotiation group */ + *buf++ = GI_PRIVATE_NEGOTIATION; /* group id */ + glen = 15; /* group length (msb first) */ + *buf++ = (glen>>8)&0xff; + *buf++ = glen&0xff; + len += 3; + *buf++ = PI_PARAMETER_SET_ID; + *buf++ = 3; /* p length */ + *buf++ = 0x56;/*old 0x26 */ /* p value */ // v42vmi: 0x56 + *buf++ = 0x34; + *buf++ = 0x32; + *buf++ = PI_V42BIS_REQUEST; + *buf++ = 1; /* p length */ + *buf++ = l->modem->cfg.comp; /* 3 - compression in both direction */ + *buf++ = PI_V42BIS_CW_NUMBER; + *buf++ = 2; /* p length */ + pval = l->modem->cfg.comp_dict_size; + *buf++ = (pval>>8)&0xff; /* p value */ + *buf++ = (pval&0xff); + *buf++ = PI_V42BIS_MAX_STRING; + *buf++ = 1; /* p length */ + *buf++ = l->modem->cfg.comp_max_string; + len += glen; + } +#endif + + /* user data */ + /* ... */ + if (len > size) { + EC_ERR("tx_xid: result length(%d) > size (%d).\n", len, size); + return -1; + } + f->size = len; + LAPM_PRINT_XID("tx_xid",f,len); + return 0; +} + + +/* timeout procedures */ + +static void t401_timeout(struct modem *m) +{ + struct lapm_state *l = &m->ec.lapm; + EC_DBG("t401_timeout: %d...\n",l->rtx_count); + if (l->rtx_count > LAPM_MAX_RTX ) { + EC_DBG("t401: max retransmission count was reached.\n"); + l->rtx_count = 0; + // TBD + switch(l->state) { + case LAPM_ESTAB: + case LAPM_DISC: + l->state = LAPM_IDLE; + modem_update_status(l->modem,STATUS_EC_RELEASE); + break; + case LAPM_DATA: + // TBD: disconnect + EC_DBG("t401: max data rtx was reached: disconnect\n"); + lapm_disconnect(l); + break; + } + return ; + } + l->rtx_count++; + if (l->config) { + tx_xid(l,l->cmd_addr); + } + else { + switch(l->state) { + case LAPM_ESTAB: + TX_SABME(l); + break; + case LAPM_DISC: + TX_DISC(l); + break; + case LAPM_DATA: + if (l->busy) + TX_RNR(l,l->cmd_addr,1); + else + TX_RR(l,l->cmd_addr,1); + break; + } + } + m->bit_timer = T401_TIMEOUT; + m->bit_timer_func = t401_timeout; +} + +#if T403_IMPLEMENTED +static void t403_timeout(struct lapm_state *l) +{ + EC_DBG("t403_timeout...\n"); + if (l->state != LAPM_DATA) { + EC_ERR("t403: no in data state.\n"); + return; + } + if (l->busy) + TX_RNR(l,l->cmd_addr,1); + else + TX_RR(l,l->cmd_addr,1); + T401_START(l); + l->rtx_count = 1; +} +#endif + + +/* transmit info */ +static int tx_info(struct lapm_state *l) +{ + frame_t *f; + int n = 0; + if (l->peer_busy || + ((l->vs - l->va)&0x7f) >= l->tx_win_size) { + return 0; + } + if (l->tx_info == l->info_list) { /* empty tx */ + if (l->info_list->next == l->tx_info || + l->info_list->next == l->sent_info) { + EC_ERR("tx_info: cannot alloc frame.\n"); + return 0; + } + f = l->info_list; + if(!l->modem->get_chars) + return 0; + n = l->modem->get_chars(l->modem,(char*)(f->buf+3),l->tx_info_size); + if (n < 0) { /* error */ + EC_ERR("tx_info: get chars error.\n"); + modem_update_status(l->modem,STATUS_EC_ERROR); + return 0; + } + if ( n == 0) { /* no data */ + return 0; + } + + f->size = n + 3; + l->info_list = l->info_list->next; + l->info_count--; // debug + l->tx_count++; // debug + LAPM_PRINT_FRAME("tx_info",1,f); + } + + /* start T401 */ + //if (!l->timer) + // TIMER_START(l); + return 1; +} + +/* reject all noacked frames (>va) */ +static int reject_info(struct lapm_state *l) +{ + u8 n = (l->vs-l->va)&0x7f; + if (l->state != LAPM_DATA) /* ignore retransmission */ + return 0; + EC_DBG("(va/vs/vr %d/%d/%d) reject info: reject %d frames...\n", + l->va,l->vs,l->vr,n); + l->vs = l->va; + l->tx_info = l->sent_info; + l->tx_count += l->sent_count; // debug + l->sent_count = 0; // debug + return n; +} + +/* ack info */ +static int ack_info(struct lapm_state *l, u8 nr) +{ + int n = 0; + //EC_DBG1("ack info: nr %d...\n", nr); + /* check for valid nr ( va <= nr <= vs && vs-va<= k ) */ + // fixme: optimize this + if (!( ((nr-l->va)&0x7f) >= 0 && + ((l->vs-nr)&0x7f) >= 0 && + ((l->vs-l->va)&0x7f) <= l->tx_win_size) ) { + EC_ERR("nr sequince error. disconnect!\n"); + // TBD notify CF + lapm_disconnect(l); + return -1; + } + while(l->va != nr) { + if (l->sent_info == l->tx_info) { /* debug only ? */ + EC_ERR("ack info: VERY BAD: empty sent list: va %d, vs %d\n", + l->va,l->vs); + break; + } + l->sent_info = l->sent_info->next; + l->sent_count--; // debug + l->info_count++; // debug + l->va = (l->va+1)&0x7f; + n++; + } + /* stop T401 , start T403 */ +#if 1 + if(n > 0 && !l->rtx_count) { +#else + if(n > 0 && !l->rtx_count && !l->peer_busy) { +#endif + TIMER_STOP(l); + if ((l->vs-l->va)&0x7f) + TIMER_START(l); // exp.8.4.8 + } + return n; +} + + +/* push rest data (when busy) */ +static void push_rest_data(struct modem *m, int bits) +{ + struct lapm_state *l = &m->ec.lapm; + if (l->state != LAPM_DATA) + return; + if (l->rx_count && l->modem->put_chars) { + int ret = l->modem->put_chars(l->modem, + (const char*)(l->rx_buf+l->rx_head), + l->rx_count); + if (ret > 0) { + l->rx_head += ret; + l->rx_count -= ret; + if (!l->rx_count) { + l->rx_head = 0; + /* reset busy state */ + l->busy = 0; + TX_RR(l,l->cmd_addr,0); + l->modem->packer_process = NULL; + } + } + } +} + +/* info frame process */ +static int rx_info(struct lapm_state *l, frame_t *f) +{ + int ret = 0, n; + //LAPM_PRINT_FRAME("rx_info",1,f); + + /* ack I frames: nr -1 */ + n = ack_info(l,FRAME_NR(f)); + /* busy */ + if (l->busy) { + if(FRAME_I_PF(f)) /* 8.4.7 */ + TX_RNR(l,l->rsp_addr,1); + return 0; + } + /* NS sequence error */ + if (FRAME_NS(f)!= l->vr) { + /* TBD */ /* is info may be send */ + EC_DBG("seq.error: ns %d, vr %d\n",FRAME_NS(f),l->vr); + // reject should be sent + if (l->reject) /* already sent */ + return -1; + EC_DBG("tx reject...\n"); + TX_REJ(l,l->rsp_addr,FRAME_I_PF(f)); + /* TX_REJ(l,l->cmd_addr,1); */ + l->reject = 1; + // fixme: why to start timer + //if (!l->timer) + // TIMER_START(l); + return -1; + } + l->reject = 0; + /* recv data */ + + if(l->modem->put_chars) + ret = l->modem->put_chars(l->modem,(const char*)(f->buf+3),f->count-3); + if(ret<0) { + /* FIXME: handle error*/ ; + } + if (ret != f->count-3) { + /* save rest data, enter busy state */ + l->rx_head = 0; + l->rx_count = f->count - 3 - ret; + memcpy(l->rx_buf,f->buf+3+ret,l->rx_count); + // TBD + l->busy = 1; + // try to push rest data later + l->modem->packer_process = push_rest_data; + } + /* increment vr */ + l->vr = (l->vr+1)&0x7f; + /* response I,RR,RNR */ + if (l->busy) + TX_RNR(l,FRAME_ADDR(f),FRAME_I_PF(f)); + else if ( l->peer_busy || FRAME_I_PF(f) || + !tx_info(l) ) + TX_RR(l,FRAME_ADDR(f),FRAME_I_PF(f)); + return 0; +} + +/* rx supervisory frame */ + +static void rx_super_cmd(struct lapm_state *l, frame_t *f) +{ + int n; + //LAPM_PRINT_FRAME("rx super:",1,f); + + /* note 8.4.7: + if l->busy each RR,RNR,REJ with p=1 should be replied by RNR with f=1 */ + switch(FRAME_CTRL(f)) { + case FRAME_S_RR: + /* clear peer_busy state */ + l->peer_busy = 0; + n = ack_info(l,FRAME_NR(f)); + /* p=1 may be used for status checking */ + if (FRAME_S_PF(f) || !tx_info(l)) { + if (l->busy) + TX_RNR(l,FRAME_ADDR(f),FRAME_S_PF(f)); + else + TX_RR(l,FRAME_ADDR(f),FRAME_S_PF(f)); + } + break; + case FRAME_S_RNR: + /* going to peer_busy state */ + l->peer_busy = 1; + n = ack_info(l,FRAME_NR(f)); + /* if p=1 may be used for status checking ?? */ + if (FRAME_S_PF(f)) { + if (l->busy) + TX_RNR(l,l->rsp_addr,FRAME_S_PF(f)); + else + TX_RR(l,l->rsp_addr,FRAME_S_PF(f)); + } + break; + case FRAME_S_REJ: + /* clear peer_busy state */ + l->peer_busy = 0; + n = ack_info(l,FRAME_NR(f)); + if (!l->rtx_count) { + TIMER_STOP(l); + reject_info(l); + } + /* p=1 may be used for status checking */ + if (FRAME_S_PF(f) || !tx_info(l)) { + if (l->busy) + TX_RNR(l,FRAME_ADDR(f),FRAME_S_PF(f)); + else + TX_RR(l,FRAME_ADDR(f),FRAME_S_PF(f)); + } + break; + case FRAME_S_SREJ: + /* TBD, optional */ + EC_ERR("unsupported SREJ command!\n"); + return; + default: + EC_ERR("unknown s frame: %02x.\n",FRAME_CTRL(f)); + return; + } +} + +static void rx_super_rsp(struct lapm_state *l, frame_t *f) +{ + int n; + //LAPM_PRINT_FRAME("rx_super",0,f); + + if (!l->rtx_count && FRAME_S_PF(f)) { + EC_ERR("rx_super: unsolisited final response!\n"); + return; + } + /* ack I frames <= nr -1 */ + switch(FRAME_CTRL(f)) { + case FRAME_S_RR: + l->peer_busy = 0; + n = ack_info(l,FRAME_NR(f)); + if (l->rtx_count && FRAME_S_PF(f)) { + reject_info(l); + TIMER_STOP(l); + } + break; + case FRAME_S_RNR: + l->peer_busy = 1; + n = ack_info(l,FRAME_NR(f)); + if (l->rtx_count && FRAME_S_PF(f)) { + reject_info(l); + TIMER_STOP(l); // fixme: need stop even on RNR ?? + } + if (!l->rtx_count) + TIMER_START(l); + break; + case FRAME_S_REJ: + l->peer_busy = 0; + n = ack_info(l,FRAME_NR(f)); + if (!l->rtx_count || FRAME_S_PF(f)) { + reject_info(l); + TIMER_STOP(l); + } + break; + case FRAME_S_SREJ: + /* TBD, optional */ + EC_ERR("unsupported SREJ response!\n"); + return; + default: + EC_ERR("rx_s_rsp: unknown header %02x.\n", FRAME_CTRL(f)); + return; + } +} + + +/* rx unnumbered frame */ + +static int rx_unnum_cmd(struct lapm_state *l, frame_t *f) +{ + //LAPM_PRINT_FRAME("rx unnum:",1,f); + switch(FRAME_CTRL(f)&0xef) { + case FRAME_U_SABME: + EC_DBG("sabme received.\n"); + /* discard unacked I frames, + reset vs,vr,va, clear exceptions */ + reset(l); + /* going to connected state */ + l->state = LAPM_DATA; + /* respond UA (or DM on error) */ + // fixme: why may be error and TX_DM ?? + TX_UA(l,FRAME_U_PF(f)); + TIMER_STOP(l); + modem_update_status(l->modem,STATUS_EC_LINK); + break; + case FRAME_U_UI: + /* break signal */ + /* pf = 0 */ + /* TBD */ + break; + case FRAME_U_DISC: + /* respond UA (or DM) */ + if (l->state == LAPM_IDLE) + TX_DM(l,1); + else { /* going to disconnected state, + discard unacked I frames, reset all */ + l->state = LAPM_IDLE; + reset(l); + TX_UA(l,FRAME_U_PF(f)); + T401_STOP(l); + // TBD notify CF + modem_update_status(l->modem,STATUS_EC_RELEASE); + } + break; + case FRAME_U_XID: + /* exchange general id info */ + rx_xid(l,f); + tx_xid(l,l->rsp_addr); + break; + case FRAME_U_TEST: + /* TBD */ + /* optional */ + break; + default: + EC_ERR("rx unnum cmd: unknown frame 0x%02x\n", FRAME_CTRL(f)); + return -1; + } + return 0; +} + +static int rx_unnum_rsp(struct lapm_state *l, frame_t *f) +{ + //LAPM_PRINT_FRAME("rx unnum",0, f); + switch(FRAME_CTRL(f)&0xef) { + case FRAME_U_DM: + /* notify peer about disconnected state */ + /* TBD */ + switch(l->state) { + case LAPM_ESTAB: + case LAPM_DISC: + if (FRAME_U_PF(f)) { + l->state = LAPM_IDLE; + reset(l); + T401_STOP(l); + // TBD notify CF + modem_update_status(l->modem,STATUS_EC_RELEASE); + } + break; + case LAPM_DATA: + if (l->rtx_count || !FRAME_U_PF(f)) { + l->state = LAPM_IDLE; + reset(l); + // TBD: notify CF + modem_update_status(l->modem,STATUS_EC_RELEASE); + } + break; + case LAPM_IDLE: + if (!FRAME_U_PF(f)) { + // TBD: notify CF + // to establish connection + modem_update_status(l->modem,STATUS_EC_LINK); + } + break; + default: + break; + } + break; + case FRAME_U_UI: + /* break signal */ + /* pf = 0 */ + /* TBD */ + break; + case FRAME_U_UA: + /* notify us about mode change, responds SABME,DISC */ + switch(l->state) { + case LAPM_ESTAB: + l->state = LAPM_DATA; + reset(l); + TIMER_STOP(l); + modem_update_status(l->modem,STATUS_EC_LINK); + break; + case LAPM_DISC: + // TBD + l->state = LAPM_IDLE; + reset(l); + T401_STOP(l); + modem_update_status(l->modem,STATUS_EC_RELEASE); + break; + default: + // TBD + /* handle unsolicited UA */ + break; + } + /* clear all exceptions, busy states (self and peer) */ + /* reset vars */ + break; + case FRAME_U_FRMR: + /* not recovarable error */ + /* TBD */ + break; + case FRAME_U_XID: + if (l->config) { + rx_xid(l,f); + l->config = 0; + T401_STOP(l); + if (l->state == LAPM_IDLE) { + lapm_connect(l); + } + else if (l->state == LAPM_DATA) { + l->busy = 0; + TX_RR(l,l->cmd_addr,0); + } + } + break; + default: + EC_ERR("rx unnum rsp: unknown frame 0x%02x\n", FRAME_CTRL(f)); + break; + } + return 0; +} + + +/* lapm framer interface functions */ + +static frame_t *lapm_get_tx_frame(void *framer) +{ + struct lapm_state *l = framer; + frame_t *f; + /* get ctrl frame */ + if ( l->tx_ctrl != l->ctrl_list ) { + f = l->tx_ctrl; + l->tx_ctrl = l->tx_ctrl->next; + return f; + } + /* get info frame */ + if ( l->peer_busy || l->config || l->state != LAPM_DATA) + return 0; + if ( l->tx_info == l->info_list && !tx_info(l) ) + return 0; + f = l->tx_info; + l->tx_info = l->tx_info->next; + + f->buf[0] = l->cmd_addr; + f->buf[1] = l->vs << 1; + f->buf[2] = l->vr << 1; + l->vs = (l->vs + 1)&0x7f; + if (!l->modem->bit_timer) + TIMER_START(l); + //LAPM_PRINT_FRAME("get_tx_frame",1,f); + + //EC_DBG1("get_tx_frame: sent %d, tx %d, free %d...\n", + // l->sent_count,l->tx_count,l->info_count); + return f; +} + +static void lapm_tx_complete(void *framer, frame_t *f) +{ + struct lapm_state *l = framer; + LAPM_PRINT_FRAME("tx",TX_IS_COMMAND(f),f); + switch(FRAME_TYPE(f)) { + case FRAME_I: + l->sent_count++; // debug + l->tx_count--; // debug + //EC_DBG1("tx_info_complete: sent %d, tx %d, free %d.\n", + // l->sent_count,l->tx_count,l->info_count); + break; + case FRAME_S: + case FRAME_U: + l->ctrl_count++; // debug + break; + default: + EC_ERR("unknown frame type.\n"); + break; + } +} + + +static int valid_data_state(struct lapm_state *l) +{ + switch (l->state) { + case LAPM_ESTAB: + reset(l); + l->state = LAPM_DATA; + modem_update_status(l->modem,STATUS_EC_LINK); + case LAPM_DATA: + return 1; + case LAPM_DISC: + reset(l); + l->state = LAPM_IDLE; + modem_update_status(l->modem,STATUS_EC_RELEASE); + case LAPM_IDLE: + return 0; + default: + EC_ERR("valid_data_state: unknown state %d.\n", l->state); + return 0; + } + return 0; + +} + +static void lapm_rx_complete(void *framer, frame_t *f) +{ + struct lapm_state *l = framer; + LAPM_PRINT_FRAME("rx",RX_IS_COMMAND(f),f); + switch(FRAME_TYPE(f)) { + case FRAME_I: + if(!valid_data_state(l)) + return; + rx_info(l,f); + break; + case FRAME_S: + if(!valid_data_state(l)) + return; + if (RX_IS_COMMAND(f)) + rx_super_cmd(l,f); + else + rx_super_rsp(l,f); + break; + case FRAME_U: + if (RX_IS_COMMAND(f)) + rx_unnum_cmd(l,f); + else + rx_unnum_rsp(l,f); + break; + default: + EC_ERR("unknown frame type.\n"); + break; + } +} + + +/* lapm api functions */ + +static int lapm_connect(struct lapm_state *l) +{ + if (!l->state == LAPM_IDLE) + return -1; + + /* negotiate params */ + //tx_xid(l,l->cmd_addr); + + /* clear all */ + reset(l); + /* connect */ + l->state = LAPM_ESTAB; + TX_SABME(l); + /* start t401 (and not t403) */ + T401_START(l); + return 0; +} + +/* negotiate params */ +static int lapm_config(struct lapm_state *l) +{ + l->config = 1; + if (l->state == LAPM_DATA) { + l->busy = 1; + TX_RNR(l,l->cmd_addr,1); + } + tx_xid(l,l->cmd_addr); + T401_START(l); + return 0; +} + +static int lapm_disconnect(struct lapm_state *l) +{ + l->state = LAPM_DISC; + TX_DISC(l); + /* start T401 (and not T403) */ + T401_START(l); + return 0; +} + + +static void reset(struct lapm_state *l) +{ + l->busy = 0; + l->peer_busy = 0; + l->vs = 0; + l->va = 0; + l->vr = 0; + /* discard pended data */ + // l->rx_head = l->rx_count = 0; + /* discard info frames */ + l->sent_info = l->info_list; + l->tx_info = l->info_list; + l->sent_count = l->tx_count = 0; + l->info_count = LAPM_INFO_FRAMES; + /* discard ctrl frames */ + // TBD ??? +} + +/* fixme: optimize mem usage */ +static int alloc_frames(struct lapm_state *l) +{ +#define arrsize(a) (sizeof(a)/sizeof((a)[0])) + frame_t *f; + int i; + EC_DBG("alloc_frames: lapm size %d (info %d, ctrl %d).\n", + sizeof(*l), sizeof(l->info_buf), sizeof(l->ctrl_buf)); + /* init info list */ + l->info_list = &l->info_buf[0].frame; + for (i=0;iinfo_buf);i++) { + f = &l->info_buf[i].frame; + f->next = &l->info_buf[i+1].frame; + f->buf = l->info_buf[i].ctrl; + f->size = sizeof(l->info_buf[0]) - sizeof(frame_t); + } + f->next = l->info_list; + l->info_count= arrsize(l->info_buf); // debug + l->tx_info = l->info_list; + l->sent_info = l->info_list; + /* init ctrl list */ + l->ctrl_list = &l->ctrl_buf[0].frame; + for (i=0;ictrl_buf);i++) { + f = &l->ctrl_buf[i].frame; + f->next = &l->ctrl_buf[i+1].frame; + f->buf = l->ctrl_buf[i].ctrl; + f->size = sizeof(l->ctrl_buf[0]) - sizeof(frame_t); + } + f->next = l->ctrl_list; + l->ctrl_count= arrsize(l->ctrl_buf); // debug + l->tx_ctrl = l->ctrl_list; + return 0; +} + + +static int lapm_init(struct lapm_state *l, struct modem *m) +{ + memset(l,0,sizeof(*l)); + l->modem = m; + l->state = LAPM_IDLE; + l->busy = 0; + l->peer_busy = 0; + /* set originator/answer addresses */ + l->cmd_addr = m->caller ? 0x3 : 0x1; + l->rsp_addr = m->caller ? 0x1 : 0x3; + + l->tx_win_size = m->cfg.ec_tx_win_size; + l->rx_win_size = m->cfg.ec_rx_win_size; + l->tx_info_size = m->cfg.ec_tx_info_size; + l->rx_info_size = m->cfg.ec_rx_info_size; + + alloc_frames(l); + reset(l); + return 0; +} + +static int lapm_exit(struct lapm_state *l) +{ + reset(l); + l->info_list = 0; + l->ctrl_list = 0; + return 0; +} + + + +/* modem ec interface func */ +static void modem_ec_negotiate(struct modem *m) +{ + m->packer.hdlc.tx_complete = lapm_tx_complete; + m->packer.hdlc.get_tx_frame = lapm_get_tx_frame; + lapm_config(&m->ec.lapm); +} + +void modem_ec_start(struct modem *m) +{ + struct hdlc_state *h = &m->packer.hdlc; + struct lapm_state *l = &m->ec.lapm; + EC_DBG("modem_ec_start...\n"); + h->framer = l; + h->tx_complete = NULL; + h->rx_complete = lapm_rx_complete; + h->get_tx_frame = NULL; + if(m->caller) { + m->bit_timer = 48*8; + m->bit_timer_func = modem_ec_negotiate; + } + else { + h->tx_complete = lapm_tx_complete; + h->get_tx_frame = lapm_get_tx_frame; + } + // fixme: improve BUSY becoming, remove packer_process() + m->packer_process = NULL; +} + +void modem_ec_stop(struct modem *m) +{ + struct lapm_state *l = &m->ec.lapm; + EC_DBG("modem_ec_stop...\n"); + m->bit_timer = 0; + m->packer_process = NULL; + lapm_disconnect(l); +} + +int modem_ec_init(struct modem *m) +{ + struct lapm_state *l = &m->ec.lapm; + lapm_init(l,m); + return 0; +} + +void modem_ec_exit(struct modem *m) +{ + struct lapm_state *l = &m->ec.lapm; + lapm_exit(l); +} + diff --git a/slmodemd/modem_homolog.h b/slmodemd/modem_homolog.h new file mode 100644 index 0000000..808df02 --- /dev/null +++ b/slmodemd/modem_homolog.h @@ -0,0 +1,111 @@ +/*****************************************************************************/ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem_homolog.h -- Modem Homologation definitions. + * + * Author: Sasha K (sashak@smlink.com) + * + * + */ + +/*****************************************************************************/ + +#ifndef __MODEM_HOMOLOG_H__ +#define __MODEM_HOMOLOG_H__ + + +/* homologation parameters struct */ +struct homolog_params { + u8 PulseDialMakeTime; + u8 PulseDialBreakTime; + u8 PulseDialDigitPattern; + u8 DTMFHighToneLevel; + u8 DTMFDialSpeed; + u8 MinBusyCadenceOnTime; + u8 MaxBusyCadenceOnTime; + u8 BusyDetectionCyclesNumber; + u8 MinBusyCadenceOffTime; + u8 MaxBusyCadenceOffTime; + u8 CallingToneFlag; + u8 HookFlashTime; + u8 DialPauseTime; // ? + u8 TransmitLevel; + u8 DialModifierValidation; + u8 DialToneValidationTime; + //u8 BusyToneDiffTime; + u8 DTMFHighAndLowToneLevelDifference; + u8 DialToneCallProgressFilterIndex; + u8 DialToneDetectionThreshold; + u8 ABCDDialingPermittedFlag; + u8 ComaPauseDurationLimit; + //u8 PulseAndToneDialInSameDialStringPermittedFlag; + u8 BusyToneCallProgressFilterIndex; + u8 PulseBetweenDigitsInterval; + u8 DialToneWaitTime; + u8 MinRingbackCadenceOnTime; + u8 MaxRingbackCadenceOnTime; + u8 RingbackDetectionCyclesNumber; + //u8 MinRingbackCadenceOffTime; + //u8 MaxRingbackCadenceOffTime; + //u8 RingbackToneCallProgressFilterIndex; + //u8 MinCongestionCadenceOnTime; + //u8 MaxCongestionCadenceOnTime; + //u8 CongestionDetectionCyclesNumber; + //u8 MinCongestionCadenceOffTime; + //u8 MaxCongestionCadenceOffTime; + //u8 CongestionToneCallProgressFilterIndex; + u16 CallProgressSamplesBufferLength; + u8 MustNoiseFilterBeApplied; + //u32 DigitalImpairmentsMask; + //u8 DialToneFilterSubindex; + //u8 BusyToneLooseDetectionEnabled; + //u8 CallWaitingIntegrationTimeMiliSec; + //u8 CallWaitingThresholdPercentage; +}; + + +/* homologation country set */ +struct homolog_set { + const u16 id; + const char *name; + const struct homolog_params *params; +}; + +/* 'nulled'-terminated homologation array */ +extern const struct homolog_set homolog_set[]; + +#endif /* __MODEM_HOMOLOG_H__ */ diff --git a/slmodemd/modem_main.c b/slmodemd/modem_main.c new file mode 100644 index 0000000..998090a --- /dev/null +++ b/slmodemd/modem_main.c @@ -0,0 +1,1212 @@ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * Copyright (c) 2021, Aon plc + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem_main.c -- modem main func. + * + * Author: Sasha K (sashak@smlink.com) + * + * + */ + +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#define ENOIOCTLCMD 515 + +#ifdef SUPPORT_ALSA +#define ALSA_PCM_NEW_HW_PARAMS_API 1 +#define ALSA_PCM_NEW_SW_PARAMS_API 1 +#include +/* buffer size in periods */ +#define BUFFER_PERIODS 12 +#define SHORT_BUFFER_PERIODS 4 +#endif + +#include +#include + +#define INFO(fmt,args...) fprintf(stderr, fmt , ##args ); +#define ERR(fmt,args...) fprintf(stderr, "error: " fmt , ##args ); + +#define DBG(fmt,args...) dprintf("main: " fmt, ##args) + + +#define SLMODEMD_USER "nobody" +#define LOCKED_MEM_MIN_KB (8UL * 1024) +#define LOCKED_MEM_MIN (LOCKED_MEM_MIN_KB * 1024) + +#define CLOSE_COUNT_MAX 100 + + +/* modem init externals : FIXME remove it */ +extern int dp_dummy_init(void); +extern void dp_dummy_exit(void); +extern int dp_sinus_init(void); +extern void dp_sinus_exit(void); +extern int prop_dp_init(void); +extern void prop_dp_exit(void); +extern int datafile_load_info(char *name,struct dsp_info *info); +extern int datafile_save_info(char *name,struct dsp_info *info); +extern int modem_ring_detector_start(struct modem *m); + +/* global config data */ +extern const char *modem_dev_name; +extern unsigned int ring_detector; +extern unsigned int need_realtime; +extern const char *modem_group; +extern mode_t modem_perm; +extern unsigned int use_short_buffer; +extern const char *modem_exec; + + +struct device_struct { + int num; + int fd; +#ifdef SUPPORT_ALSA + snd_pcm_t *phandle; + snd_pcm_t *chandle; + snd_mixer_t *mhandle; + snd_mixer_elem_t *hook_off_elem; + snd_mixer_elem_t *cid_elem; + snd_mixer_elem_t *speaker_elem; + unsigned int period; + unsigned int buf_periods; + unsigned int started; +#endif + int delay; +}; + + +static char inbuf[4096]; +static char outbuf[4096]; + + +/* + * ALSA 'driver' + * + */ + +#ifdef SUPPORT_ALSA + +#define INTERNAL_DELAY 40 /* internal device tx/rx delay: should be selfdetectible */ + +extern unsigned use_alsa; +static snd_output_t *dbg_out = NULL; + +static int alsa_mixer_setup(struct device_struct *dev, const char *dev_name) +{ + char card_name[32]; + int card_num = 0; + char *p; + snd_mixer_elem_t *elem; + int err; + + if((p = strchr(dev_name, ':'))) + card_num = strtoul(p+1, NULL, 0); + sprintf(card_name, "hw:%d", card_num); + + err = snd_mixer_open(&dev->mhandle, 0); + if(err < 0) { + DBG("mixer setup: cannot open: %s\n", snd_strerror(err)); + return err; + } + err = snd_mixer_attach(dev->mhandle, card_name); + if (err < 0) { + ERR("mixer setup: attach %s error: %s\n", card_name, snd_strerror(err)); + goto error; + } + err = snd_mixer_selem_register(dev->mhandle, NULL, NULL); + if (err <0) { + ERR("mixer setup: register %s error: %s\n", card_name, snd_strerror(err)); + goto error; + } + err = snd_mixer_load(dev->mhandle); + if (err < 0) { + ERR("mixer setup: load %s error: %s\n", card_name, snd_strerror(err)); + goto error; + } + + for (elem = snd_mixer_first_elem(dev->mhandle) ; elem; elem = snd_mixer_elem_next(elem)) { + if(strcmp(snd_mixer_selem_get_name(elem),"Off-hook") == 0) + dev->hook_off_elem = elem; + else if(strcmp(snd_mixer_selem_get_name(elem),"Caller ID") == 0) + dev->cid_elem = elem; + else if(strcmp(snd_mixer_selem_get_name(elem),"Modem Speaker") == 0) + dev->speaker_elem = elem; + } + + if(dev->hook_off_elem) + return 0; + +error: + snd_mixer_close(dev->mhandle); + dev->mhandle = NULL; + if (!err) { + ERR("mixer setup: Off-hook switch not found for card %s\n", card_name); + err = -ENODEV; + } + return err; +} + +static int alsa_device_setup(struct device_struct *dev, const char *dev_name) +{ + struct pollfd pfd; + int ret; + memset(dev,0,sizeof(*dev)); + + ret = alsa_mixer_setup(dev, dev_name); + if(ret < 0) + DBG("alsa setup: cannot setup mixer: %s\n", snd_strerror(ret)); + + ret = snd_pcm_open(&dev->phandle, dev_name, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK); + if(ret < 0) { + ERR("alsa setup: cannot open playback device '%s': %s\n", + dev_name, snd_strerror(ret)); + return -1; + } + ret = snd_pcm_open(&dev->chandle, dev_name, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK); + if(ret < 0) { + ERR("alsa setup: cannot open playback device '%s': %s\n", + dev_name, snd_strerror(ret)); + return -1; + } + ret = snd_pcm_poll_descriptors(dev->chandle, &pfd, 1); + if(ret <= 0) { + ERR("alsa setup: cannot get poll descriptors of '%s': %s\n", + dev_name, snd_strerror(ret)); + return -1; + } + dev->fd = pfd.fd; + dev->num = 0; /* <-- FIXME */ + + if(modem_debug_level > 0) + snd_output_stdio_attach(&dbg_out,stderr,0); + + return 0; +} + +static int alsa_device_release(struct device_struct *dev) +{ + snd_pcm_close (dev->phandle); + snd_pcm_close (dev->chandle); + if (dev->mhandle) { + if (dev->hook_off_elem) + snd_mixer_selem_set_playback_switch_all(dev->hook_off_elem, 0); + if (dev->cid_elem) + snd_mixer_selem_set_playback_switch_all(dev->cid_elem, 0); + if (dev->speaker_elem) + snd_mixer_selem_set_playback_switch_all(dev->speaker_elem, 0); + snd_mixer_close(dev->mhandle); + } + return 0; +} + + +static int alsa_xrun_recovery(struct device_struct *dev) +{ + int err; + int len; + DBG("alsa xrun: try to recover...\n"); + err = snd_pcm_prepare(dev->phandle); + if (err < 0) { + ERR("xrun recovery: cannot prepare playback: %s\n", snd_strerror(err)); + return err; + } + len = dev->delay - INTERNAL_DELAY; + snd_pcm_format_set_silence(SND_PCM_FORMAT_S16_LE, outbuf, len); + err = snd_pcm_writei(dev->phandle, outbuf, len); + if (err < 0) { + ERR("xrun recovery: write error: %s\n", snd_strerror(err)); + return err; + } + err = snd_pcm_start(dev->chandle); + if(err < 0) { + ERR("xrun recovcery snd_pcm_start error: %s\n", snd_strerror(err)); + return err; + } + DBG("alsa xrun: recovered.\n"); + return 0; +} + + +static int alsa_device_read(struct device_struct *dev, char *buf, int count) +{ + int ret; + do { + ret = snd_pcm_readi(dev->chandle,buf,count); + if (ret == -EPIPE) { + ret = alsa_xrun_recovery(dev); + break; + } + } while (ret == -EAGAIN); +#if 0 + if(ret != dev->period) + DBG("alsa_device_read (%d): %d ...\n",count,ret); +#endif + return ret ; +} + +static int alsa_device_write(struct device_struct *dev, const char *buf, int count) +{ + int written = 0; + if(!dev->started) + return 0; + while(count > 0) { + int ret = snd_pcm_writei(dev->phandle,buf,count); + if(ret < 0) { + if (ret == -EAGAIN) + continue; + if (ret == -EPIPE) { + ret = alsa_xrun_recovery(dev); + } + written = ret; + break; + } + count -= ret; + buf += ret; + written += ret; + } +#if 0 + if(written != dev->period) + DBG("alsa_device_write (%d): %d...\n",asked,written); +#endif + return written; +} + + +static snd_pcm_format_t mdm2snd_format(unsigned mdm_format) +{ + if(mdm_format == MFMT_S16_LE) + return SND_PCM_FORMAT_S16_LE; + return SND_PCM_FORMAT_UNKNOWN; +} + + +static int setup_stream(snd_pcm_t *handle, struct modem *m, const char *stream_name) +{ + struct device_struct *dev = m->dev_data; + snd_pcm_hw_params_t *hw_params; + snd_pcm_sw_params_t *sw_params; + snd_pcm_format_t format; + unsigned int rate, rrate; + snd_pcm_uframes_t size, rsize; + int err; + + err = snd_pcm_hw_params_malloc(&hw_params); + if (err < 0) { + ERR("cannot alloc hw params for %s: %s\n", stream_name, snd_strerror(err)); + return err; + } + err = snd_pcm_hw_params_any(handle,hw_params); + if (err < 0) { + ERR("cannot init hw params for %s: %s\n", stream_name, snd_strerror(err)); + return err; + } + err = snd_pcm_hw_params_set_access(handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED); + if (err < 0) { + ERR("cannot set access for %s: %s\n", stream_name, snd_strerror(err)); + return err; + } + format = mdm2snd_format(m->format); + if(format == SND_PCM_FORMAT_UNKNOWN) { + ERR("unsupported format for %s\n",stream_name); + return -1; + } + err = snd_pcm_hw_params_set_format(handle, hw_params, format); + if (err < 0) { + ERR("cannot set format for %s: %s\n", stream_name, snd_strerror(err)); + return err; + } + err = snd_pcm_hw_params_set_channels(handle, hw_params, 1); + if (err < 0) { + ERR("cannot set channels for %s: %s\n", stream_name, snd_strerror(err)); + return err; + } + rrate = rate = m->srate; + err = snd_pcm_hw_params_set_rate_near(handle, hw_params, &rrate, 0); + if (err < 0) { + ERR("cannot set rate for %s: %s\n", stream_name, snd_strerror(err)); + return err; + } + if ( rrate != rate ) { + ERR("rate %d is not supported by %s (%d).\n", + rate, stream_name, rrate); + return -1; + } + rsize = size = dev->period ; + err = snd_pcm_hw_params_set_period_size_near(handle, hw_params, &rsize, NULL); + if (err < 0) { + ERR("cannot set periods for %s: %s\n", stream_name, snd_strerror(err)); + return err; + } + if ( rsize < size ) { + ERR("period size %ld is not supported by %s (%ld).\n", + size, stream_name, rsize); + return -1; + } + rsize = size = use_short_buffer ? rsize * dev->buf_periods : rsize * 32; + err = snd_pcm_hw_params_set_buffer_size_near(handle, hw_params, &rsize); + if (err < 0) { + ERR("cannot set buffer for %s: %s\n", stream_name, snd_strerror(err)); + return err; + } + if ( rsize != size ) { + DBG("buffer size for %s is changed %ld -> %ld\n", + stream_name, size, rsize); + } + err = snd_pcm_hw_params(handle, hw_params); + if (err < 0) { + ERR("cannot setup hw params for %s: %s\n", stream_name, snd_strerror(err)); + return err; + } + err = snd_pcm_prepare(handle); + if (err < 0) { + ERR("cannot prepare %s: %s\n", stream_name, snd_strerror(err)); + return err; + } + snd_pcm_hw_params_free(hw_params); + + err = snd_pcm_sw_params_malloc(&sw_params); + if (err < 0) { + ERR("cannot alloc sw params for %s: %s\n", stream_name, snd_strerror(err)); + return err; + } + err = snd_pcm_sw_params_current(handle,sw_params); + if (err < 0) { + ERR("cannot get sw params for %s: %s\n", stream_name, snd_strerror(err)); + return err; + } + err = snd_pcm_sw_params_set_start_threshold(handle, sw_params, INT_MAX); + if (err < 0) { + ERR("cannot set start threshold for %s: %s\n", stream_name, snd_strerror(err)); + return err; + } + err = snd_pcm_sw_params_set_avail_min(handle, sw_params, 4); + if (err < 0) { + ERR("cannot set avail min for %s: %s\n", stream_name, snd_strerror(err)); + return err; + } + err = snd_pcm_sw_params_set_xfer_align(handle, sw_params, 4); + if (err < 0) { + ERR("cannot set align for %s: %s\n", stream_name, snd_strerror(err)); + return err; + } + err = snd_pcm_sw_params(handle, sw_params); + if (err < 0) { + ERR("cannot set sw params for %s: %s\n", stream_name, snd_strerror(err)); + return err; + } + snd_pcm_sw_params_free(sw_params); + + if(modem_debug_level > 0) + snd_pcm_dump(handle,dbg_out); + return 0; +} + +static int alsa_start (struct modem *m) +{ + struct device_struct *dev = m->dev_data; + int err, len; + DBG("alsa_start...\n"); + dev->period = m->frag; + dev->buf_periods = use_short_buffer ? SHORT_BUFFER_PERIODS : BUFFER_PERIODS; + err = setup_stream(dev->phandle, m, "playback"); + if(err < 0) + return err; + err = setup_stream(dev->chandle, m, "capture"); + if(err < 0) + return err; + dev->delay = 0; + len = use_short_buffer ? dev->period * dev->buf_periods : 384; + DBG("startup write: %d...\n",len); + err = snd_pcm_format_set_silence(SND_PCM_FORMAT_S16_LE, outbuf, len); + if(err < 0) { + ERR("silence error\n"); + return err; + } + + err = snd_pcm_writei(dev->phandle,outbuf,len); + if(err < 0) { + ERR("startup write error\n"); + return err; + } + dev->delay = err; + dev->delay += INTERNAL_DELAY; /* <-- fixme: delay detection is needed */ + err = snd_pcm_link(dev->chandle, dev->phandle); + if(err < 0) { + ERR("snd_pcm_link error: %s\n", snd_strerror(err)); + return err; + } + err = snd_pcm_start(dev->chandle); + if(err < 0) { + ERR("snd_pcm_start error: %s\n", snd_strerror(err)); + return err; + } + dev->started = 1; + return 0; +} + +static int alsa_stop (struct modem *m) +{ + struct device_struct *dev = m->dev_data; + DBG("alsa_stop...\n"); + dev->started = 0; + snd_pcm_drop(dev->chandle); + snd_pcm_nonblock(dev->phandle, 0); + snd_pcm_drain(dev->phandle); + snd_pcm_nonblock(dev->phandle, 1); + snd_pcm_unlink(dev->chandle); + snd_pcm_hw_free(dev->phandle); + snd_pcm_hw_free(dev->chandle); + return 0; +} + +static int alsa_ioctl(struct modem *m, unsigned int cmd, unsigned long arg) +{ + /* TODO */ + struct device_struct *dev = m->dev_data; + DBG("alsa_ioctl: cmd %x, arg %lx...\n",cmd,arg); + switch(cmd) { + case MDMCTL_CAPABILITIES: + return -EINVAL; + case MDMCTL_HOOKSTATE: + return (dev->hook_off_elem) ? + snd_mixer_selem_set_playback_switch_all( + dev->hook_off_elem, + (arg == MODEM_HOOK_OFF) ) : 0 ; + case MDMCTL_SPEAKERVOL: + return (dev->speaker_elem) ? + snd_mixer_selem_set_playback_volume_all( + dev->speaker_elem, arg) : 0 ; + case MDMCTL_CODECTYPE: + return CODEC_SILABS; + case MDMCTL_IODELAY: + DBG("delay = %d\n", dev->delay); + return dev->delay; + default: + return 0; + } + return -EINVAL; +} + + +struct modem_driver alsa_modem_driver = { + .name = "alsa modem driver", + .start = alsa_start, + .stop = alsa_stop, + .ioctl = alsa_ioctl, +}; + + +#endif + + +/* + * 'driver' stuff + * + */ + +static int modemap_start (struct modem *m) +{ + struct device_struct *dev = m->dev_data; + int ret; + DBG("modemap_start...\n"); + dev->delay = 0; + ret = ioctl(dev->fd,100000+MDMCTL_START,0); + if (ret < 0) + return ret; + ret = 192*2; + memset(outbuf, 0 , ret); + ret = write(dev->fd, outbuf, ret); + if (ret < 0) { + ioctl(dev->fd,100000+MDMCTL_STOP,0); + return ret; + } + dev->delay = ret/2; + return 0; +} + +static int modemap_stop (struct modem *m) +{ + struct device_struct *dev = m->dev_data; + DBG("modemap_stop...\n"); + return ioctl(dev->fd,100000+MDMCTL_STOP,0); +} + +static int modemap_ioctl(struct modem *m, unsigned int cmd, unsigned long arg) +{ + struct device_struct *dev = m->dev_data; + int ret; + DBG("modemap_ioctl: cmd %x, arg %lx...\n",cmd,arg); + if (cmd == MDMCTL_SETFRAG) + arg <<= MFMT_SHIFT(m->format); + ret = ioctl(dev->fd,cmd+100000,&arg); + if (cmd == MDMCTL_IODELAY && ret > 0) { + ret >>= MFMT_SHIFT(m->format); + ret += dev->delay; + } + return ret; +} + + + +struct modem_driver mdm_modem_driver = { + .name = "modemap driver", + .start = modemap_start, + .stop = modemap_stop, + .ioctl = modemap_ioctl, +}; + +static int socket_start (struct modem *m) +{ + struct device_struct *dev = m->dev_data; + int ret; + DBG("socket_start...\n"); + + int sockets[2]; + + if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) { + perror("socketpair"); + exit(-1); + } + + pid_t pid = fork(); + if (pid == -1) { + perror("fork"); + exit(-1); + } + if (pid == 0) { // child + char str[16]; + snprintf(str,sizeof(str),"%d",sockets[0]); + close(sockets[1]); + execl(modem_exec,modem_exec,m->dial_string,str,NULL); + } else { + close(sockets[0]); + dev->fd = sockets[1]; + dev->delay = 0; + ret = 192*2; + memset(outbuf, 0 , ret); + ret = write(dev->fd, outbuf, ret); + DBG("done delay thing\n"); + if (ret < 0) { + close(dev->fd); + dev->fd = -1; + return ret; + } + dev->delay = ret/2; + } + return 0; +} + +static int socket_stop (struct modem *m) +{ + struct device_struct *dev = m->dev_data; + DBG("socket_stop...\n"); + close(dev->fd); + dev->fd = -1; + wait(NULL); // for exec'ed child + return 0; +} + +static int socket_ioctl(struct modem *m, unsigned int cmd, unsigned long arg) +{ + //struct device_struct *dev = m->dev_data; + int ret = 0; + DBG("socket_ioctl: cmd %x, arg %lx...\n",cmd,arg); + if (cmd == MDMCTL_SETFRAG) + arg <<= MFMT_SHIFT(m->format); + + switch (cmd) { + case MDMCTL_CAPABILITIES: + ret = -EINVAL; + break; + case MDMCTL_CODECTYPE: + ret = 4; // CODEC_STLC7550; XXX this worked fine as 0 (CODEC_UNKNOWN)... + break; + case MDMCTL_IODELAY: // kernel module returns s->delay + ST7554_HW_IODELAY (48) + ret = 0;//48 >> MFMT_SHIFT(m->format); + //ret += dev->delay; + //DBG("%d %d %d %d",m->format,MFMT_SHIFT(m->format),dev->delay,ret); + break; + case MDMCTL_HOOKSTATE: // 0 = on, 1 = off + case MDMCTL_SPEED: // sample rate (9600) + case MDMCTL_GETFMTS: + case MDMCTL_SETFMT: + case MDMCTL_SETFRAGMENT: // (30) + case MDMCTL_START: + case MDMCTL_STOP: + case MDMCTL_GETSTAT: + ret = 0; + break; + default: + return -ENOIOCTLCMD; + } + + DBG("socket_ioctl: returning %x\n",ret); + return ret; +} + +struct modem_driver socket_modem_driver = { + .name = "socket driver", + .start = socket_start, + .stop = socket_stop, + .ioctl = socket_ioctl, +}; + +static int mdm_device_read(struct device_struct *dev, char *buf, int size) +{ + int ret = read(dev->fd, buf, size*2); + if (ret > 0) ret /= 2; + return ret; +} + +static int mdm_device_write(struct device_struct *dev, const char *buf, int size) +{ + int ret = write(dev->fd, buf, size*2); + if (ret > 0) ret /= 2; + return ret; +} +#if 0 +static int mdm_device_setup(struct device_struct *dev, const char *dev_name) +{ + struct stat stbuf; + int ret, fd; + memset(dev,0,sizeof(*dev)); + ret = stat(dev_name,&stbuf); + if(ret) { + ERR("mdm setup: cannot stat `%s': %s\n", dev_name, strerror(errno)); + return -1; + } + if(!S_ISCHR(stbuf.st_mode)) { + ERR("mdm setup: not char device `%s'\n", dev_name); + return -1; + } + /* device stuff */ + fd = open(dev_name,O_RDWR); + if(fd < 0) { + ERR("mdm setup: cannot open dev `%s': %s\n",dev_name,strerror(errno)); + return -1; + } + dev->fd = fd; + dev->num = minor(stbuf.st_rdev); + return 0; +} +#endif + +static int mdm_device_release(struct device_struct *dev) +{ + close(dev->fd); + return 0; +} + +static int socket_device_setup(struct device_struct *dev, const char *dev_name) +{ + memset(dev,0,sizeof(*dev)); + return 0; +} + + +/* + * PTY creation (or re-creation) + * + */ + +static char link_name[PATH_MAX]; + +int create_pty(struct modem *m) +{ + struct termios termios; + const char *pty_name; + int pty, ret; + + if(m->pty) + close(m->pty); + + pty = getpt(); + if (pty < 0 || grantpt(pty) < 0 || unlockpt(pty) < 0) { + ERR("getpt: %s\n", strerror(errno)); + return -1; + } + + if(m->pty) { + termios = m->termios; + } + else { + ret = tcgetattr(pty, &termios); + /* non canonical raw tty */ + cfmakeraw(&termios); + cfsetispeed(&termios, B115200); + cfsetospeed(&termios, B115200); + } + + ret = tcsetattr(pty, TCSANOW, &termios); + if (ret) { + ERR("tcsetattr: %s\n",strerror(errno)); + return -1; + } + + fcntl(pty,F_SETFL,O_NONBLOCK); + + pty_name = ptsname(pty); + + m->pty = pty; + m->pty_name = pty_name; + + modem_update_termios(m,&termios); + + if(modem_group && *modem_group) { + struct group *grp = getgrnam(modem_group); + if(!grp) { + ERR("cannot find group '%s': %s\n", modem_group, + strerror(errno)); + } + else { + ret = chown(pty_name, -1, grp->gr_gid); + if(ret < 0) { + ERR("cannot chown '%s' to ':%s': %s\n", + pty_name, modem_group, strerror(errno)); + } + } + } + + ret = chmod(pty_name, modem_perm); + if (ret < 0) { + ERR("cannot chmod '%s' to %o: %s\n", + pty_name, modem_perm, strerror(errno)); + } + + if(*link_name) { + unlink(link_name); + if(symlink(pty_name,link_name)) { + ERR("cannot create symbolink link `%s' -> `%s': %s\n", + link_name,pty_name,strerror(errno)); + *link_name = '\0'; + } + else { + INFO("symbolic link `%s' -> `%s' created.\n", + link_name, pty_name); + } + } + + return 0; +} + + +/* + * main run cycle + * + */ + +static int (*device_setup)(struct device_struct *dev, const char *dev_name); +static int (*device_release)(struct device_struct *dev); +static int (*device_read)(struct device_struct *dev, char *buf, int size); +static int (*device_write)(struct device_struct *dev, const char *buf, int size); +static struct modem_driver *modem_driver; + +static volatile sig_atomic_t keep_running = 1; + +void mark_termination(int signum) +{ + DBG("signal %d: mark termination.\n",signum); + keep_running = 0; +} + + +static int modem_run(struct modem *m, struct device_struct *dev) +{ + struct timeval tmo; + fd_set rset,eset; + struct termios termios; + unsigned pty_closed = 0, close_count = 0; + int max_fd; + int ret, count; + void *in; + + while(keep_running) { + + if(m->event) + modem_event(m); + +#ifdef MODEM_CONFIG_RING_DETECTOR + if(ring_detector && !m->started) + modem_ring_detector_start(m); +#endif + + tmo.tv_sec = 1; + tmo.tv_usec= 0; + FD_ZERO(&rset); + FD_ZERO(&eset); + if(m->started) + FD_SET(dev->fd,&rset); + + FD_SET(dev->fd,&eset); + max_fd = dev->fd; + + if(pty_closed && close_count > 0) { + if(!m->started || + ++close_count > CLOSE_COUNT_MAX ) + close_count = 0; + } + else if(m->xmit.size - m->xmit.count > 0) { + FD_SET(m->pty,&rset); + if(m->pty > max_fd) max_fd = m->pty; + } + + ret = select(max_fd + 1,&rset,NULL,&eset,&tmo); + + if (ret < 0) { + if (errno == EINTR) + continue; + ERR("select: %s\n",strerror(errno)); + return ret; + } + + if ( ret == 0 ) + continue; + + if(FD_ISSET(dev->fd, &eset)) { + unsigned stat; + DBG("dev exception...\n"); +#ifdef SUPPORT_ALSA + if(use_alsa) { + DBG("dev exception...\n"); + continue; + } +#endif + ret = ioctl(dev->fd,100000+MDMCTL_GETSTAT,&stat); + if(ret < 0) { + ERR("dev ioctl: %s\n",strerror(errno)); + return -1; + } + if(stat&MDMSTAT_ERROR) modem_error(m); + if(stat&MDMSTAT_RING) modem_ring(m); + continue; + } + if(FD_ISSET(dev->fd, &rset)) { + count = device_read(dev,inbuf,sizeof(inbuf)/2); + if(count <= 0) { + if (errno == ECONNRESET) { + DBG("lost connection to child socket process\n"); + } else { + ERR("dev read: %s\n",strerror(errno)); + } + // hack to force hangup + modem_hangup(m); // sets sample_timer_func to run_modem_stop() + m->sample_timer_func(m); + m->sample_timer = 0; + m->sample_timer_func = NULL; + continue; + } + in = inbuf; + if(m->update_delay < 0) { + if ( -m->update_delay >= count) { + DBG("change delay -%d...\n", count); + dev->delay -= count; + m->update_delay += count; + continue; + } + DBG("change delay %d...\n", m->update_delay); + in -= m->update_delay; + count += m->update_delay; + dev->delay += m->update_delay; + m->update_delay = 0; + } + + modem_process(m,inbuf,outbuf,count); + if (dev->fd == -1) { + DBG("closed connection to child socket process\n"); + continue; + } + count = device_write(dev,outbuf,count); + if(count < 0) { + ERR("dev write: %s\n",strerror(errno)); + return -1; + } + else if (count == 0) { + DBG("dev write = 0\n"); + } + + if(m->update_delay > 0) { + DBG("change delay +%d...\n", m->update_delay); + memset(outbuf, 0, m->update_delay*2); + count = device_write(dev,outbuf,m->update_delay); + if(count < 0) { + ERR("dev write: %s\n",strerror(errno)); + return -1; + } + if(count != m->update_delay) { + ERR("cannot update delay: %d instead of %d.\n", + count, m->update_delay); + return -1; + } + dev->delay += m->update_delay; + m->update_delay = 0; + } + } + if(FD_ISSET(m->pty,&rset)) { + /* check termios */ + tcgetattr(m->pty,&termios); + if(memcmp(&termios,&m->termios,sizeof(termios))) { + DBG("termios changed.\n"); + modem_update_termios(m,&termios); + } + /* read data */ + count = m->xmit.size - m->xmit.count; + if(count == 0) + continue; + if(count > sizeof(inbuf)) + count = sizeof(inbuf); + count = read(m->pty,inbuf,count); + if(count < 0) { + if(errno == EAGAIN) { + DBG("pty read, errno = EAGAIN\n"); + continue; + } + if(errno == EIO) { /* closed */ + if(!pty_closed) { + DBG("pty closed.\n"); + if(termios.c_cflag&HUPCL) { + modem_hangup(m); + /* re-create PTM - simulate hangup */ + ret = create_pty(m); + if (ret < 0) { + ERR("cannot re-create PTY.\n"); + return -1; + } + } + else + pty_closed = 1; + } + // DBG("pty read, errno = EIO\n"); + close_count = 1; + continue; + } + else + ERR("pty read: %s\n",strerror(errno)); + return -1; + } + else if (count == 0) { + DBG("pty read = 0\n"); + } + pty_closed = 0; + count = modem_write(m,inbuf,count); + if(count < 0) { + ERR("modem_write failed.\n"); + return -1; + } + } + } + + return 0; +} + + +int modem_main(const char *dev_name) +{ + char path_name[PATH_MAX]; + struct device_struct device; + struct modem *m; + int pty; + int ret = 0; + struct passwd *pwd; + + modem_debug_init(basename(dev_name)); + + ret = device_setup(&device, dev_name); + if (ret) { + ERR("cannot setup device `%s'\n", dev_name); + exit(-1); + } + + dp_dummy_init(); + dp_sinus_init(); + prop_dp_init(); + modem_timer_init(); + + sprintf(link_name,"/dev/ttySL%d", device.num); + + m = modem_create(modem_driver,basename(dev_name)); + m->name = basename(dev_name); + m->dev_data = &device; + m->dev_name = dev_name; + + ret = create_pty(m); + if(ret < 0) { + ERR("cannot create PTY.\n"); + exit(-1); + } + + INFO("modem `%s' created. TTY is `%s'\n", + m->name, m->pty_name); + + sprintf(path_name,"/var/lib/slmodem/data.%s",basename(dev_name)); + datafile_load_info(path_name,&m->dsp_info); + + if (need_realtime) { + struct sched_param prm; + if(mlockall(MCL_CURRENT|MCL_FUTURE)) { + ERR("mlockall: %s\n",strerror(errno)); + } + prm.sched_priority = sched_get_priority_max(SCHED_FIFO); + if(sched_setscheduler(0,SCHED_FIFO,&prm)) { + ERR("sched_setscheduler: %s\n",strerror(errno)); + } + DBG("rt applyed: SCHED_FIFO, pri %d\n",prm.sched_priority); + } + + signal(SIGINT, mark_termination); + signal(SIGTERM, mark_termination); + +#ifdef SLMODEMD_USER + if (need_realtime) { + struct rlimit limit; + if (getrlimit(RLIMIT_MEMLOCK, &limit)) { + ERR("getrlimit failed to read RLIMIT_MEMLOCK\n"); + exit(-1); + } + if (limit.rlim_cur != RLIM_INFINITY && + limit.rlim_cur < LOCKED_MEM_MIN) { + ERR("locked memory limit too low:\n"); + ERR("need %lu bytes, have %lu bytes\n", LOCKED_MEM_MIN, + (unsigned long)limit.rlim_cur); + ERR("try 'ulimit -l %lu'\n", LOCKED_MEM_MIN_KB); + exit(-1); + } + } + + pwd = getpwnam(SLMODEMD_USER); + if (!pwd) { + ERR("getpwnam " SLMODEMD_USER ": %s\n",strerror(errno)); + exit(-1); + } + + ret = (setgroups(1,&pwd->pw_gid) || + setgid(pwd->pw_gid) || + setuid(pwd->pw_uid)); + if (ret) { + ERR("setgroups or setgid %ld or setuid %ld failed: %s\n", + (long)pwd->pw_gid,(long)pwd->pw_uid,strerror(errno)); + exit(-1); + } + + if (setuid(0) != -1) { + ERR("setuid 0 succeeded after dropping privileges!\n"); + exit(-1); + } + DBG("dropped privileges to %ld.%ld\n", + (long)pwd->pw_gid,(long)pwd->pw_uid); +#endif + + INFO("Use `%s' as modem device, Ctrl+C for termination.\n", + *link_name ? link_name : m->pty_name); + + /* main loop here */ + ret = modem_run(m,&device); + + datafile_save_info(path_name,&m->dsp_info); + + pty = m->pty; + modem_delete(m); + + usleep(100000); + close(pty); + if(*link_name) + unlink(link_name); + + dp_dummy_exit(); + dp_sinus_exit(); + prop_dp_exit(); + + device_release(&device); + + modem_debug_exit(); + + exit(ret); + return 0; +} + + + + +int main(int argc, char *argv[]) +{ + extern void modem_cmdline(int argc, char *argv[]); + int ret; + modem_cmdline(argc,argv); + if(!modem_dev_name) modem_dev_name = "/dev/slamr0"; + + device_setup = socket_device_setup; + device_release = mdm_device_release; + device_read = mdm_device_read; + device_write = mdm_device_write; + modem_driver = &socket_modem_driver; + +#ifdef SUPPORT_ALSA + if(use_alsa) { + device_setup = alsa_device_setup; + device_release = alsa_device_release; + device_read = alsa_device_read; + device_write = alsa_device_write; + modem_driver = &alsa_modem_driver; + } +#endif + + ret = modem_main(modem_dev_name); + return ret; +} diff --git a/slmodemd/modem_pack.c b/slmodemd/modem_pack.c new file mode 100644 index 0000000..7156f82 --- /dev/null +++ b/slmodemd/modem_pack.c @@ -0,0 +1,634 @@ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem_pack.c -- modem packer module. + * + * Author: Sasha K (sashak@smlink.com) + * + * + */ + +#include +#include + +#define PACK_DBG(fmt,arg...) dprintf("%s: " fmt , m->name , ##arg) +#define PACK_ERR(fmt,arg...) eprintf("%s: " fmt , m->name , ##arg) + +/* HDLC definitions */ + +#define HDLC_FLAG 0x7e +#define HDLC_ESCAPE (0x1f<<3) + + +/* bit ordering (reverse) table */ +static const u8 _ordered[] = { + 0x0,0x8,0x4,0xc,0x2,0xa,0x6,0xe, + 0x1,0x9,0x5,0xd,0x3,0xb,0x7,0xf}; +#define REVERSE_BITS(c) { (c) = _ordered[(c)&0xf]<<4 | _ordered[(c)>>4] ; } + + +/* + * Async packer + * + */ + +#define START_BIT 0 +#define STOP_BIT 1 +#if 0 +#define STOP_BITS(p) ((p)->stop_bits) +#define DATA_SIZE(p) ((p)->data_bits) +#define CHAR_SIZE(p) ((p)->char_size) +#define CHAR_DATA(p,ch) ( ( ~(0x1<<(CHAR_SIZE(p)-1)) & \ + ((ch)<<(p)->stop_bits) ) | \ + ((0x1<<(p)->stop_bits)-1) ) +#else +#define STOP_BITS(p) 1 +#define DATA_SIZE(p) 8 +#define CHAR_SIZE(p) 10 +#define CHAR_DATA(p,ch) (((ch)<<1)|0x1) +#endif + +int modem_async_get_bits(struct modem *m, int nbits, u8 *bit_buf, int bit_cnt) +{ + struct bits_state *s = &m->pack; + int ret = 0; + u8 ch; + do { + /* fill bits */ + while ( bit_cnt > 0 && s->bit >= nbits) { + *bit_buf++ = (s->data>>(s->bit-nbits)); + s->bit -= nbits; + ret ++; + bit_cnt--; + } + if (bit_cnt <= 0) + break; + /* get char */ + if (!m->get_chars || m->get_chars(m, (char*)&ch, 1) != 1) + break; + REVERSE_BITS(ch); + s->data <<= CHAR_SIZE(m); + s->data |= CHAR_DATA(m,ch); + s->bit += CHAR_SIZE(m); + } while (1); + if (s->bit && bit_cnt > 0) { + /* left data + stops */ + *bit_buf++ = (s->data<<(nbits-s->bit))|((0x1<<(nbits-s->bit))-1); + ret ++; + bit_cnt--; + s->bit = 0; + } +#if 0 + memcpy(bit_buf,(1< 0) { + /* fill stops */ + *bit_buf++ = (1<unpack; + int ret = 0; + u8 ch; + while(bit_cnt > 0) { + s->data<<= nbits; + s->data |= *bit_buf++ & ((0x1<bit += nbits; + bit_cnt --; + ret++; + while(s->bit && s->data&(0x1<<(s->bit-1))) /* stop bit */ + s->bit--; + while (s->bit >= CHAR_SIZE(m)) { + ch = s->data >> + (s->bit-(CHAR_SIZE(m)-STOP_BITS(m))); + s->bit-= CHAR_SIZE(m); + REVERSE_BITS(ch); + if (m->put_chars) + m->put_chars(m,(const char*)&ch,1); + } + } + return ret; +} + +void modem_async_start(struct modem *m) +{ + m->pack.bit = m->unpack.bit = 0; + m->pack.data = m->unpack.data = 0; + m->bit_timer_func = NULL; + m->bit_timer = 0; +} + + +/* + * Packer detector + * + */ + +/* + * Detection phase description. + * originator - transmits ODPs until T400 timer is expired + * or until ADP is received. + * + * answer - transmits marks(1) until: detect phase termination, + * ODP receipt - send at least 10 ADPs, + * detection of start protocol phase (continuous flags). + * + * + */ + +/* ODP: 0100010001 11111111 0100010011 11111111 */ +#define ODP0 0x88 +#define ODP1 0x89 +/* ADP v42: 0101000101 11111111 0110000101 11111111 */ +/* ADP v14: 0101000101 11111111 0000000001 11111111 */ +#define ADP0 0xa2 +#define ADP1_V14 0x00 +#define ADP1_V42 0xc2 +#define ADP1 ADP1_V42 + +#define MIN_RX_PATTERNS 2 +#define MAX_TX_PATTERNS 16 +#define PATTERN_SIZE 36 + +#define FILL_PATTERN_ODP(pat) { (pat)[0]=ODP0 ; (pat)[1]=ODP1; } +#define FILL_PATTERN_ADP(pat) { (pat)[0]=ADP0 ; (pat)[1]=ADP1; } + + +static void detector_start(struct modem *m) +{ + PACK_DBG("detector start...\n"); + m->packer.detector.tx_count = 1; +} + +static void detector_finish(struct modem *m) +{ + PACK_DBG("detector finished.\n"); + // fixme: modem update config + m->cfg.ec = m->packer.detector.ec_enable; + modem_update_status(m,STATUS_PACK_LINK); +} + +int modem_detector_get_bits(struct modem *m, int nbits, u8 *bit_buf, int bit_cnt) +{ + struct bits_state *s = &m->pack; + struct detect_state *d = &m->packer.detector; + int ret = 0; + do { + /* fill bits */ + while ( bit_cnt > 0 && s->bit >= nbits) { + *bit_buf++ = (s->data>>(s->bit-nbits)); + s->bit -= nbits; + ret ++; + bit_cnt--; + } + if (bit_cnt <= 0) + break; +#if 0 + s->data <<= 18; + s->data |= (0x1ff<<9)|(d->tx_pattern[d->tx_count++%2]); + s->bit += 18; +#else + /* get char */ + s->data <<= 9; + s->data |= 0x1ff; + s->bit += 9; + if (d->tx_count > 0) { + s->data <<= 9; + s->data |= d->tx_pattern[d->tx_count++%2]; + s->bit += 9; + } +#endif + } while (1); + return ret; +} + + +int modem_detector_put_bits(struct modem *m, int nbits, u8 *bit_buf, int bit_cnt) +{ + struct bits_state *s = &m->unpack; + struct detect_state *d = &m->packer.detector; + int ret = 0; + u8 ch; + while(bit_cnt > 0) { + s->data<<= nbits; + s->data |= *bit_buf++ & ((0x1<bit += nbits; + bit_cnt --; + ret++; + while(s->bit && s->data&(0x1<<(s->bit-1))) /* skip marks */ + s->bit--; + while (s->bit >= 10 ) { + ch = s->data >> (s->bit-9); + s->bit-= 10; + PACK_DBG("rx pattern: 0x%02x.\n",ch); + if (ch == HDLC_FLAG) { + PACK_DBG("hdlc flag detected.\n"); + d->ec_enable = 1; + m->bit_timer_func = detector_finish; + m->bit_timer = PATTERN_SIZE; + continue; + } + if (!d->rx_count) { + d->rx_count = (ch == d->rx_pattern[0]); + continue; + } + if (d->rx_count >= 2) + continue; + switch(ch) { + case ODP1: + //PACK_DBG("rx ODP.\n"); + if (!m->caller) { + /* start replay ADP and leave detector */ + d->tx_count = 1; + d->rx_count = 2; + d->ec_enable = 1; + m->bit_timer_func = detector_finish; + m->bit_timer = MAX_TX_PATTERNS*PATTERN_SIZE; + } + else + d->rx_count = 0; + break; + case ADP1_V14: + //PACK_DBG("rx ADP non v42.\n"); + d->rx_count = 2; + d->ec_enable = 0; + m->bit_timer_func = detector_finish; + m->bit_timer = PATTERN_SIZE; + break; + case ADP1_V42: + //PACK_DBG("rx ADP v42.\n"); + m->cfg.ec = 1; + d->rx_count = 2; + d->ec_enable = 1; + m->bit_timer_func = detector_finish; + m->bit_timer = PATTERN_SIZE; + break; + default: + d->rx_count = 0; + break; + } + } + } + return ret; +} + +void modem_detector_start(struct modem *m) { + struct detect_state *d = &m->packer.detector; + int rate = 28800 ; // fixme: use real bit rate from modem + d->tx_count = 0; /* mute transmitter */ + d->rx_count = 0; + d->ec_enable = 0; + if (m->caller) { + FILL_PATTERN_ODP(d->tx_pattern); + FILL_PATTERN_ADP(d->rx_pattern); + m->bit_timer_func = detector_start; + m->bit_timer = 64*8 ; + } + else { + FILL_PATTERN_ADP(d->tx_pattern); + FILL_PATTERN_ODP(d->rx_pattern); + m->bit_timer_func = detector_finish; + m->bit_timer = rate*3/4; /* T400 timeout */ + } + m->pack.bit = m->unpack.bit = 0; + m->pack.data = m->unpack.data = 0; +} + + +/* + * HDLC packer + * + */ + + +/* static data */ + +/* fcs16 table */ +static const +u16 fcs16_tab[256] = { + 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, + 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, + 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, + 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, + 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, + 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, + 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, + 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, + 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, + 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, + 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, + 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, + 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, + 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, + 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, + 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, + 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, + 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, + 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, + 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, + 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, + 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, + 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, + 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, + 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, + 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, + 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, + 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, + 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, + 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, + 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, + 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78 +}; + +#define fcstab fcs16_tab +#define INIT_FCS16 0xffff /* Initial FCS16 value */ +#define GOOD_FCS16 0xf0b8 /* Good final FCS16 value */ + +#define GET_FCS(fcs,c) (((fcs) >> 8) ^ fcstab[((fcs) ^ (c)) & 0xff]) +#define INIT_FCS INIT_FCS16 /* Initial FCS value */ +#define GOOD_FCS GOOD_FCS16 /* Good final FCS value */ + + +/* hdlc bit generators */ + +#define HDLC_PUT_BYTE { \ + for( i = 0 ; i < 8 ; i++ ) { \ + s->data<<=1; \ + s->bit++; \ + if(in&0x1) { \ + h->tx_ones++; \ + s->data |= 0x1; \ + if (h->tx_ones==5) { \ + s->data<<=1; \ + s->bit++; \ + h->tx_ones = 0; \ + } \ + } \ + else { \ + h->tx_ones = 0; \ + } \ + in>>=1; \ + } } + + +int modem_hdlc_get_bits(struct modem *m, int nbits, + u8 *bit_buf, int bit_cnt) +{ + struct hdlc_state *h = &m->packer.hdlc; + register struct bits_state *s = &m->pack; + register int i, ret = 0; + register u8 in, mask = ((1< 0 && s->bit >= nbits) { + *bit_buf++ = (s->data>>(s->bit-nbits))&mask; + s->bit -= nbits; + ret ++; + bit_cnt--; + } + if (bit_cnt <= 0) + break; + if (!h->tx_frame) { + s->data <<= 8; + s->data |= HDLC_FLAG; + s->bit += 8; + if (h->get_tx_frame && + (h->tx_frame = h->get_tx_frame(h->framer))) { + h->tx_frame->fcs = INIT_FCS; + h->tx_frame->count = 0; + } + } + else if(h->tx_frame->count == h->tx_frame->size) { + /* end frame */ + /* put fcs */ + h->tx_frame->fcs ^= 0xffff; + in = h->tx_frame->fcs&0xff; + HDLC_PUT_BYTE; + in = (h->tx_frame->fcs>>8)&0xff; + HDLC_PUT_BYTE; + h->tx_ones = 0; + /* frame complete callback */ + if (h->tx_complete) + h->tx_complete(h->framer, h->tx_frame); + /* reset tx frame */ + h->tx_frame = NULL; + /* put flags will done automatically */ + } + else { + in = h->tx_frame->buf[h->tx_frame->count]; + h->tx_frame->count++; + /* fixme: in order to speed up + fcs calc: copy it to local var */ + h->tx_frame->fcs = GET_FCS(h->tx_frame->fcs,in); + HDLC_PUT_BYTE; + } + } while (1); + return ret; +} + + +int modem_hdlc_put_bits(struct modem *m, int nbits, + u8 *bit_buf, int bit_cnt) +{ + struct hdlc_state *h = &m->packer.hdlc; + register struct bits_state *s = &m->unpack; + register int ret = 0; + register int i; + register u8 in, out, mask = ((0x1< 0) { + s->data <<= nbits; + s->data |= *bit_buf++ & mask; + s->bit += nbits; + bit_cnt--; + ret++; + + /* 8 char, 2 possible escapes, +8 estimated flag */ + if ( s->bit < 8 + 8 + 2) + continue; + + out = 0; + // fixme: probably may be optimized by handling whole + // byte with masking + /* mask = 0x80; */ + for ( i=0 ; i<8 ; i++ ) { + in = s->data >> (s->bit-8) ; + /* flag: finish frame */ + if (in == HDLC_FLAG) { + /* end of frame */; + if ( !h->rx_frame->count ) { + //HDLC_DBG("empty.\n"); + } + /* check frame for errors */ + else if (h->rx_error) { + PACK_DBG("hdlc frame error.\n"); + } + else if (i) { + PACK_DBG("hdlc frame integrity error.\n"); + } +#if 1 + else if ( h->rx_frame->count < 3 ) { +#else + else if ( h->rx_frame->count < 4 ) { +#endif + PACK_DBG("hdlc frame size error.\n"); + } + else if ( h->rx_frame->fcs != GOOD_FCS ) { + PACK_DBG("hdlc frame fcs error.\n"); + } + /* good frame */ + else if ( h->rx_complete ) { + /* reduce fcs size */ + h->rx_frame->count -= 2; + h->rx_complete(h->framer,h->rx_frame); + } + s->bit -= 8; + h->rx_ones = 0; + h->rx_error = 0; + h->rx_frame->fcs = INIT_FCS; + h->rx_frame->count = 0; + break; + } + else if(h->rx_error) { + s->bit--; + continue; + } + /* put reversed data bit */ + out >>= 1; + if (in&0x80) { + out |= 0x80; + h->rx_ones++; + /* escape or idle reached */ + if (h->rx_ones == 5) { + if (in&0x40) { + h->rx_error++; + h->rx_frame->count = 0; + } + s->bit--; + h->rx_ones = 0; + } + } + else + h->rx_ones = 0; + s->bit--; + } + + /* finish char */ + if(i==8 && !h->rx_error) { + if (h->rx_frame->count < h->rx_frame->size) { + h->rx_frame->buf[h->rx_frame->count] = out; + h->rx_frame->count++; + h->rx_frame->fcs = GET_FCS(h->rx_frame->fcs,out); + } + else { /* overflow */ + PACK_DBG("hdlc rx frame overflow.\n"); + h->rx_error++; + h->rx_frame->count = 0; + } + } + } + + return ret; +} + + +void modem_hdlc_start(struct modem *m) +{ + struct hdlc_state *h = &m->packer.hdlc; + PACK_DBG("hdlc_start...\n"); + memset(h,0,sizeof(*h)); + /* wait for flag to clear rx error state */ + h->rx_error = 1; + /* rx frame */ + h->rx_frame = &h->_rx_frame; + h->rx_frame->buf = h->_rx_buf; + h->rx_frame->count= 0; + h->rx_frame->size = sizeof(h->_rx_buf); + h->rx_frame->fcs = INIT_FCS; + /* tx frame */ + h->tx_frame = 0; + + m->pack.bit = m->unpack.bit = 0; + m->pack.data = m->unpack.data = 0; + m->bit_timer_func = NULL; + m->bit_timer = 0; +} + +#if 0 +// temp stupid things +static struct hdlc_frame *tmp_get_frame(void *framer) +{ + frame_t *f; + struct modem *m = framer; + if(m->get_chars) { + f = &m->packer.hdlc._tx_frame; + f->buf = m->packer.hdlc._tx_buf; + f->size = m->get_chars(m,f->buf,sizeof(m->packer.hdlc._tx_buf)); + if(f->size <= 0) { + return NULL; + } + PACK_DBG("get frame: %d...\n",f->size); + return f; + } + return NULL; +} +static void tmp_put_frame(void *framer, frame_t *fr) +{ + struct modem *m = framer; + if(fr->count > 0 && m->put_chars) { + PACK_DBG("put frame: %d...\n",fr->count); + m->put_chars(m,fr->buf,fr->count); + } + return; +} + +void tmp_init(struct modem *m) +{ + m->packer.hdlc.get_tx_frame = tmp_get_frame; + m->packer.hdlc.rx_complete = tmp_put_frame; + m->packer.hdlc.framer = m; +} +#endif + + diff --git a/slmodemd/modem_param.c b/slmodemd/modem_param.c new file mode 100644 index 0000000..f34ac57 --- /dev/null +++ b/slmodemd/modem_param.c @@ -0,0 +1,207 @@ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem_param.c -- modem parameters access module. + * + * Author: Sasha K (sashak@smlink.com) + * + * + */ + + +#include +#include +#include + + + +/* param access services */ +long modem_get_sreg_param(struct modem *m,unsigned sreg_num) +{ + return modem_get_sreg(m,sreg_num); +} + +long modem_get_param(struct modem *m, unsigned param_name) +{ + int val; + switch (param_name) { + case MDMPRM_NONE: + break; + case MDMPRM_MIN_RATE: + return m->min_rate; + case MDMPRM_MAX_RATE: + return m->max_rate; + case MDMPRM_IODELAY: + return m->driver.ioctl(m,MDMCTL_IODELAY,0); + case MDMPRM_CODECTYPE: + val = m->driver.ioctl(m,MDMCTL_CODECTYPE,0); + if(val<0) + return CODEC_UNKNOWN; /* unknown */ + return val; + case MDMPRM_DIALSTR: + return (long)m->dial_string; + case MDMPRM_AUTOMODE: + return 0 /* MODEM_AUTOMODE(m)*/; + case MDMPRM_DPRUNTIME: + return (long)(m->dp_runtime); + case MDMPRM_DSPINFO: + return (long)(&m->dsp_info); +#ifdef MODEM_CONFIG_VOICE + case MDMPRM_VOICEINFO: + return (long)(&m->voice_info); +#endif + case MDMPRM_DP_ADDR: + return (long)(m->dp); + case GetPulseDialMakeTime: + return m->homolog->params->PulseDialMakeTime; + case GetPulseDialBreakTime: + return m->homolog->params->PulseDialBreakTime; + case GetPulseDialDigitPattern: + return m->homolog->params->PulseDialDigitPattern; + case GetDTMFHighToneLevel: + return m->homolog->params->DTMFHighToneLevel; + case GetDTMFDialSpeed: + return modem_get_sreg(m,SREG_DTMF_DURATION); + case GetMinBusyCadenceOnTime: + return m->homolog->params->MinBusyCadenceOnTime; + case GetMaxBusyCadenceOnTime: + return m->homolog->params->MaxBusyCadenceOnTime; + case GetBusyDetectionCyclesNumber: + return m->homolog->params->BusyDetectionCyclesNumber; + case GetMinBusyCadenceOffTime: + return m->homolog->params->MinBusyCadenceOffTime; + case GetMaxBusyCadenceOffTime: + return m->homolog->params->MaxBusyCadenceOffTime; + case GetCallingToneFlag: + return m->homolog->params->CallingToneFlag; + case GetHookFlashTime: +#if 0 + return modem_get_sreg(m,SREG_FLASH_TIMER); +#else + return m->homolog->params->HookFlashTime; +#endif + case GetBlindDialPause: + return modem_get_sreg(m,SREG_DIAL_TONE_WAIT_TIME); + case GetNoAnswerTimeOut: + return modem_get_sreg(m,SREG_WAIT_CARRIER_AFTER_DIAL); + case GetDialPauseTime: + return modem_get_sreg(m,SREG_DIAL_PAUSE_TIME); + case GetTransmitLevel: + return m->homolog->params->TransmitLevel; + case GetDialModifierValidation: + return m->homolog->params->DialModifierValidation; + case GetDialToneValidationTime: + return m->homolog->params->DialToneValidationTime; + case GetBusyToneDiffTime: + return 0; + case GetDTMFHighAndLowToneLevelDifference: + return m->homolog->params->DTMFHighAndLowToneLevelDifference; + case GetPulseDialingFlag: + return !modem_get_sreg(m,SREG_TONE_OR_PULSE); + case GetDialToneCallProgressFilterIndex: + return m->homolog->params->DialToneCallProgressFilterIndex; + case GetDialToneDetectionThreshold: + return m->homolog->params->DialToneDetectionThreshold; + case GetABCDDialingPermittedFlag: + return m->homolog->params->ABCDDialingPermittedFlag; + case GetComaPauseDurationLimit: + return m->homolog->params->ComaPauseDurationLimit; + case GetPulseAndToneDialInSameDialStringPermittedFlag: + return 0; + case GetBusyToneCallProgressFilterIndex: + return m->homolog->params->BusyToneCallProgressFilterIndex; + case GetPulseBetweenDigitsInterval: + return m->homolog->params->PulseBetweenDigitsInterval; + case GetDialToneWaitTime: + return modem_get_sreg(m,SREG_DIAL_TONE_WAIT_TIME); + case GetMinRingbackCadenceOnTime: + return m->homolog->params->MinRingbackCadenceOnTime; + case GetMaxRingbackCadenceOnTime: + return m->homolog->params->MaxRingbackCadenceOnTime; + case GetRingbackDetectionCyclesNumber: + return m->homolog->params->RingbackDetectionCyclesNumber; + case GetMinRingbackCadenceOffTime: + case GetMaxRingbackCadenceOffTime: + case GetRingbackToneCallProgressFilterIndex: + case GetMinCongestionCadenceOnTime: + case GetMaxCongestionCadenceOnTime: + case GetCongestionDetectionCyclesNumber: + case GetMinCongestionCadenceOffTime: + case GetMaxCongestionCadenceOffTime: + case GetCongestionToneCallProgressFilterIndex: + return 0; + case GetCallProgressSamplesBufferLength: + return m->homolog->params->CallProgressSamplesBufferLength; + case MustNoiseFilterBeApplied: + return m->homolog->params->MustNoiseFilterBeApplied; + case GetAdditAttenToBeepgenVoice: + return 0; + case GetDialToneFilterSubindex: + return 0; + case GetBusyToneLooseDetectionEnabled: + return 0; + } + return -1; +} + +long modem_set_param(struct modem *m, unsigned name, int val) +{ + switch(name) { + case MDMPRM_NONE: + break; + case MDMPRM_RX_RATE: + m->rx_rate = val; + break; + case MDMPRM_TX_RATE: + m->tx_rate = val; + break; + case MDMPRM_DP_REQUESTED: + m->dp_requested = val; + break; + case MDMPRM_UPDATE_DELAY: + m->update_delay = val; + break; + case MDMPRM_HOOK_ON: + return m->driver.ioctl(m, MDMCTL_HOOKSTATE, + val ? MODEM_HOOK_ON : MODEM_HOOK_OFF ); + case MDMPRM_PULSE_DIAL: + // bla-bla + return m->driver.ioctl(m, MDMCTL_PULSEDIAL, val); + default: + return -1; + } + return 0; +} diff --git a/slmodemd/modem_param.h b/slmodemd/modem_param.h new file mode 100644 index 0000000..22fd89e --- /dev/null +++ b/slmodemd/modem_param.h @@ -0,0 +1,202 @@ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem_param.h -- modem parameters access definitions. + * + * Author: Sasha K (sashak@smlink.com) + * + * + */ + +#ifndef __MODEM_PARAM_H__ +#define __MODEM_PARAM_H__ + +/* param names */ +enum MODEM_PARAMETER_NAMES { + MDMPRM_NONE, + MDMPRM_RX_RATE, + MDMPRM_RATE = MDMPRM_RX_RATE, + MDMPRM_TX_RATE, + MDMPRM_MIN_RATE, + MDMPRM_MAX_RATE, + MDMPRM_IODELAY, + MDMPRM_CODECTYPE, + MDMPRM_DIALSTR, + MDMPRM_AUTOMODE, + MDMPRM_DP_REQUESTED, + MDMPRM_DPRUNTIME, + MDMPRM_DSPINFO, + MDMPRM_VOICEINFO, + MDMPRM_UPDATE_DELAY, + MDMPRM_DP_ADDR, + MDMPRM_HOOK_ON, + MDMPRM_PULSE_DIAL, + //GetDTMFBetweenDigitsInterval, + GetPulseDialMakeTime, + GetPulseDialBreakTime, + GetPulseDialDigitPattern, + GetDTMFHighToneLevel, + GetDTMFDialSpeed, + //GetCallProgressDetectionThreshold, + //GetDialToneDelay, + //GetDialToneHoleTime, + //GetDelayBeforeRingCountResettingInMcs, + //GetRingCountForAutoanswer, + //GetMinRingSignalPeriodInMcs, + //GetMaxRingSignalPeriodInMcs, + //GetMinRingCadenceOnTimeInMcs, + //GetRingCadenceOffTimeInMcs, + GetMinBusyCadenceOnTime, + GetMaxBusyCadenceOnTime, + GetBusyDetectionCyclesNumber, + GetMinBusyCadenceOffTime, + GetMaxBusyCadenceOffTime, + //GetContinuousUnavailableDetectionFlag, + //GetAnswerToneValidationTime, + //GetBlacklistingDelayedFlag, + //GetFailedAttemptsAllowedInFirstStage, + //GetFailedAttemptsNumberBeforeBlacklisting, + //GetTroubledCallDelay, + //GetIneffectiveCallDelay, + //GetErroneousCallDelay, + //GetBlackListingDuration, + //GetLoopCurrentSenseWaitingTime, + GetCallingToneFlag, + //GetBlindDialFlag, + //GetBusyDetectDisable, + //GetGuardToneType, + //GetBellModesPermittedFlag, + //GetOffHookRestrictions, + //GetShuntRelayOnTimeDuringOffHook, + GetHookFlashTime, + GetBlindDialPause, + GetNoAnswerTimeOut, + GetDialPauseTime, + //GetNoCarrierDisconnectTime, + GetTransmitLevel, + GetDialModifierValidation, + //GetTADReceiveGain, + //GetHalfOrFullWaveRingDetection, + //GetFailedAttemptsNumberBeforeBlockingFurtherAttempts, + //GetErroneousCallIncrementCount, + GetDialToneValidationTime, + //GetDialToneMinOnTimePeriod, + GetBusyToneDiffTime, + //GetBusyToneDetectionDuringDialToneDetectionFlag, + GetDTMFHighAndLowToneLevelDifference, + //GetLocalPhoneDetectionInSpeakerphone, + GetPulseDialingFlag, + GetDialToneCallProgressFilterIndex, + GetDialToneDetectionThreshold, + GetABCDDialingPermittedFlag, + GetComaPauseDurationLimit, + //GetTADTransmitLevel, + //GetDataFAXCarrierReceiveThreshold, + //GetNoDialToneTimeOutDuration, + //GetFAXDataAnswerToneDetectionThreshold, + //GetDialToneLevel, + //GetFAXCallingToneLevel, + GetPulseAndToneDialInSameDialStringPermittedFlag, + //GetRingerImpedanceRelayFlag, + //GetDCLoopVICharacteristicsRelayFlag, + //GetDCLoopLimitingRelayFlag, + //GetRealOrComplexImpedance, + //GetMinPauseBetweenRingSequencesInMcs, + //GetMaxPauseBetweenRingSequencesInMcs, + //GetMinRingCadenceOnTimeFirstInMcs, + //GetMaxRingCadenceOnTimeFirstInMcs, + //GetMinRingCadenceOnTimeForFirstSequenceInMcs, + //GetMaxRingCadenceOnTimeForFirstSequenceInMcs, + //GetMaxRingCadenceOnTimeInMcs, + //GetNumberOfSequencesInFirstRing, + //GetNumberOfSequencesInRegularRing, + //IsALaw, + GetBusyToneCallProgressFilterIndex, + //GetCoefficientTableIndex, + GetPulseBetweenDigitsInterval, + GetDialToneWaitTime, + //GetAnswerDelay, + //GetPulseRefresh, + //GetHandsetGain, + //GetSpecificHardwareBitmask, + //GetDefaultDTMFDialSpeed, + //GetDefaultNoAnswerTimeout, + //GetBlacklistingTimeout, + //IsATPCommandDisabled, + //GetDelayAfterCounterpartDisconnection, + //IsFloatModeForced, + //GetDataFaxCarrierDisconnectThreshold, + //GetFaxTransmitLevel, + //GetPulseDialingRefreshScheme, + GetMinRingbackCadenceOnTime, + GetMaxRingbackCadenceOnTime, + GetRingbackDetectionCyclesNumber, + GetMinRingbackCadenceOffTime, + GetMaxRingbackCadenceOffTime, + GetRingbackToneCallProgressFilterIndex, + GetMinCongestionCadenceOnTime, + GetMaxCongestionCadenceOnTime, + GetCongestionDetectionCyclesNumber, + GetMinCongestionCadenceOffTime, + GetMaxCongestionCadenceOffTime, + GetCongestionToneCallProgressFilterIndex, + GetCallProgressSamplesBufferLength, + MustNoiseFilterBeApplied, + //GetDigitalImpairmentsMask, + GetAdditAttenToBeepgenVoice, + GetDialToneFilterSubindex, + GetBusyToneLooseDetectionEnabled, + //GetRingFreqValueInHz(int); + //GetEndUniversalRingTimeoutInMcs, + //GetRingIntsForFreq, + //GetDelayBeforeUniversalRingCountResettingInMcs, + //GetUniversalRingDetectorEnabled, + //GetCallWaitingIntegrationTimeMiliSec, + //GetCallWaitingThresholdPercentage, + //GetDialStringAfterFlash(char *dialString); + MDMPRM_LAST +}; + + +struct modem; + +extern long modem_get_param(struct modem *m, unsigned param); +extern long modem_set_param(struct modem *m, unsigned name, int val); + +extern long modem_get_sreg_param(struct modem *m, unsigned sreg_param); + +#endif /* __MODEM_PARAM_H__ */ + diff --git a/slmodemd/modem_test.c b/slmodemd/modem_test.c new file mode 100644 index 0000000..1dca030 --- /dev/null +++ b/slmodemd/modem_test.c @@ -0,0 +1,481 @@ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem_test.c -- modem simulator. + * + * Author: Sasha K (sashak@smlink.com) + * + * + */ + +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#define INFO(fmt,args...) fprintf(stderr, fmt , ##args ); +#define ERR(fmt,args...) fprintf(stderr, "error: " fmt , ##args ); + +#define DBG(fmt,args...) if(modem_debug_level) \ + fprintf(stderr, "main: " fmt , ##args ); + + +//#define SIMULATE_RING 1 + + +/* modem init externals : FIXME remove it */ +extern int dp_dummy_init(void); +extern void dp_dummy_exit(void); +extern int dp_sinus_init(void); +extern void dp_sinus_exit(void); +extern int prop_dp_init(void); +extern void prop_dp_exit(void); +extern int datafile_load_info(char *name,struct dsp_info *info); +extern int datafile_save_info(char *name,struct dsp_info *info); + + +/* global config data */ +extern unsigned modem_debug_logging; + + +struct modem_test { + struct modem *modem; + struct modem_test *link; + int in,out; + unsigned int delay; + unsigned int started; + unsigned pty_closed; + unsigned close_count; +}; + + +#define CLOSE_COUNT_MAX 100 + +/* static data */ +static char inbuf[4096]; +static char outbuf[4096]; + + +/* 'driver' simulation */ + +static int modem_test_start (struct modem *m) +{ + struct modem_test *t = m->dev_data; + DBG("modem_test_start...\n"); + t->delay = 256; + t->started = 1; + memset(outbuf,0,t->delay); + write(t->out,outbuf,t->delay); + return 0; +} + +static int modem_test_stop (struct modem *m) +{ + struct modem_test *t = m->dev_data; + DBG("modem_test_stop...\n"); + t->started = 0; + t->delay = 0; + return 0; +} + +static int modem_test_ioctl(struct modem *m, unsigned int cmd, unsigned long arg) +{ + struct modem_test *t = m->dev_data; + DBG("modem_test_ioctl: cmd %x, arg %lx...\n",cmd,arg); + switch (cmd) { + case MDMCTL_CAPABILITIES: + return -1; + case MDMCTL_HOOKSTATE: + return 0; + case MDMCTL_SPEED: + return 0; + case MDMCTL_GETFMTS: + case MDMCTL_SETFMT: + return 0; + case MDMCTL_SETFRAGMENT: + return 0; + case MDMCTL_SPEAKERVOL: + return 0; + case MDMCTL_CODECTYPE: + return CODEC_UNKNOWN; + case MDMCTL_IODELAY: + return t->delay/2; + default: + break; + } + return -2; +} + + + +struct modem_driver modem_test_driver = { + .name = "modem_test driver", + .start = modem_test_start, + .stop = modem_test_stop, + .ioctl = modem_test_ioctl, +}; + + +/* + * + */ + +static volatile sig_atomic_t keep_running = 1; + +void mark_termination(int signum) +{ + DBG("signal %d: mark termination.\n",signum); + keep_running = 0; +} + + +static int modem_test_run(struct modem_test *modems) +{ + struct timeval tmo; + fd_set rset,eset; + struct termios termios; + struct modem_test *t; + void *in; + int max_fd = 0; + int count, ret; + +#ifdef SIMULATE_RING +#define RING_HZ 20 +#define RING_ON 1*RING_HZ +#define RING_OFF 4*RING_HZ + unsigned rcount = RING_ON; +#endif + + + while(keep_running) { + + for( t = modems ; t->modem ; t++ ) + if(t->modem->event) + modem_event(t->modem); +#ifdef SIMULATE_RING + tmo.tv_sec = 0; + tmo.tv_usec= 1000000/RING_HZ; +#else + tmo.tv_sec = 1; + tmo.tv_usec= 0; +#endif + FD_ZERO(&rset); + FD_ZERO(&eset); + max_fd = 0; + + for( t = modems ; t->modem ; t++ ) { + FD_SET(t->in,&rset); + FD_SET(t->in,&eset); + if(t->in > max_fd) + max_fd = t->in; + if( t->pty_closed && t->close_count ) { + if ( !t->started || + t->close_count++ > CLOSE_COUNT_MAX ) + t->close_count = 0; + } + else if (t->modem->xmit.size - t->modem->xmit.count > 0) { + FD_SET(t->modem->pty,&rset); + if(t->modem->pty > max_fd) + max_fd = t->modem->pty; + } + } + + ret = select(max_fd + 1,&rset,NULL,&eset,&tmo); + + if (ret < 0) { + if (errno == EINTR) { + continue; + } + ERR("select: %s\n",strerror(errno)); + return ret; + } + + //DBG("select = %d\n",ret); + if (ret == 0) { +#ifdef SIMULATE_RING + if(!modems->modem->started) { + rcount++; + if (rcount <= RING_ON) + modem_ring(modems->modem); + else if (rcount > RING_OFF) + rcount = 0; + } +#endif + continue; + } + + for( t = modems ; t->modem ; t++ ) { + if(FD_ISSET(t->in,&eset)) { + DBG("dev exception...\n"); + } + } + + for( t = modems ; t->modem ; t++ ) { + if(FD_ISSET(t->in,&rset)) { + //DBG("dev read...\n"); + count = read(t->in,inbuf,sizeof(inbuf)/2); + if(count < 0) { + ERR("dev read: %s\n",strerror(errno)); + return -1; + } + else if (count == 0) { + DBG("dev read = 0\n"); + continue; + } + in = inbuf; + if(t->modem->update_delay < 0) { + if ( -t->modem->update_delay >= count/2) { + DBG("change delay -%d...\n", count/2); + t->delay -= count; + t->modem->update_delay += count/2; + continue; + } + DBG("change delay %d...\n", t->modem->update_delay); + in -= t->modem->update_delay*2; + count += t->modem->update_delay*2; + t->delay += t->modem->update_delay*2; + t->modem->update_delay = 0; + } + if(t->started) { + modem_process(t->modem,in,outbuf,count>>1); + } + else { + memset(outbuf,0,count); + /* ring here */ + } + count = write(t->out,outbuf,count); + if(count < 0) { + ERR("dev write: %s\n",strerror(errno)); + return -1; + } + else if (count == 0) { + DBG("dev write = 0\n"); + } + if(t->modem->update_delay > 0) { + DBG("change delay %d...\n", t->modem->update_delay); + memset(outbuf, 0, t->modem->update_delay*2); + count = write(t->out,outbuf,t->modem->update_delay*2); + if(count < 0) { + ERR("dev write: %s\n",strerror(errno)); + return -1; + } + t->delay += t->modem->update_delay*2; + t->modem->update_delay = 0; + } + } + } + + for( t = modems ; t->modem ; t++ ) { + int pty = t->modem->pty; + if(FD_ISSET(pty,&rset)) { + //DBG("pty read...\n"); + /* check termios */ + tcgetattr(pty,&termios); + if(memcmp(&termios,&t->modem->termios, + sizeof(termios))) { + DBG("termios changed.\n"); + modem_update_termios(t->modem, &termios); + } + /* read data */ + count = t->modem->xmit.size - t->modem->xmit.count; + if(count == 0) + continue; + if (count > sizeof(inbuf)) + count = sizeof(inbuf); + count = read(pty,inbuf,count); + if(count < 0) { + if(errno == EAGAIN) { + DBG("pty read, errno = EAGAIN\n"); + continue; + } + if(errno == EIO) { + if(!t->pty_closed) { + DBG("pty closed.\n"); + t->pty_closed = 1; + if(termios.c_cflag&HUPCL) + modem_hangup(t->modem); + } + t->close_count = 1; + //DBG("pty read, errno=EIO\n"); + continue; + } + else + ERR("pty read: %s\n", + strerror(errno)); + return -1; + } + else if (count == 0) { + DBG("pty read = 0\n"); + } + t->pty_closed = 0; + //DBG("pty read %d\n",count); + count = modem_write(t->modem,inbuf,count); + if(count < 0) { + DBG("modem_write failed.\n"); + return -1; + } + } + } + } + + return 0; +} + + +static int modem_test_init(struct modem_test *t, const char *name, int in, int out) +{ + struct termios termios; + char *pty_name; + int pty; + int ret; + + memset(t,0,sizeof(*t)); + + t->in = in; + t->out = out; + + pty = getpt(); + if (pty < 0 || grantpt(pty) < 0 || unlockpt(pty) < 0) { + ERR("getpt: %s\n",strerror(errno)); + exit(-1); + } + + ret = tcgetattr(pty, &termios); + /* non canonical raw tty */ + cfmakeraw(&termios); + cfsetispeed(&termios, B115200); + cfsetospeed(&termios, B115200); + + ret = tcsetattr(pty, TCSANOW, &termios); + if (ret) { + ERR("tcsetattr: %s\n",strerror(errno)); + exit(-1); + } + + fcntl(pty,F_SETFL,O_NONBLOCK); + + pty_name = ptsname(pty); + + t->modem = modem_create(&modem_test_driver,name); + if(!t->modem) { + return -1; + } + t->modem->name = name; + t->modem->pty = pty; + //t->modem->dev = dev; + t->modem->dev_name = name; + t->modem->pty_name = pty_name; + // datafile_load_info(basename(dev_name),&t->modem->dsp_info); + modem_update_termios(t->modem,&termios); + t->modem->dev_data = t; + + DBG("created %s: %s\n",t->modem->name,t->modem->pty_name); + return 0; +} + +static void modem_test_free(struct modem_test *t) +{ + int pty = t->modem->pty; + modem_delete(t->modem); + close(pty); +} + + +int modem_test() +{ + struct modem_test *ma, *mb; + struct modem_test modems[3] = {}; + int pipe1[2], pipe2[2]; + int ret = 0; + + modem_debug_init("test"); + + memset(modems,0,sizeof(modems)); + + dp_dummy_init(); + dp_sinus_init(); + prop_dp_init(); + modem_timer_init(); + + ma = &modems[0]; + mb = &modems[1]; + + if(pipe(pipe1) < 0 || pipe(pipe2) < 0) { + ERR("pipe: %s\n",strerror(errno)); + exit(-1); + } + + modem_test_init(ma,"modemA",pipe1[0],pipe2[1]); + modem_test_init(mb,"modemB",pipe2[0],pipe1[1]); + + ma->link = mb; + mb->link = ma; + + signal(SIGINT, mark_termination); + signal(SIGTERM, mark_termination); + + /* main loop here */ + ret = modem_test_run(modems); + + modem_test_free(ma); + modem_test_free(mb); + + dp_dummy_exit(); + dp_sinus_exit(); + prop_dp_exit(); + + exit(ret); + return 0; +} + + + +int main(int argc, char *argv[]) +{ + extern void modem_cmdline(int argc, char *argv[]); + modem_debug_level = 1; + modem_cmdline(argc,argv); + return modem_test(); +} diff --git a/slmodemd/modem_timer.c b/slmodemd/modem_timer.c new file mode 100644 index 0000000..16cdd77 --- /dev/null +++ b/slmodemd/modem_timer.c @@ -0,0 +1,205 @@ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem_timer.c -- simple timer (will not in multithreaded env). + * + * Author: Sasha K (sashak@smlink.com) + * + * + */ + +#include +#include +#include +#include + +#include + +#if 0 +#include +#define WARN(fmt...) fprintf(stderr, fmt); +#else +#define WARN(fmt...) +#endif + +#define MAX_TIME LONG_MAX + +static struct timeval tv_init; + +static struct timer_list_struct { + struct timer *list; + unsigned long when; + struct sigaction old_act; +} timer_list; + + + +unsigned long get_time() +{ + struct timeval tv_now,tv; + gettimeofday(&tv_now,NULL); + timersub(&tv_now,&tv_init,&tv); + return tv.tv_sec*MODEM_HZ + tv.tv_usec/(1000000/MODEM_HZ); +} + +static void set_timer(unsigned long when) +{ + struct itimerval it; + long t; + t = (long)(when - get_time()); + if( t <= 0) t = 1; + it.it_interval.tv_usec = 0; + it.it_interval.tv_sec = 0; + it.it_value.tv_usec = (t%MODEM_HZ)*(1000000/MODEM_HZ); + it.it_value.tv_sec = t/MODEM_HZ; + setitimer(ITIMER_REAL,&it,NULL); +} + + +static void timer_list_handler(int num) +{ + unsigned long now; + struct timer *t,*next; + now = get_time(); + t = timer_list.list; + timer_list.list = NULL; + while(t) { + next = t->next; + t->next = NULL; + if( (long)(t->expires - now) <= 0 ) { + t->added = 0; + if(t->func) { + t->func(t->data); + } + } + else { + t->next = timer_list.list; + timer_list.list = t; + } + t = next; + } + timer_list.when = now + MAX_TIME; + t = timer_list.list; + while(t) { + if((long)(timer_list.when - t->expires) > 0) + timer_list.when = t->expires; + t = t->next; + } + set_timer(timer_list.when); +} + + +void timer_init(struct timer *t) +{ + t->next = 0; + t->added = 0; + t->expires = 0; + t->func = NULL; + t->data = NULL; +} + +int timer_add(struct timer *t) +{ + sigset_t set, old_set; + sigemptyset(&set); + sigaddset(&set,SIGALRM); + sigprocmask(SIG_BLOCK,&set,&old_set); + if(t->added) { + WARN("timer_add: already.\n"); + } + else { + t->added = 1; + t->next = timer_list.list; + timer_list.list = t; + } + if((long)(timer_list.when - t->expires) > 0) { + timer_list.when = t->expires; + set_timer(timer_list.when); + } + sigprocmask(SIG_SETMASK,&old_set,NULL); + return 0; +} + +int timer_del(struct timer *t) +{ + sigset_t set, old_set; + struct timer *p, **prev; + sigemptyset(&set); + sigaddset(&set,SIGALRM); + sigprocmask(SIG_BLOCK,&set,&old_set); + if(t->added) { + p = timer_list.list; + prev = &timer_list.list; + while(p) { + if(p == t) { + *prev = t->next; + t->next = NULL; + t->added = 0; + break; + } + prev = &((*prev)->next); + p = p->next; + } + } + else { + WARN("timer_del: not added\n"); + } + sigprocmask(SIG_SETMASK,&old_set,NULL); + return 0; +} + + +int modem_timer_init() +{ + struct sigaction act; + gettimeofday(&tv_init,NULL); + timer_list.list = NULL; + timer_list.when = get_time() + MAX_TIME; + act.sa_handler = timer_list_handler; + sigemptyset(&act.sa_mask); + sigaddset(&act.sa_mask, SIGALRM); + act.sa_flags = SA_SIGINFO; + sigaction(SIGALRM,&act,&timer_list.old_act); + set_timer(timer_list.when); + return 0; +} + +void modem_timer_exit() +{ + sigaction(SIGALRM,&timer_list.old_act,NULL); +} + + diff --git a/slmodemd/modem_timer.h b/slmodemd/modem_timer.h new file mode 100644 index 0000000..ef7e72a --- /dev/null +++ b/slmodemd/modem_timer.h @@ -0,0 +1,70 @@ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * modem_timer.h -- definitions for simple timer. + * + * Author: Sasha K (sashak@smlink.com) + * + * + */ + +#ifndef __MODEM_TIMER_H__ +#define __MODEM_TIMER_H__ + + +#define MODEM_HZ 100 + +struct timer { + struct timer *next; + unsigned added; + unsigned expires; + void (*func)(void *); + void *data; +}; + + +#define time_before(t1,t2) ((long)((t2)-(t1)) > 0) +#define time_after(t1,t2) (!time_before(t1,t2)) + +unsigned long get_time(void); + +extern void timer_init(struct timer *t); +extern int timer_add(struct timer *t); +extern int timer_del(struct timer *t); + +extern int modem_timer_init(void); + +#endif /* __MODEM_TIMER_H__ */ diff --git a/slmodemd/sysdep_common.c b/slmodemd/sysdep_common.c new file mode 100644 index 0000000..9316262 --- /dev/null +++ b/slmodemd/sysdep_common.c @@ -0,0 +1,112 @@ +/*****************************************************************************/ + +/* + * + * Copyright (c) 2002, Smart Link Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Neither the name of the Smart Link Ltd. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * + * sysdep_common.c -- sysdep API. + * + * Author: Sasha K (sashak@smlink.com) + * + * + */ + +/*****************************************************************************/ + +#include +#include +#include +#include + + +/* memory allocations */ +void *sysdep_malloc (unsigned int size) +{ + return malloc(size); +} + +void sysdep_free (void *mem) +{ + free(mem); +} + +/* strings */ +size_t sysdep_strlen(const char *s) +{ + return strlen(s); +} +char *sysdep_strcpy(char *d,const char *s) +{ + return strcpy(d,s); +} +char *sysdep_strcat(char *d, const char *s) +{ + return strcat(d,s); +} +int sysdep_strcmp(const char *s1,const char *s2) +{ + return strcmp(s1, s2); +} +char *sysdep_strstr(const char *s1,const char *s2) +{ + return strstr(s1,s2); +} +void *sysdep_memset(void *d,int c,size_t l) +{ + return memset(d,c,l); +} +void *sysdep_memcpy(void *d,const void *s,size_t l) +{ + return memcpy(d,s,l); +} +void *sysdep_memchr(const void *s,int c,size_t l) +{ + return memchr (s,c,l); +} + +int sysdep_vsnprintf(char *str, unsigned size, const char *format, va_list ap) +{ + return vsnprintf(str, size, format, ap); +} + +int sysdep_sprintf(char *buf, const char *fmt, ...) +{ + va_list args; + int i; + va_start(args, fmt); + i=vsprintf(buf,fmt,args); + va_end(args); + return i; +} +