X-Git-Url: http://git.jankratochvil.net/?p=mdsms.git;a=blobdiff_plain;f=mdsms.c;h=932dc490f6cbc8e7d265e2555988b513ed8c5843;hp=48eb8f5df8b523d6260d23d1ee7b5ed339c4b147;hb=de6759d0cd4f1074a30268ccf3fd2e74f021c5e2;hpb=25f8b04f0bb7af6a2bb1b73d50762de53b87663c diff --git a/mdsms.c b/mdsms.c index 48eb8f5..932dc49 100644 --- a/mdsms.c +++ b/mdsms.c @@ -3,38 +3,62 @@ static char rcsid[] ATTR_UNUSED = "$Id$"; #endif -/* - * $Log$ - * Revision 1.3 1999/06/03 11:46:41 short - * Logging (--log) implemented. - * - * Revision 1.2 1999/06/03 10:38:52 short - * Implemented remaining communication timeouts and maximum retry count. - * - * Revision 1.1.1.1 1999/05/26 13:06:26 short - * First alpha release. - * - */ - #include "setup.h" +#ifdef HAVE_STDIO_H #include +#endif +#ifdef HAVE_STDLIB_H #include +#endif +#ifdef HAVE_STRING_H #include +#endif +#ifdef HAVE_SIGNAL_H #include +#endif +#ifdef HAVE_STDARG_H #include +#endif +#ifdef HAVE_LIMITS_H #include +#endif +#ifdef HAVE_CTYPE_H #include -#include +#endif +#ifdef HAVE_TERMIOS_H #include +#endif +#ifdef HAVE_UNISTD_H #include +#endif +#ifdef HAVE_ASSERT_H #include +#endif +#ifdef HAVE_SYS_TYPES_H #include +#endif +#ifdef HAVE_SYS_STAT_H #include +#endif +#ifdef HAVE_FCNTL_H #include +#endif +#ifdef HAVE_ERRNO_H #include -#include +#endif +#ifdef HAVE_TIME_H #include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_POLL_H +#include +#endif +#ifdef HAVE_LOCALE_H +#include +#endif #ifdef HAVE_GETOPT_LONG #include @@ -42,14 +66,6 @@ static char rcsid[] ATTR_UNUSED = "$Id$"; #include "getopt.h" #endif -#if 0 -char *strdup(const char *s); -int kill(pid_t pid,int sig); -int snprintf(char *str,size_t n,const char *format,...); -int vsnprintf(char *str,size_t n,const char *format,va_list ap); -void usleep(unsigned long usec); -#endif - #define NELEM(x) (sizeof((x))/sizeof(*(x))) #ifndef DEBUG @@ -61,12 +77,16 @@ void usleep(unsigned long usec); #define dO stderr #define dB(a) dbg(fprintf a) -#define d1(n1) dB((dO,n1 )) -#define d2(n1,n2) dB((dO,n1,n2 )) -#define d3(n1,n2,n3) dB((dO,n1,n2,n3 )) -#define d4(n1,n2,n3,n4) dB((dO,n1,n2,n3,n4)) +#define d1(n1) dB((dO,n1 )) +#define d2(n1,n2) dB((dO,n1,n2 )) +#define d3(n1,n2,n3) dB((dO,n1,n2,n3 )) +#define d4(n1,n2,n3,n4) dB((dO,n1,n2,n3,n4 )) +#define d5(n1,n2,n3,n4,n5) dB((dO,n1,n2,n3,n4,n5 )) +#define d6(n1,n2,n3,n4,n5,n6) dB((dO,n1,n2,n3,n4,n5,n6 )) +#define d7(n1,n2,n3,n4,n5,n6,n7) dB((dO,n1,n2,n3,n4,n5,n6,n7 )) +#define d8(n1,n2,n3,n4,n5,n6,n7,n8) dB((dO,n1,n2,n3,n4,n5,n6,n7,n8)) -static const char version[]="This is MobilDock SMS sender (" PACKAGE " " VERSION ")\n"; +static const char version[]="Mobile Device SMS tool (" PACKAGE " " VERSION ")\n"; static int verbose #ifdef DEBUG @@ -76,23 +96,65 @@ static int verbose static char *pname; static int dis_cleanup=0,devfd=-1; -static char *phone,*body,*device,*logname,*lockfile,*smsc,*maxretry,*readtime,*chartime,*cmdtime; +static char *phone,*device,*logname,*lockfile,*smsmode,*pdusmscmode,*smsc,*maxretry,*readtime,*chartime,*cmdtime,*baud,*restore; static int readbody; -static long maxretryn=DEF_MAXRETRY,readtimen=DEF_READTIME,chartimen=DEF_CHARTIME,cmdtimen=DEF_CMDTIME; +static long maxretryn=DEF_MAXRETRY,readtimen=-1,chartimen=DEF_CHARTIME,cmdtimen=DEF_CMDTIME,baudn=DEF_BAUD; +#ifdef HAVE_CRTSCTS +static int handshake_rtscts; +static unsigned handshake_stamp; +#else +#define handshake_rtscts (0) +#endif +static enum { + FSM_AUTO=0, + FSM_PDU, + FSM_TEXT + } force_smsmode=FSM_AUTO; +static enum { + FPSM_AUTO=0, + FPSM_COUNT_IN, + FPSM_COUNT_OUT, + FPSM_NONE + } force_pdusmscmode=FPSM_AUTO, +#define FPSM_MIN (FPSM_COUNT_IN) +#define FPSM_MAX (FPSM_NONE) + try_pdusmscmode=FPSM_MIN; static size_t bodylen; +/* --send / --send-mobildock / --receive specific */ +static char *body; +/* --logo-send specific */ +static char *logoname,*gsmnet; +/* --ring-send specific */ +static char *ringname; + +static enum modenum { + MODE_UNKNOWN=0, +/* must differ from regular char-s */ + MODE_FIRST =0x3400, + MODE_SEND =MODE_FIRST+0, /* --send / --send-mobildock */ + MODE_SEND_MOBILDOCK=MODE_FIRST+1, /* --send-mobildock in before readtimen is set */ + MODE_RECEIVE =MODE_FIRST+2, /* --receive */ + MODE_LOGO_SEND =MODE_FIRST+3, /* --logo-send */ + MODE_RING_SEND =MODE_FIRST+4 /* --ring-send */ + } mode=MODE_UNKNOWN; +#define MODE_ORDER(x) ((x)-MODE_FIRST) +#define MODE_NAME(x) (longopts[MODE_ORDER((x))].name) +#define MODE_BIT(x) (1<"); + if (gethostname(host,sizeof(host))) strcpy(host,_("")); } time(&stamp); ctm=ctime(&stamp); if ((s=strchr(ctm,'\n'))) *s='\0'; fprintf(logf,"%s %s %s[%d]: ",ctm,host,pname,mypid); vfprintf(logf,fmt,ap); -#ifndef PRINTF_WORKS_PM - if (outerr) fputs(strerror(errno),logf); -#endif + if (pm) { fputs(": ",logf); fputs(strerror(errno),logf); } + if (fatal!='\n') fputc((fatal=='.'?'.':'!'),logf); fputc('\n',logf); fflush(logf); } +static void logmsg(const char *fmt,...) ATTR_PRINTFORMAT(1,2); static void logmsg(const char *fmt,...) { va_list ap; va_start(ap,fmt); - vlogmsg( -#ifndef PRINTF_WORKS_PM - 0, -#endif - fmt,ap); + vlogmsg(0,'\n',fmt,ap); va_end(ap); } +static void error(const char *fmt,...) ATTR_PRINTFORMAT(1,2); static void error(const char *fmt,...) { va_list ap; -char fatal=*fmt; -#ifndef PRINTF_WORKS_PM -char pm,*nfmt; -size_t fmtl; -#endif +char fatal,pm; + if ((pm=(*fmt=='^'))) fmt++; + fatal=*fmt; if (fatal=='!' || fatal=='.' || fatal=='\n') fmt++; else fatal=0; -#ifndef PRINTF_WORKS_PM - if (!(nfmt=strdup(fmt))) return; - fmtl=strlen(fmt); - if ((pm=(fmtl>=2 && !strcmp(fmt+fmtl-2,"%m")))) nfmt[fmtl-2]='\0'; -#endif - fprintf(stderr,"%s: ",pname); va_start(ap,fmt); - vfprintf(stderr, -#ifdef PRINTF_WORKS_PM - fmt -#else - nfmt -#endif - ,ap); - if (fatal=='!') vlogmsg( -#ifdef PRINTF_WORKS_PM - fmt -#else - pm,nfmt -#endif - ,ap); + vfprintf(stderr,fmt,ap); + if (fatal=='!') vlogmsg(pm,fatal,fmt,ap); va_end(ap); - -#ifndef PRINTF_WORKS_PM - if (pm) { - fputs(strerror(errno),stderr); - free(nfmt); - } -#endif - + if (pm) { fputs(": ",stderr); fputs(strerror(errno),stderr); } if (fatal!='\n') fputc((fatal=='.'?'.':'!'),stderr); fputc('\n',stderr); if (fatal=='!') exit(EXIT_FAILURE); } -static void chk(void *p) +static void chk(const void *p) { if (p) return; - error("!Virtual memory exhausted"); + error(_("!Virtual memory exhausted")); +} + +static char *devcmd(const char *term,const char *catch,const char *send,...) ATTR_PRINTFORMAT(3,4); + +static void unlockdevice(int hard) +{ + d2("unlockdevice(), locked=%d\n",locked); + if (!locked || !*lockreal) return; + if (!hard && locked>1) { locked--; return; } + d2("Removing lockfile \"%s\"\n",lockreal); + if (unlink(lockreal)) + error(_("^Error removing my device lockfile \"%s\""),lockreal); + locked=0; } static void cleanup(void) { d1("cleanup()\n"); if (dis_cleanup) return; + if (restore) { +char *cmd=restore; + restore=NULL; + devcmd(NULL,NULL,"\r\nAT"); + devcmd(NULL,NULL,cmd); + devcmd(NULL,NULL,"\r\nAT"); + } if (restios_yes) { if (tcsetattr(devfd,TCSANOW,&restios)) - error("Error restoring termios for device: %m"); + error(_("^Error restoring termios for device")); restios_yes=0; } - if (locked && *lockreal) { - d2("Removing lockfile \"%s\"\n",lockreal); - if (unlink(lockreal)) - error("Error removing my device lockfile \"%s\": %m",lockreal); - locked=0; - } + unlockdevice(1); dis_cleanup=1; exit(EXIT_FAILURE); } static void usage(void) { - fprintf(stderr,"\ + fprintf(stderr,_("\ \n\ %s\ \n\ -Usage: " PACKAGE " [-c|--config ] [-d|--device ]\n\ - [-L|--log ]\n\ - [-l|--lockfile ] [-s|--smsc ] [-m|--maxretry <#>]\n\ +Usage: %s [-c|--config ] [-d|--device ]\n\ + [-L|--log ] [-l|--lockfile ]\n\ + [-b|--baud ] [-x|--xonxoff] [-C|--rtscts]\n\ + [-M|--smsmode ] [-P|--pdusmscmode ]\n\ + [-s|--smsc ] [-m|--maxretry <#>]\n\ [-r|--readtime ] [-t|--chartime ] [-T|--cmdtime ]\n\ - [-f|--file] [-v|--verbose] [-h|--help] [-V|--version]\n\ - \n\ + [-v|--verbose] [-h|--help] [-V|--version]\n\ + {--send | --send-mobildock | --receive | --logo-send}\n\ + --send / --send-mobildock:\n\ + [-f|--file] \n\ + --receive:\n\ + \n\ + --logo-send:\n\ + []\n\ + --ring-send:\n\ + \n\ \n\ -c, --config\tRead this additional config file\n\ -\t\t(def. \"" CONFIG_MAIN "\" and \"$HOME" CONFIG_HOME "\")\n\ - -d, --device\tMobilDock on this serial device (def. \"" DEF_DEVICE "\")\n\ - -L, --log\tLog all important messages to this file (def. \"" DEF_LOGNAME "\")\n\ +\t\t(def. \"%s\" and \"$HOME%s\")\n\ + -d, --device\tMobile on this serial device (def. \"%s\")\n\ + -L, --log\tLog all important messages to this file (def. \"%s\")\n\ -l, --lockfile\tLock serial port by this file, \"%%s\" is basename of device\n\ \t\t(def. \"%s\")\n\ - -s, --smsc\tUse this SMS Center number (def. query from Siemens A1)\n\ + -b, --baud\tSet baudrate, 2400-57600 supported (def. %d)\n\ + -x, --xonxoff\tUse XON/XOFF (AKA software) serial port handshaking - default\n\ + -C, --rtscts\tUse RTS/CTS (AKA hardware) serial port handshaking%s\n\ + -M, --smsmode\tForce SMS as: \"pdu\" or 0: PDU mode, \"text\" or 1: text mode\n\ + -P, --pdusmscmode\tForce PDU as: \"count-in\", \"count-out\", \"none\"\n\ + -s, --smsc\tUse this SMS Center number (def. query from mobile)\n\ -m, --maxretry\tMaximum retries of any command before giving up (def. %d)\n\ - -r, --readtime\tSeconds for maximum wait time for response (def. %ds)\n\ - -t, --chartime\tMilliseconds between each char on baud 19200 (def. %dms)\n\ + -r, --readtime\tSeconds for maximum wait time for response\n\ +\t\t(def. %ds standard, %ds for MobilDock modes,\n\ +\t\t multiplied %dx for long cmds)\n\ + -t, --chartime\tMilliseconds between each char (def. %dms)\n\ -T, --cmdtime\tMilliseconds before each whole AT command (def. %dms)\n\ - -f, --file\tRead contents of message from file instead\n\ -v, --verbose\tIncrease verbosity level, more \"-v\"s give more messages\n\ -h, --help\tPrint a summary of the options\n\ -V, --version\tPrint the version number\n\ -\n",version,DEF_LOCKFILE,DEF_MAXRETRY,DEF_READTIME,DEF_CHARTIME,DEF_CMDTIME); +\n\ +--send / --send-mobildock:\n\ + -f, --file\tRead contents of message from file instead\n\ +--receive:\n\ + \tProgram to run on receive, message will be on stdin\n\ +\t\tFollowing substitutes are recognized:\n\ +\t\t%%p - source phone number\n\ +\t\t%%T - timestamp from SMSC as # of seconds from 1970 (-1 if invalid)\n\ +\t\t%%t - ctime(3) style timestamp (e.g. \"Wed Jun 30 21:49:08 1993\"),\n\ +\t\t empty string if invalid\n\ +\t\t%%s - originating SMSC number, if available (else empty)\n\ +--logo-send:\n\ + \t* Oper. logo: Enter custom network code MccMnc, e.g. 23002\n\ +\t\t* Oper. logo: Specify \"%s\" to read network code from NOL file\n\ +\t\t* Group gfx : Specify \"%s\" to send logo as group graphics\n\ +\n\ +You may need to use the following line to catch all of this help text:\n\ +./mdsms 2>&1|more\n\ +\n"),version,PACKAGE,CONFIG_MAIN,CONFIG_HOME,DEF_DEVICE,DEF_LOGNAME,DEF_LOCKFILE,DEF_BAUD, +#ifdef HAVE_CRTSCTS + "", +#else + _("\n\t\t(Not supported on this platform!)"), +#endif +DEF_MAXRETRY,DEF_READTIME,DEF_READTIME_MOBILDOCK,EXT_READTIME,DEF_CHARTIME,DEF_CMDTIME, +WORD_NET,WORD_GROUP); exit(EXIT_FAILURE); } static const struct option longopts[]={ -{"config" ,1,0,'c'}, -{"device" ,1,0,'d'}, -{"log" ,1,0,'l'}, -{"lockfile",1,0,'l'}, -{"smsc" ,1,0,'s'}, -{"maxretry",1,0,'m'}, -{"readtime",1,0,'r'}, -{"chartime",1,0,'t'}, -{"cmdtime" ,1,0,'T'}, -{"file" ,0,0,'f'}, -{"verbose" ,0,0,'v'}, -{"help" ,0,0,'h'}, -{"version" ,0,0,'V'}}; +/* Modes has to be in-order on exact positions */ +{"send" ,0,0,MODE_SEND}, +{"send-mobildock",0,0,MODE_SEND_MOBILDOCK}, +{"receive" ,0,0,MODE_RECEIVE}, +{"logo-send" ,0,0,MODE_LOGO_SEND}, +{"ring-send" ,0,0,MODE_RING_SEND}, +/* Mode aliases may follow in no particular order * + * as long as no non-mode options is between them */ +{"send-md" ,0,0,MODE_SEND_MOBILDOCK}, +{"recv" ,0,0,MODE_RECEIVE}, +{"logo" ,0,0,MODE_LOGO_SEND}, +{"ring" ,0,0,MODE_RING_SEND}, +{"config" ,1,0,'c'}, +{"device" ,1,0,'d'}, +{"log" ,1,0,'L'}, +{"lockfile" ,1,0,'l'}, +{"baud" ,1,0,'b'}, +{"xonxoff" ,0,0,'x'}, +{"rtscts" ,0,0,'C'}, +{"smsmode" ,1,0,'M'}, +{"pdusmscmode" ,1,0,'P'}, +{"smsc" ,1,0,'s'}, +{"maxretry" ,1,0,'m'}, +{"readtime" ,1,0,'r'}, +{"chartime" ,1,0,'t'}, +{"cmdtime" ,1,0,'T'}, +{"file" ,0,0,'f'}, +{"verbose" ,0,0,'v'}, +{"help" ,0,0,'h'}, +{"version" ,0,0,'V'}, +{NULL ,0,0,0 }}; static void processargs(int argp,char **args,const char *from); @@ -256,7 +362,19 @@ static unsigned cfgstacki=0; static void chkfclose(FILE *f,const char *fname) { if (fclose(f)) - error("Error closing \"%s\": %m",fname); + error(_("^Error closing \"%s\""),fname); +} + +static long getfilesize(FILE *f,const char *fname) +{ +long size; + + if (fseek(f,0,SEEK_END)) + error(_("^Error seeking to end of \"%s\""),fname); + if ((size=ftell(f))<0) + size=-1,error(_("^Error measuring length of \"%s\""),fname); + rewind(f); + return(size); } static void readfile(const char *fname,char quiet) @@ -270,25 +388,22 @@ long size; static unsigned tot=0; if (tot++>=MAXCFGNUM) { - if (tot==MAXCFGNUM+1) error("Too many config files to read, max is %d, break-out",MAXCFGNUM); + if (tot==MAXCFGNUM+1) error(_("Too many config files to read, max is %d, break-out"),MAXCFGNUM); return; } if (!(f=fopen(fname,"rt"))) { - if (!quiet) error("Can't open config file \"%s\" for r/o: %m",fname); + if (!quiet) error(_("^Can't open config file \"%s\" for r/o"),fname); return; } - if (verbose>=2) error(".Reading config file \"%s\"",fname); - if (fseek(f,0,SEEK_END)) - error("Error seeking to end of \"s\": %m",fname); - if ((size=ftell(f))<0) - size=0,error("Error measuring \"%s\": %m",fname); + + if (verbose>=2) error(_(".Reading config file \"%s\""),fname); + if ((size=getfilesize(f,fname))==-1) size=0; if (size>MAXCONFIG) - error("File \"%s\" is too long, read only %ld bytes",fname,MAXCONFIG); + error(_("File \"%s\" is too long, read only %d bytes"),fname,MAXCONFIG); chk(buf=malloc((size?size:MAXCONFIG)+1)); - rewind(f); got=fread(buf,1,(size?size:MAXCONFIG),f); if (size && got!=size) - error("File \"%s\" read error, got only %u bytes of %ld",fname,got,size); + error(_("File \"%s\" read error, got only %u bytes of %ld"),fname,got,size); chkfclose(f,fname); buf[got]='\0'; args[0]=pname; @@ -299,13 +414,13 @@ char c=*s; if (!blank) { *d='\0'; blank=1; - if (verbose>=2) error("\nConfig \"%s\": arg#%d: %s",fname,argp-1,args[argp-1]); + if (verbose>=2) error(_("\nConfig \"%s\": arg#%d: %s"),fname,argp-1,args[argp-1]); } continue; } if (blank) { if (argp>=NELEM(args)-1) { - error("Too many arguments in \"%s\", from offset %d ignored",fname,s-buf); + error(_("Too many arguments in \"%s\", from offset %d ignored"),fname,s-buf); break; } args[argp++]=s; @@ -325,19 +440,125 @@ char c=*s; free(buf); } +static struct argstack { + struct argstack *next; + int num,offset; + const char *from; + char *arg[1]; + } *argstack; + +static struct argstack **argstack_tail=&argstack; +static size_t lastargstack_len; +static const char *lastargstack_from; +static int lastargstack_index; + +static size_t argstack_size; +static int argstack_num; + +static void pushargstack(char **args,int num,int offset,const char *from,char stack) +{ +struct argstack *as; +int i; + + if (!num) return; + assert(num>=1); + chk(as=malloc(sizeof(*as)+sizeof(as->arg)*(num-1))); + as->num=num; + as->offset=offset; + if (!from) as->from=NULL; + else chk(as->from=strdup(from)); + for (i=0;iarg[i]=strdup(args[i])); + argstack_size+=strlen(args[i]); + } + argstack_num+=num; + if (stack) { + as->next=argstack; + argstack=as; + } + else { + as->next=NULL; + *argstack_tail=as; + argstack_tail=&as->next; + } +} + +static void pushargstack_one(char *s,char stack) +{ pushargstack(&s,1,0,NULL,stack); } + +static char *nextargstack(void) +{ +static int order=0; +char *r; + + if (argstack && order==argstack->num) { +struct argstack *as=argstack; + if (!(argstack=as->next)) + argstack_tail=&argstack; + order=0; + free((char *)as->from); + lastargstack_from=NULL; + free(as); + } + if (!argstack) { + assert(!argstack_num); assert(!argstack_size); + return(NULL); + } + assert(ordernum); + lastargstack_index=argstack->offset+order; + r=argstack->arg[order++]; + assert(argstack_num>0); argstack_num--; + lastargstack_len=strlen(r); + assert(argstack_size>=lastargstack_len); argstack_size-=lastargstack_len; + lastargstack_from=argstack->from; + return(r); +} + +static char *glueargstack(size_t *destlenp,const char *glue) +{ +size_t gluel=(glue?strlen(glue):0),destlen; +char *dest,*d,*s; + + if (!argstack_num) { + chk(dest=strdup("")); + if (destlenp) *destlenp=0; + return(dest); + } + destlen=argstack_size+(argstack_num-1)*gluel; + if (destlenp) *destlenp=destlen; + chk(dest=malloc(destlen+1)); + for (d=dest;(s=nextargstack());) { + memcpy(d,s,lastargstack_len); + free(s); + d+=lastargstack_len; + if (!argstack_num) break; + if (!glue) continue; + memcpy(d,glue,gluel); + d+=gluel; + assert(d<=dest+destlen); + } + assert(!argstack_num); + assert(d==dest+destlen); + *d='\0'; + return(dest); +} + static struct { const char c; char **const var; unsigned stamp; } optset[]={ - { 'd',&device }, - { 'L',&logname }, - { 'l',&lockfile }, - { 's',&smsc }, - { 'm',&maxretry }, - { 'r',&readtime }, - { 't',&chartime }, - { 'T',&cmdtime }, + { 'd',&device }, + { 'L',&logname }, + { 'l',&lockfile }, + { 'b',&baud }, + { 'M',&smsmode }, + { 'P',&pdusmscmode }, + { 's',&smsc }, + { 'm',&maxretry }, + { 'r',&readtime }, + { 't',&chartime }, + { 'T',&cmdtime }, }; static void processargs(int argp,char **args,const char *from) @@ -348,15 +569,15 @@ int i; seq++; optarg=NULL; optind=0; /* FIXME: Possible portability problem. */ - while ((optc=getopt_long(argp,args,"c:d:L:l:s:m:r:t:T:fvhV",longopts,NULL))!=EOF) switch (optc) { + while ((optc=getopt_long(argp,args,"c:d:L:l:b:xCM:P:s:m:r:t:T:fvhV",longopts,NULL))!=EOF) switch (optc) { case 'c': if (cfgstacki>=NELEM(cfgstack)) { - error("Looping (%d) during attempt to read config file \"%s\", break-out",NELEM(cfgstack),optind); + error(_("Looping (%d) during attempt to read config file \"%s\", break-out"),NELEM(cfgstack),from); break; } chk(cfgstack[cfgstacki++]=strdup(optarg)); break; - case 'd': case 'L': case 'l': case 's': case 'm': case 'r': case 't': case 'T': + case 'd': case 'L': case 'b': case 'l': case 'M': case 'P': case 's': case 'm': case 'r': case 't': case 'T': for (i=0;i=3) error(".Checking the lockfile \"%s\"..",lockreal); + if (verbose>=3) error(_(".Checking the lockfile \"%s\".."),lockreal); if ((fd=open(lockreal,O_RDONLY))==-1) break; if ((got=read(fd,buf,sizeof(buf)-1))<=0) { isempty: if (empty>=DEVLOCK_MAXEMPTY) { - error(".Lockfile \"%s\" is still not valid, removing it",lockreal); + error(_(".Lockfile \"%s\" is still not valid, removing it"),lockreal); goto remove; } empty++; @@ -464,33 +807,47 @@ isempty: empty=0; errno=0; if (kill(pid,0) && errno!=ESRCH && errno!=EPERM) - error("Error during checking consciousness of PID %d: %m",pid); - if (errno!=ESRCH) continue; - error(".Lockfile \"%s\" is stale (PID %d), removing it",lockreal,pid); + error(_("^Error during checking consciousness of PID %d"),pid); + if (errno!=ESRCH) { + if (attempt) return(0); + continue; + } + error(_(".Lockfile \"%s\" is stale (PID %d), removing it"),lockreal,pid); remove: lockclose(fd); if (unlink(lockreal)) - error("Error removing foreign lockfile \"%s\": %m",lockreal); + error(_("^Error removing foreign lockfile \"%s\""),lockreal); break; } errno=0; if ((fd=open(lockreal,O_WRONLY|O_CREAT|O_EXCL,0644))==-1) { if (errno==EEXIST) goto recheck; - error("!Error creating lockfile \"%s\": %m",lockreal); + error(_("^!Error creating lockfile \"%s\""),lockreal); } locked=1; got=VARPRINTF(buf,"%010d\n",getpid()); assert(got==11); if (write(fd,buf,got)!=got) - error("!Error writing data to lockfile \"%s\": %m",lockreal); + error(_("^!Error writing data to lockfile \"%s\""),lockreal); lockclose(fd); + return((locked=1)); } static char wasalarm=0; -static void sigalarm(int signo) +static void sigalarm(int signo); + +static void setalarm(void) { signal(SIGALRM,(RETSIGTYPE (*)(int))sigalarm); +#ifdef HAVE_SIGINTERRUPT + siginterrupt(SIGALRM,1); +#endif +} + +static void sigalarm(int signo) +{ + setalarm(); wasalarm=1; - if (verbose>=1) error("Timed out"); + if (verbose>=1) error(_("Timed out")); } static void blocking(char yes) @@ -498,51 +855,111 @@ static void blocking(char yes) static char state=-1; if (state==yes) return; if (fcntl(devfd,F_SETFL,(yes?0:O_NONBLOCK))) - error("!fcntl() on device for %sblocking mode: %m",(yes?"":"non-")); + error(_("^!fcntl() on device for %s mode"),(yes?_("blocking"):_("non-blocking"))); state=yes; } -static const char *record; +static const char *record,*recordend; static char *catchdata; static size_t catchdatal,catchdatasiz; -static void catched(const char *end) +static char *reform(const char *s,int slot); +static void catched(const char *end,char edata) { size_t len; -void *p; +const char *p; if (!record) return; assert(end>=record); - if ((p=memchr(record,'\n',end-record))) end=p; - if ((len=end-record)) { + p=memchr(record,edata,end-record); + if ((len=(p?p:end)-record)) { + if (!catchdata) + chk(catchdata=malloc((catchdatasiz=LINE_MAX))); if (catchdatal+len>catchdatasiz) chk(catchdata=realloc(catchdata, - (catchdatasiz=MAX(LINE_MAX,(catchdatal+len)*2)))); + (catchdatasiz=(catchdatal+len)*2))); memcpy(catchdata+catchdatal,record,len); catchdatal+=len; } - record=(p?NULL:end); + record =(p?NULL:end); + recordend=(p?p :end); assert(catchdatal<=catchdatasiz); } static int retrycnt=0; static void retrying(void) { - if (++retrycnt>maxretryn) error("!Maximum command retry count (%d) exceeded",maxretryn); - if (verbose>=2) error(".Retrying phase, %d out of %d..",retrycnt,maxretryn); + if (maxretryn>=0 && ++retrycnt>=maxretryn) error(_("!Maximum command retry count (%ld) exceeded"),maxretryn); + if (verbose>=2) error(_(".Retrying phase, %d out of %ld.."),retrycnt,maxretryn); } +static char *reform(const char *s,int slot) +{ +static struct formslot { + char *s; + size_t l; + } arr[3]; +char c,*d; +struct formslot *fs; + + assert(slot>=0 && slot")); + if (!(fs=&arr[slot])->s) + chk(fs->s=malloc(fs->l=LINE_MAX)); + d=fs->s; + for (*d++='"';(c=*s);s++) { + if (d>=fs->s+fs->l-10) { +off_t o=d-fs->s; + chk(fs->s=realloc(fs->s,(fs->l=(fs->l?fs->l*2:LINE_MAX)))); + d=fs->s+o; + } + if (c!='\\' && c!='"' && isprint(c)) { *d++=c; continue; } + *d++='\\'; + switch (c) { + case '\\': case '"': *d++=c; break; + case '\n': *d++='n'; break; + case '\r': *d++='r'; break; + case '\032': *d++='Z'; break; + case '\033': *d++='e'; break; + default: + d+=sprintf(d,"x%02X",(unsigned char)c); + break; + } + } + *d++='"'; *d='\0'; + return(fs->s); +} + +static char *devcmd(const char *term,const char *catch,const char *send,...) ATTR_PRINTFORMAT(3,4); static char *devcmd(const char *term,const char *catch,const char *send,...) { -size_t l,bufl,terml,catchl,fragl,offs; -char buf[LINE_MAX]; +size_t l,bufl2,terml,catchl=0 /* GCC happiness */,fragl,offs; +static char buf[LINE_MAX]; +static size_t bufl; ssize_t got; char *hit,*s; va_list ap; -char errout; +char errout,extend,catch_any,edata; +long alarmtime; +const char *osend; +static const char emptystring[]=""; +size_t discard; if (!term) term="\nOK\n"; + if (!strcmp(send," ")) send=NULL; /* GCC formatstring-check workaround */ + if (verbose>=2) error(_(".devcmd(sendfmt=%s,term=%s,catch=%s)"), + reform(send,0),reform(term,1),reform(catch,2)); + if (!(osend=send)) send=""; + if ((catch_any=(catch && !strcmp(catch,"@")))) catch=NULL; if ((errout=(*send=='!'))) send++; + errout|=(maxretryn==-1); + if ((extend=(*send=='~'))) send++; + alarmtime=readtimen*(extend?EXT_READTIME:1); + buf[bufl]='\0'; /* for d8() below */ + d8("devcmd(), alarmtime=%ld, errout=%d, extend=%d, catch_any=%d, osend=%p, bufl=%d, buf: %s\n", + alarmtime,errout,extend,catch_any,osend,bufl,reform(buf,0)); + assert(!catch || !strchr(catch,'\r')); /* we are no longer supporting 'noconvcr'! */ + assert(!term || !strchr(term ,'\r')); if (0) { err: alarm(0); @@ -550,30 +967,34 @@ err: retrying(); } catchdatal=0; - va_start(ap,send); - l=VARVPRINTF(buf,send,ap); bufl=l+1; - va_end(ap); - if (bufl>=sizeof(buf)-1) error("!Command too big (%d>%d)",bufl,sizeof(buf)-1); - if (verbose>=2) error(".devcmd(send=\"%s\",term=\"%s\",catch=\"%s\")",buf,term,catch); - buf[l]='\r'; buf[l+1]='\n'; - for (offs=0,got=0;offs=sizeof(buf)-1) error(_("!Command too big (%d>%d)"),bufl,sizeof(buf)-1); + if (verbose>=2) error(_(".devcmd formatted send=%s%s"),reform(buf,0),(osend?"+\"\\r\"":"")); + if (osend) buf[l]='\r'; + for (offs=0,got=0;offss && (s=memchr(s,'\r',buf+bufl-s))) *s='\n'; - catched(buf+bufl); assert(!record || record==buf+bufl); - assert(bufl=fragl) { - buf[bufl]='\0'; - assert(strlen(buf)==bufl); - /* d3(">%s|%s<\n",buf,term); */ - if (strstr(buf,ERROR_SUBSTR1) || strstr(buf,ERROR_SUBSTR2)) { - error("Found ERROR response on command \"%s\"",send); - goto err; - } - if (catch && bufl>=catchl && (hit=strstr(buf,catch))) { - record=hit+catchl; - catched(buf+bufl); assert(!record || record==buf+bufl); - } - if ( bufl>= terml && (hit=strstr(buf,term))) break; - memmove(buf,buf+bufl-(fragl-1),fragl-1); - bufl=fragl-1; - if (record) record=buf+bufl; + while (buf+bufl2>s && (s=memchr(s,'\0',buf+bufl2-s))) *s++=REPL_NULLCHAR; + if (verbose>=3) + error(_("\nGot chunk of data from device: %s"),reform(buf+bufl,0)); + /* convert CR */ { + s=buf+bufl; + while (buf+bufl2>s && (s=memchr(s,'\r',buf+bufl2-s))) *s++='\n'; + } + bufl=bufl2; +skipread: + catched(buf+bufl,edata); assert(!record || record==buf+bufl); + assert(bufl%s|%s<\n",buf,term); */ + if (strstr(buf,ERROR_SUBSTR1) || strstr(buf,ERROR_SUBSTR2)) { + error(_("Found ERROR response on command %s"),reform(send,0)); + goto err; + } +/* "record" may get NULLed here after successful 'catch' + * but "recordend" will never be NULLed + */ + if (catch && !recordend && bufl>=catchl && (hit=strstr(buf,catch))) { + record=hit+catchl; + catched(buf+bufl,edata); assert(!record || record==buf+bufl); + } + if (catch_any && !recordend && buf[discard=strspn(buf,"\n" /* accept */)]) { + record=buf+discard; + catched(buf+bufl,edata); assert(!record || record==buf+bufl); + } + if (((!catch && !catch_any) || catchdatal) && bufl>= terml + && (hit=strstr((recordend?recordend:buf),term))) { + memmove(buf,hit+terml,(bufl2=(buf+bufl)-(hit+terml))); bufl=bufl2; + break; } + if (bufl=2) error(".Returning data \"%s\" for cmd \"%s\"",catchdata,send); + assert(!!catch || catch_any); + record=emptystring; + catched(record+1,edata); + if (verbose>=2) error(_(".Returning data %s for cmd %s"),reform(catchdata,0),reform(send,1)); return(catchdata); } @@ -648,7 +1090,7 @@ unsigned char n; *++d=(plus?ADDR_INT:ADDR_NAT); while (*addr) { if (*addr<'0' || *addr>'9') - error("!Error during conversion of number at: %s",addr); + error(_("!Error during conversion of number at: %s"),addr); tot++; n=(*addr++)-'0'; if ((flip=!flip)) *++d=0xF0|n; @@ -668,7 +1110,7 @@ static inline char tohex(unsigned char x) return(x-10+'A'); } -static void textconv(char *d,unsigned char *s,size_t len) +static inline void textconv(char *d,unsigned char *s,size_t len) { while (len--) { *d++=tohex(*s>>4U); @@ -681,49 +1123,244 @@ static void textconv(char *d,unsigned char *s,size_t len) static inline void smscset(void) { char *s,*t,*e,*serr; -long l; unsigned char bin[2+(MAXNUMLEN+1)/2]; if (smsc) devcmd(NULL,NULL,"\r\nAT+CSCA=\"%s\"",smsc); s=devcmd(NULL,"\n+CSCA:","\r\nAT+CSCA?"); while (isspace(*s)) s++; if (!*s || !strcmp(s,"EMPTY")) - error("!No SMS set in A1 found"); - if (verbose>=1) error("\nFound default SMSC in A1: %s",s); - if (*s!='"') error("!No left-quote found in: %s",s); - if (!(t=strrchr(s+1,'"'))) error("!No right-quote found in: %s",s); + error(_("!No SMSC set in mobile station found, please use option \"-s\"")); + if (verbose>=1) error(_("\nFound default SMSC in mobile: %s"),s); + if (*s++!='"') error(_("!No left-quote found in: %s"),s); + if (!(t=strrchr(s,'"'))) error(_("!No right-quote found in: %s"),s); + if (s==t) + error(_("!No SMS set in mobile station found, please use option \"-s\"")); e=t++; while (isspace(*t)) t++; - if (*t++!=',') error("!No comma found after quotes in: %s",s); - while (isspace(*t)) t++; - l=strtol(t,&serr,10); - if ((l!=ADDR_NAT && l!=ADDR_INT) || (serr && *serr)) - error("!Type parse error in: %s",s); - if (l==ADDR_NAT || s[1]=='+') s++; - else *s='+'; + if (*t) { +long l; + + if (*t++!=',') error(_("!No comma found after quotes in: %s"),s); + while (isspace(*t)) t++; + l=strtol(t,&serr,10); + if ((l!=ADDR_NAT && l!=ADDR_INT) || (serr && *serr)) + error(_("!Type parse error in: %s"),s); + if (l==ADDR_INT && *s!='+') *--s='+'; + } *e='\0'; + if (verbose>=2) error(_("\nDecoded SMSC address: %s"),s); + if (!NEED_PDUSMSC()) return; chk(finalsmsc=strdup(s)); - if (verbose>=2) error("\nDecoded SMSC address: %s",finalsmsc); bin[0]=1+(prepaddr(bin,finalsmsc)+1)/2; textconv(pdusmsc,bin,bin[0]+1); } -static char *pdudata; - -static inline unsigned char charconv(char c,size_t offs) +static inline unsigned char charconv_send(char c,size_t offs) { - if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')) return(c); switch (c) { case '@': return(0); case '$': return(2); - case '"': return(96); - case ' ': - return(c); case 0: assert(0); + default: + return(c&0x7F); } - error("Can't convert character '%c' (0x%02X) at offs %d (0-based), substituted '?'", +#if 0 + if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')) return(c); + error(_("Can't convert character '%c' (0x%02X) at offs %d (0-based), substituted '?'"), c,(unsigned char)c,offs); return('?'); +#endif +} + +static inline unsigned char charconv_recv(char c,size_t offs) +{ /* FIXME: unify with charconv_send() */ + switch (c) { + case 0: return('@'); + case 2: return('$'); + default: + return(c); + } +/* strict checking not done, see charconv_send */ +} + +/* Logo format shamelessly stolen from GNokii-0.3.0: http://www.gnokii.org/ + * Beware - Nokia Smart Messaging specification 1.0.0 and 2.0.0 is incompatible + * with Nokia current product line implementation + * http://www.forum.nokia.com/developers/smartmsg/download/ssm2_0_0.pdf + */ + +static char *pdudata; +static struct hexdata { + struct hexdata *next; + char data[140*2+1]; + } *hexdata,**hexdatatail=&hexdata; + +static void nokiaprep(unsigned char *bin,size_t w) +{ +struct hexdata *hd; + assert(w<=140); + chk(hd=malloc(sizeof(*hd))); + *hexdatatail=hd; + hd->next=NULL; + hexdatatail=&hd->next; + textconv(hd->data,bin,w); + if (verbose>=2) error(_("\nWill send hexdata: %s"),hd->data); +} + +static inline void logoread(void) +{ +FILE *f; +char buf[32+140*8+1]; +unsigned char bin[140]={ + 0x06, /* UDH length */ + 0x05, /* IEI */ + 0x04, /* IEDL */ + 0x15, 0x83, /* dest port (group gfx) */ + 0x00, 0x00 /* src port (unused) */ + }; +size_t got,r=0 /* GCC happiness */,w; +ssize_t chars,bits; +char gsmnetf[10]; +int sizex,sizey,bit; + +#define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8)) + + if (!(f=fopen(logoname,"rb"))) + error(_("^!Cannot open logo file \"%s\" for r/o"),logoname); + got=fread(buf,1,sizeof(buf),f); + chkfclose(f,logoname); + if (got>=20 && !memcmp(buf,"NOL",4)) { + VARPRINTF2(gsmnetf,"%03.3u%02.2u",WORD(6),WORD(8)); + assert(strlen(gsmnetf)==5); + r=10; + if (verbose>=1) error(_(".Reading NOL file \"%s\", GSMnet \"%s\", word@4=%d.."), + logoname,gsmnetf,WORD(4)); + } + else if (got>=16 && !memcmp(buf,"NGG",4)) { + r=6; + if (verbose>=1) error(_(".Reading NGG file \"%s\", word@4=%d.."), + logoname,WORD(4)); + } + else error(_("!Unknown file format of logo file \"%s\""),logoname); + if (gsmnet && !strtrycasecmp(gsmnet,WORD_NET)) { + if (!*gsmnetf) error(_("!NOL network code detection requested but NOL file not loaded, please specify network code")); + gsmnet=gsmnetf; + } + if (!gsmnet || !strtrycasecmp(gsmnet,WORD_GROUP) || !*gsmnet) { + error(_("\nSending logo as: group graphics")); + gsmnet=NULL; + } + else { + error(_("\nSending logo as: operator logo for \"%s\""),gsmnet); + bin[4]=0x82; /* dest port 0x1582 */ + } + + sizex=WORD(r); sizey=WORD(r+2); + if (verbose>=2) error(_(".Magic words: @+4=%d, @+6=%d, @+8=%d"), + WORD(r+4),WORD(r+6),WORD(r+8)); + r+=10; + if (sizex<1 || sizex>255 + || sizey<1 || sizey>255) error(_("!Invalid size: %dx%d"),sizex,sizey); + chars=((bits=sizex*sizey)+7)/8; + if (r+bits>got) error(_("!Logo file \"%s\" too short - actual=%d, need(%dx%d)=%d"), + logoname,got,sizex,sizey,r+chars); + else if (r+bits=1) error(_("Ignoring trailing garbage in \"%s\", used only %d bytes"),logoname,r+bits); + if ((got=(7+(gsmnet?3:0)+4+chars))>140) + error(_("!SMS size would be %d bytes but 140 is maximum"),got); + w=7; + if (gsmnet) { + bin[w++]=((gsmnet[1]&0x0F)<<4)|(gsmnet[0]&0x0F); + bin[w++]=0xF0 |(gsmnet[2]&0x0F); + bin[w++]=((gsmnet[4]&0x0F)<<4)|(gsmnet[3]&0x0F); + } + bin[w++]=0x00; /* RFU by Nokia */ + bin[w++]=sizex; bin[w++]=sizey; + bin[w++]=0x01; /* one B/W plane */ + while (chars--) { + bin[w]=0; + for (bit=0x80;(bits>0) && (bit>0);bits--,bit>>=1) { + if (buf[r]!='0' && buf[r]!='1') + error(_("!Invalid character (neither '0' nor '1') in logo file \"%s\" at offset 0x%X"), + logoname,r); + if (buf[r++]=='1') bin[w]|=bit; + } + w++; + } + assert(chars==-1); assert(bits==0); assert(w==got); + nokiaprep(bin,w); +#undef WORD +} + +static inline void ringread(void) +{ +FILE *f; +unsigned char bin1[140]={ + 6, /* UDH length */ + 0x05, /* IEI */ + 0x04, /* IEDL */ + 0x15, 0x81, /* dest port (ring tones) */ + 0x15, 0x81 /* src port (unused) */ +#define BIN1_PAYLOAD (140-7) + }; +unsigned char binn[140]={ + 11, /* UDH length */ + 0x05, /* IEI */ + 0x04, /* IEDL */ + 0x15, 0x81, /* dest port (ring tones) */ + 0x15, 0x81, /* src port (unused) */ + 0x00, 0x03, /* multipart */ + /* 0x??, unique serial ID */ + /* 0x??, total messages */ + /* 0x??, message number (# from 1) */ +#define BINN_PAYLOAD (140-12) + }; +size_t got,want; +int totn,fragn; +long size; + +#define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8)) + + if (!(f=fopen(ringname,"rb"))) + error(_("^!Cannot open ring file \"%s\" for r/o"),ringname); + if ((size=getfilesize(f,ringname))==-1) + error(_("!File size determination is essential to continue operation")); + if (size<0x103) + error(_("!File \"%s\" size %ld too small (must >=0x103)! Is it .000 file?"), + ringname,size); + if (fseek(f,0x100,SEEK_SET)) + error(_("^Seeking error on \"%s\", ignoring"),ringname); + size-=0x100; + if (size<=BIN1_PAYLOAD) { + if ((got=fread(bin1+7,1,size,f))!=size) + error(_("^Read error on \"%s\", wanted %ld, got %d"),ringname,size,got); + error(_("\nSending ring tone \"%s\" as single SMS (size %ld, max %d)"), + ringname,size,BIN1_PAYLOAD); + nokiaprep(bin1,7+size); + } + else { + totn=(size+BINN_PAYLOAD-1)/BINN_PAYLOAD; + if (totn>0xFF) + error(_("!File size %ld too large even for multi-SMS ring upload (max=%d)"), + size,BINN_PAYLOAD*0xFF); + binn[10]=totn; + if (verbose>=1) + error(_("\nSending ring tone \"%s\" as %d multi-SMSes (size %ld, max %d, frag %d)"), + ringname,totn,size,BIN1_PAYLOAD,BINN_PAYLOAD); + binn[9]=time(NULL)&0x100; /* rand() would be better but it is a compatibility pain */ + if (verbose>=1) + error(_("\nUsing unique multi-SMS ID 0x%02X"),(unsigned)binn[9]); + for (fragn=1;fragn<=totn;fragn++) { + binn[11]=fragn; + want=MIN(size,BINN_PAYLOAD); + if ((got=fread(binn+12,1,want,f))!=want) + error(_("^Read error on \"%s\", wanted %d, got %d"),ringname,want,got); + nokiaprep(binn,12+want); + size-=want; + } + } + chkfclose(f,ringname); +#undef WORD } static inline void genpdu(void) @@ -731,8 +1368,8 @@ static inline void genpdu(void) static unsigned char pdu[64+MAXNUMLEN/2+(MAXBODYLEN*7)/8]; unsigned char *d=pdu; int i; -char inb=0,outb=0,xb; -unsigned char inreg; +char inb=0,outb=0,xb,*bodyr; +unsigned char inreg=0 /* GCC happiness */; size_t offs=0; *d++=PDU_TYPE; @@ -743,15 +1380,16 @@ size_t offs=0; *d++=PDU_DCS; *d++=PDU_VP; if (bodylen>MAXBODYLEN) { - error("Body too large (%d>%d), cut",bodylen,MAXBODYLEN); - bodylen=MAXBODYLEN; + error(_("Body too large (%d>%d), cut"),bodylen,MAXBODYLEN); + body[(bodylen=MAXBODYLEN)]='\0'; } + bodyr=body; *d=bodylen; assert(d0); assert(!!*body); - inreg=charconv(*body++,offs++); + inreg=charconv_send(*bodyr++,offs++); bodylen--; inb=7; } @@ -760,7 +1398,9 @@ size_t offs=0; outb=8; } xb=MIN(inb,outb); +#if 0 d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb); +#endif *d|=((inreg>>(unsigned)(7-inb))&((1<=1) + error(_("\nPlease enter the SMS text body, end with EOF (ctrl-D):")); + } + else { + if (!(fin=fopen(finame,"rt"))) + error(_("^!Can't open data file \"%s\" for r/o"),finame); + } + chk(body=malloc(BODYLOAD)); + bodylen=fread(body,1,BODYLOAD,fin); + if (bodylen==-1) + error(_("^!Error reading stream \"%s\""),(finame?finame:_(""))); + if (finame) { + chkfclose(fin,finame); + free(finame); + } +} + +static int datawait(char immed) +{ +int i; +#ifdef HAVE_POLL +struct pollfd ufd; +#else /* HAVE_POLL */ +fd_set rfds,xfds; +#endif /* HAVE_POLL */ + + assert(devfd>=0); +retry: + errno=0; + +#ifdef HAVE_POLL + ufd.fd=devfd; + ufd.events=POLLIN; + ufd.revents=0; + i=poll(&ufd,1,(immed?0:-1)); +#else /* HAVE_POLL */ +#ifdef HAVE_FD_SETSIZE + if (devfd>=FD_SETSIZE) + error(_("!Device file descriptor %d can't fit in select() FD_SETSIZE (%d)"), + devfd,FD_SETSIZE); +#endif /* HAVE_FD_SETSIZE */ + FD_ZERO(&rfds); FD_SET(devfd,&rfds); + FD_ZERO(&xfds); FD_SET(devfd,&xfds); + i=select(devfd+1,&rfds,NULL,&xfds,NULL); +#endif /* HAVE_POLL */ + if (immed && i==0) return(0); + if (i!=1) + error(_("^Failed (retval %d) while waiting for data, ignoring"),i); + +#ifdef HAVE_POLL + if (ufd.revents&(POLLERR|POLLHUP)) +#else /* HAVE_POLL */ + if (FD_ISSET(devfd,&xfds)) +#endif /* HAVE_POLL */ + error(_("^Error while waiting for data, ignoring")); + +#ifdef HAVE_POLL + if (!(ufd.revents&POLLIN)) +#else /* HAVE_POLL */ + if (!(FD_ISSET(devfd,&rfds))) +#endif /* HAVE_POLL */ + { + error(_("^No data input after waited for data, retrying")); + goto retry; + } + return(1); +} + +static char *check_format(const char *fmt,const char *string) +{ +static char err[LINE_MAX],sub[50]; +char *subp,cf,cs; +const char *sf,*ss; + + for (sf=fmt,ss=string;(cf=*sf) && (cs=*ss);sf++,ss++) { + subp=NULL; + switch (cf) { + case '?': + break; + case '9': + if (isdigit(cs)) break; + subp=_("digit"); + break; + case '+': + if (cs=='+' || cs=='-') break; + subp=_("+/- sign"); + break; + default: + if (cf==cs) break; + VARPRINTF(sub,"'%c'",cf); subp=sub; + } + if (!subp) continue; + VARPRINTF5(err,_("Expected %s, found '%c' at pos %d of string [%s], formatstring [%s]"), + subp,cs,ss-string,string,fmt); + return(err); + } + if (*sf) { + VARPRINTF2(err,_("String too short for format, string [%s], formatstring [%s]"), + string,fmt); + return(err); + } + if (*ss) { + VARPRINTF2(err,_("Trailing garbage in string [%s], formatstring [%s]"), + string,fmt); + return(err); + } + return(NULL); +} + +static char *receive_number,*receive_smsc; +static time_t receive_time; + +struct tm tm; +static const struct { + off_t strpos; + off_t tmpos; + int min,max; + const char *name; + } timeparse[]={ +#define TP_ENT(a,b,c,d,e) { a,offsetof(struct tm,b),c,d,e } + TP_ENT( 3,tm_year,0,99,N_("year")), + TP_ENT( 6,tm_mon ,1,12,N_("month")), + TP_ENT( 9,tm_mday,1,31,N_("day of month")), + TP_ENT(12,tm_hour,0,23,N_("hour")), + TP_ENT(15,tm_min ,0,59,N_("minute")), + TP_ENT(18,tm_sec ,0,59,N_("second")), + /* Time zone ignored */ + }; +#define GETTIME(i) (*(int *)(((char *)&tm)+timeparse[(i)].tmpos)) + +static void maketime(const char *string) +{ +int val; +int i; + + for (i=0;itimeparse[i].max) { + error(_("Weird value of %s, is %d but expected %d..%d, setting to %d"), + _(timeparse[i].name),val,timeparse[i].min,timeparse[i].max,timeparse[i].min); + GETTIME(i)=timeparse[i].min; + } + } + if (tm.tm_year<70) tm.tm_year+=100; + tm.tm_mon--; + d7("mktime(y%dm%dd%dh%dm%ds%d)\n", + tm.tm_year,tm.tm_mon,tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec); + tm.tm_isdst=-1; /* "timezone" info not available */ + if ((receive_time=mktime(&tm))==-1) + error(_("^mktime(3) failed for %s"),string); +} + +/* +CMT: "+420602431329",,"99/10/25,03:21:03-00" */ +static int receive_headerparse(char *buf) +{ +char *s,*s1,*err; +int i; + +#define DIGIT2ASC(s) (((s)[0]-'0')*10+((s)[1]-'0')) + + for (s=buf;*s==' ';s++); + if (*s++!='"') { + error(_("Cannot find initial '\"' in CMT header: %s"),buf); + return(0); + } + for (s1=s;*s && *s!='"';s++); + if (!*s) { + error(_("Only one '\"' found in CMT header: %s"),buf); + return(0); + } + free(receive_smsc); receive_smsc=NULL; + free(receive_number); + chk(receive_number=malloc(s-s1+1)); + memcpy(receive_number,s1,s-s1); receive_number[s-s1]='\0'; + s++; + if ((err=check_phone(receive_number)) || + (err=check_format(",,\"99/99/99,99:99:99+99\"",s))) { + error(_("%s in CMT header: %s"),err,buf); + return(0); + } + memset(&tm,0,sizeof(tm)); /* may be redundant */ + for (i=0;i0) return; /* parent context */ + if (pid==-1) { + error(_("Can't fork(2), process spawning may block receive")); + } + else { /* child process */ + dis_cleanup=1; + } + for (s=body;*s;) { + s1=s; + do { + s1=strchr(s1+(s1!=s),'%'); + } while (s1 && s1[1]!='p' && s1[1]!='T' && s1[1]!='t' && s1[1]!='s'); + if (!s1) { + pushargstack_one(s,0); + break; + } + *s1='\0'; + pushargstack_one(s,0); + *s1++='%'; + s=s1; + switch (*s++) { + case 'p': + pushargstack_one(receive_number,0); + break; + case 'T': + VARPRINTF(tbuf,"%ld",receive_time); + pushargstack_one(tbuf,0); + break; + case 't': + if (receive_time==-1) break; + if (!(s2=ctime(&receive_time))) { + error(_("Failing ctime(3), ignoring substitution")); + break; + } + if ((s3=strchr(s2,'\n'))) *s3='\0'; + pushargstack_one(s2,0); + break; + case 's': + if (receive_smsc) pushargstack_one(receive_smsc,0); + break; + default: assert(0); + } + } + buf=glueargstack(NULL,NULL); assert(buf); + if (!(f=popen(buf,"w"))) { + error(_("^Failing spawn of receive command: %s"),buf); + goto err; + } + if (fputs(bodyline,f)<0 || putc('\n',f)!='\n') + error(_("^Failing write to child receive command: %s"),buf); + if ((i=pclose(f))) + error(_("^Spawned receive command failure (code %d): %s"),i,buf); +err: + free(buf); + if (pid==-1) return; + exit(EXIT_SUCCESS); /* cleanup() has been disabled */ +} + +static inline unsigned char fromhex(unsigned c) +{ + c&=0xDF; + return(c<'A'?c-('0'&0xDF):(c-('A'&0xDF))+0xA); +} + +static int teldecode(char *text,unsigned char *bin,size_t digits) +{ +unsigned char b; +int r=0,i; + + for (i=0;i>4; + b&=0x0F; + if (b<=0x09) + *text=b+'0'; + else { + *text='?'; + r++; + } + } + *text='\0'; + return(r); +} + +static void sctsparse(unsigned char *bin,const char *pduline,int offs) +{ +#define DIGIT2BIN(v) (((v)&0x0F)*10+(((v)>>4)&0x0F)) +int i; + + receive_time=-1; + memset(&tm,0,sizeof(tm)); /* may be redundant */ + for (i=0;i0x09 || (*bin&0xF0)>0x90) { + error(_("Invalid value of \"%s\" at offset %d in: %s"), + timeparse[i].name,offs,pduline); + return; + } + GETTIME(i)=DIGIT2BIN(*bin); + bin++; + } + maketime(pduline); + +#undef DIGIT2BIN +} + +static void receive_pdu(char *pduline) +{ +unsigned char pdu[140+0x100],*pdup,*pdue,oalen,inreg; +char text[160+1],*textp,*s,*pdulinescan; +size_t pdulinel=strlen(pduline),want; +size_t udl,udlb; +int inb,outb,xb; + + d2("receive_pdu: %s\n",pduline); + if (pdulinel>2*sizeof(pdu)) + { error(_("PDU too long (%d/2) to be valid: %s"),pdulinel,pduline); return; } + if (pdulinel&1) + { error(_("PDU length odd (%d): %s"),pdulinel,pduline); return; } + if (pdulinel<2*13) + { error(_("PDU length %d too small (min. 2*%d): %s"),pdulinel,13,pduline); return; } + for (pdup=pdu,pdulinescan=pduline;*pdulinescan;pdulinescan+=2) { + if (!isxdigit(pdulinescan[0]) || !(isxdigit(pdulinescan[1]))) + { error(_("Invalid hex byte: %c%c on byte %d in: %s"), + pdulinescan[0],pdulinescan[1],pdup-pdu,pduline); return; } + *pdup++=(fromhex(pdulinescan[0])<<4)|fromhex(pdulinescan[1]); + } + pdue=pdup; + free(receive_smsc); + if (*pdu<=1) { + receive_smsc=NULL; + } + else { + if (*pdu>10) + { error(_("SMSC length too large (%d, max. %d): %s"),*pdu,10,pduline); return; } + chk(receive_smsc=malloc(1+2*(*pdu)+1)); + s=receive_smsc; + if (pdu[1]==ADDR_INT) *s++='+'; + else { + if (pdu[1]!=ADDR_NAT) + error(_("Unknown address type 0x%02X of %s, ignoring in PDU: %s"),pdu[1],_("SMSC"),pduline); return; + } + if (teldecode(s,pdu+2,2*(*pdu-1)-((pdu[1+(*pdu)]&0xF0)==0xF0))) + error(_("Some digits unrecognized in %s \"%s\", ignoring in PDU: %s"),_("SMSC"),receive_smsc,pduline); + } + pdup=pdu+1+(*pdu); + if (*pdup&0x03) /* PDU type */ + error(_("Unrecognized PDU type 0x%02X at offset %d, dropping: %s"),*pdup,pdup-pdu,pduline); + pdup++; + free(receive_number); + if ((oalen=*pdup++)>2*0x10) /* OA len */ + { error(_("Originating number too large (0x%X, max. 2*0x%X): %s"),oalen,0x10,pduline); return; } + if (pdup+(want=1+(oalen+1)/2+10)>pdue) + { error(_("PDU length too short (want %d, is %d): %s"),(pdup-pdu)+want,pdue-pdu,pduline); return; } + chk(receive_number=malloc(1+2*(*pdup)+1)); + s=receive_number; + if (*pdup==ADDR_INT) *s++='+'; + else { + if (*pdup!=ADDR_NAT) + error(_("Unknown address type 0x%02X of %s, ignoring in PDU: %s"),*pdup,_("originating number"),pduline); return; + } + pdup++; + if (teldecode(s,pdup,oalen)) + error(_("Some digits unrecognized in %s \"%s\", ignoring in PDU at offset %d: %s"), + _("originating number"),receive_number,pdup-pdu,pduline); + pdup+=(oalen+1)/2; + if (*pdup) /* PID */ + error(_("PID number %02X unsupported, ignoring: %s"),*pdup,pduline); + pdup++; + if (*pdup) { /* DCS */ + if ((*pdup&0xF4)==0xF4) + { error(_("DCS 0x%02X indicates 8-bit data, unsupported, dropping: %s"),*pdup,pduline); return; } + error(_("DCS 0x%02X unsupported, will attempt decoding: %s"),*pdup,pduline); + } + pdup++; + sctsparse(pdup,pduline,pdup-pdu); + pdup+=7; + /* UDL */ + udl=*pdup++; + if (pdue-pdup>140) { + error(_("PDU data (%d) exceed maximum length of %d bytes, cut: %s"), + pdue-pdup,140,pduline); + pdue=pdup+140; + } + udlb=(udl*7+7)/8; + if (pdup+udlb>pdue) { +size_t udl1,udlb1; + + udlb1=pdue-pdup; + udl1=(udlb1*8)/7; + error(_("PDU data length (%d/7->%d/8) longer than data (%d), cut to %d/7->%d/8: %s"), + udl,udlb,pdue-pdup,udl1,udlb1,pduline); + udl=udl1; udlb=udlb1; + } + else + assert(pdup+udlb==pdue); /* should be checked by 'PDU length too short' above */ + textp=text; + inb=outb=0; + inreg=0; /* GCC happiness */ + while (udl) { + if (!inb) { + inreg=*pdup++; + inb=8; + } + if (!outb) { + assert(textp>(unsigned)(8-inb))&((1<"); + assert(mode==MODE_UNKNOWN); + for (i=0;i")); if ((s=getenv("HOME"))) { size_t l=strlen(s); char *buf=malloc(l+50); @@ -806,48 +1917,51 @@ char *buf=malloc(l+50); free(buf); } readfile(CONFIG_MAIN,1); + if (verbose>=1) { + if (argsmode) + error(_(".Detected mode \"%s\" from my program name \"%s\""),MODE_NAME(argsmode),pname); + else + error(_(".Automatic mode detection unsuccessul for my progam name \"%s\""),pname); + } - for (i=0;ivar) continue; + if (n->reqd && !(MODE_BIT(mode)&n->reqd)) continue; + error(_("Missing parameter \"%s\""),_(n->name)); + fatal++; + } + if (fatal) error(_("!Previous %s considered unrecoverable"),(fatal==1?_("error"):_("errors"))); + emptyclean(); if (!logname) logname=DEF_LOGNAME; if (!lockfile) lockfile=DEF_LOCKFILE; if (!device) device=DEF_DEVICE; - if (body && readbody) { - finame=body; - body=NULL; - } - else fin=stdin; - if (!body) { - readbody=0; - if (verbose>=1) - error("\nPlease enter the SMS text body, end with EOF (ctrl-D):"); - chk(body=malloc(BODYLOAD)); - bodylen=fread(body,1,BODYLOAD,fin); - if (bodylen==-1) - error("!Error reading stream \"%s\": %m",(finame?finame:"")); - } - if (fin!=stdin) { - chkfclose(fin,finame); - free(finame); - } for (i=0;i=LONG_MAX || !serr || *serr) - error("!Number parse error for parameter \"%s\" of \"%s\" at: %s", + error(_("!Number parse error for parameter \"%s\" of \"%s\" at: %s"), numarg[i].msg,*numarg[i].sp,serr); } + if (readtimen==-1) + readtimen=(mode==MODE_SEND_MOBILDOCK?DEF_READTIME_MOBILDOCK:DEF_READTIME); + if (mode==MODE_SEND_MOBILDOCK) mode=MODE_SEND; if (!strchr(device,'/')) { size_t l=strlen(device); @@ -863,63 +1977,210 @@ size_t l=strlen(device); s++; if (*s=='%') continue; if (*s=='s') { - if (i) error("!Only one \"%%s\" permitted in lockfile format-string"); + if (i) error(_("!Only one \"%%s\" permitted in lockfile format-string")); i=1; continue; } - error("!Invalid format-character '%c' in lockfile format-string, only \"%%s\" allowed",*s); + error(_("!Invalid format-character '%c' in lockfile format-string, only \"%%s\" allowed"),*s); } if (*logname) { if (!(logf=fopen(logname,"a"))) - error("!Error opening log \"%s\" for append: %m",logname); - logmsg("Starting up: " PACKAGE " " VERSION); + error(_("^!Error opening log \"%s\" for append"),logname); + logmsg(_("Starting up: %s"),PACKAGE " " VERSION); } - genpdu(); + + switch (mode) { + case MODE_SEND: + preparebody(); + genpdu(); + readbody=0; + break; + case MODE_LOGO_SEND: + logoread(); + break; + case MODE_RING_SEND: + ringread(); + break; + case MODE_RECEIVE: break; + default: assert(0); + } + if (readbody) + error(_("Warning: -f / --file is forbidden with mode \"%s\""),MODE_NAME(mode)); + if (smsmode) { + if (!strcmp(smsmode,"pdu" ) || !strcmp(smsmode,"0")) + force_smsmode=FSM_PDU ; + else if (!strcmp(smsmode,"text") || !strcmp(smsmode,"1")) + force_smsmode=FSM_TEXT; + else + error(_("!Unrecognized %s argument \"%s\", supported only: %s"),"-M/--smsmode",smsmode,"pdu/0/text/1"); + } + if (pdusmscmode) { + if (!strcmp(pdusmscmode,"count-in")) + force_pdusmscmode=FPSM_COUNT_IN; + else if (!strcmp(pdusmscmode,"count-out")) + force_pdusmscmode=FPSM_COUNT_OUT; + else if (!strcmp(pdusmscmode,"none")) + force_pdusmscmode=FPSM_NONE; + else + error(_("!Unrecognized %s argument \"%s\", supported only: %s"),"-P/--pdusmscmode",pdusmscmode,"count-in/count-out/none"); + try_pdusmscmode=force_pdusmscmode; + } + + switch (baudn) { + case 2400: portbaud= B2400; break; + case 4800: portbaud= B4800; break; + case 9600: portbaud= B9600; break; + case 19200: portbaud=B19200; break; + case 38400: portbaud=B38400; break; + case 57600: portbaud=B57600; break; + default: + error(_("!Specified baudrate %ld is not supported"),baudn); + } + if (verbose>=2) error(_(".Will use baudrate %ld with hexval 0x%X"),baudn,portbaud); if (lockfile && *lockfile && VARPRINTF(lockreal,lockfile,devicename)>0) { time_t start,end; - if (verbose>=1) error(".Locking device \"%s\" by \"%s\"..",device,lockreal); + if (verbose>=1) error(_(".Locking device \"%s\" by \"%s\".."),device,lockreal); time(&start); - lockdevice(); + lockdevice(0); time(&end); if ((end-=start)>LOCKREPORT) - logmsg("Device lock succeeded after %d seconds",end); + logmsg(_("Device lock succeeded after %ld seconds"),(long)end); } - if (verbose>=1) error(".Opening device \"%s\"..",device); + if (verbose>=1) error(_(".Opening device \"%s\".."),device); if ((devfd=open(device,O_RDWR|O_NDELAY))<0) - error("!Cannot open device \"%s\" for rw-access: %m",device); + error(_("^!Cannot open device \"%s\" for r/w access"),device); if (tcgetattr(devfd,&restios)) - error("Unable to get termios settings: %m"); + error(_("^Unable to get termios settings")); else { restios.c_cflag=(restios.c_cflag&~(CBAUD|CBAUDEX))|B0|HUPCL; restios_yes=1; } - tios.c_iflag=IGNBRK|IGNPAR|IXON|IXOFF; + tios.c_iflag=IGNBRK|IGNPAR|(handshake_rtscts ? 0 : IXON|IXOFF); tios.c_oflag=0; - tios.c_cflag=CS8|CREAD|CLOCAL|B19200|HUPCL; + tios.c_cflag=CS8|CREAD|CLOCAL|HUPCL|portbaud|(handshake_rtscts ? CRTSCTS : 0); tios.c_lflag=IEXTEN|NOFLSH; memset(tios.c_cc,_POSIX_VDISABLE,sizeof(tios.c_cc)); tios.c_cc[VTIME]=0; tios.c_cc[VMIN ]=1; + cfsetispeed(&tios,portbaud); + if (cfsetospeed(&tios,portbaud)|cfsetispeed(&tios,portbaud)) + error(_("^Error setting termios baudrate on device")); if (tcflush(devfd,TCIOFLUSH)) - error("Error flushing termios (TCIOFLUSH) on device: %m"); + error(_("^Error flushing termios (TCIOFLUSH) on device")); if (tcsetattr(devfd,TCSANOW,&tios)) - error("!Unable to set initial termios device settings"); + error(_("^!Unable to set initial termios device settings")); - signal(SIGALRM,(RETSIGTYPE (*)(int))sigalarm); - do { - devcmd("",NULL,"\r\nAT\x1A"); + setalarm(); + +retryall: + devcmd("",NULL,"\r\nAT\033\032"); /* ESCAPE, CTRL-Z */ devcmd(NULL,NULL,"\r\nAT"); smscset(); - devcmd(NULL,NULL,"\r\nAT+CMGF=0"); - devcmd("\n> ",NULL,"\r\nAT+CMGS=%d",(strlen(pdusmsc)+strlen(pdudata))/2); - if (!(s=devcmd(NULL,"\n+CMGS:","!%s%s\x1A",pdusmsc,pdudata))) retrying(); - } while (!s); - while (isspace(*s)) s++; - if (verbose>=1) error("\nMessage successfuly sent with MR: %s",s); + if (mode==MODE_SEND || mode==MODE_RECEIVE) { + cmgf=-1; + do { + /* condition is _negative_ here: */ + if (force_smsmode==FSM_TEXT || !devcmd(NULL,NULL,"!\r\nAT+CMGF=0")) { + if (force_smsmode==FSM_PDU || !devcmd(NULL,NULL,"!\r\nAT+CMGF=1")) + { retrying(); continue; } + /* CMGF=1 */ + if (verbose>=1) + error(_(".Using AT+CMGF=1 (text mode)..")); + cmgf=1; + } + else { + /* CMGF=0 */ + if (verbose>=1) + error(_(".Using AT+CMGF=0 (PDU mode)..")); + cmgf=0; + } + } while (cmgf==-1); + } + switch (mode) { + case MODE_SEND: + if (cmgf) { + devcmd("\n> ",NULL,"\r\nAT+CMGS=\"%s\"",phone); + s=devcmd(NULL,"\n+CMGS:","!~%s\032",body); + } + else { + devcmd("\n> ",NULL,"\r\nAT+CMGS=%d",( + (try_pdusmscmode==FPSM_COUNT_IN ? strlen(pdusmsc) : 0) + +strlen(pdudata))/2); + s=devcmd(NULL,"\n+CMGS:","!~%s%s\032", + (try_pdusmscmode!=FPSM_NONE ? pdusmsc : ""), + pdudata); + if (!s && force_pdusmscmode==FPSM_AUTO) { + if (FPSM_MAX==try_pdusmscmode++) + try_pdusmscmode=FPSM_MIN; + else + retrycnt--; + } + } + break; + case MODE_LOGO_SEND: + case MODE_RING_SEND: { +struct hexdata *hd; + + restore="\r\nAT+CSMP=17,,0,0"; + devcmd(NULL,NULL,"\r\nAT+CSMP=81,,0,245"); + while ((hd=hexdata)) { + devcmd("\n> ",NULL,"\r\nAT+CMGS=\"%s\"",phone); + if (!(s=devcmd(NULL,"\n+CMGS:","!~%s\032",hd->data))) break; + if ((hexdata=hd->next)) pushargstack_one(s,0); + free(hd); + parts++; + } + } break; + case MODE_RECEIVE: + restore="\r\nAT+CNMI=,0"; + devcmd(NULL,NULL,"\r\nAT+CNMI=,2"); + devcmd(NULL,NULL,"\r\nAT+CSDH=0"); + unlockdevice(0); + /* Never bail-out when we got up to this point */ + if (maxretryn!=-1 && verbose>=1) + error(_(".Initialization successful, infinite retry count set")); + maxretryn=-1; +#if RECEIVE_TEST + receive_headerparse(" \"+420602123456\",,\"99/10/25,03:21:03-00\""); + receive_accept("TESTBODY"); + exit(EXIT_SUCCESS); +#endif + datawait(0); + if (!lockdevice(1)) { + if (verbose>=1) + error(_(".Dialout detected, waiting for lock..")); + lockdevice(0); + goto retryall; + } + d1("Lock-device succeeded\n"); + do { + d1("Reading a message for us...\n"); + if (!(s=devcmd("\n","+CMT:"," "))) + goto retryall; + if (cmgf && !(i=receive_headerparse(s))) + error(_("Receive-header parsing failed on: %s"),s); + if (!(s=devcmd("\n","@"," "))) + goto retryall; + if (cmgf) { + if (i) receive_text(s); + } + else receive_pdu(s); + } while (datawait(1)); + goto retryall; + break; + default: assert(0); + } + if (!s) { retrying(); goto retryall; } + + pushargstack_one(s,0); s=NULL; + if (verbose>=1) while ((s=nextargstack())) { + while (isspace(*s)) s++; + error(_("\nMessage successfuly sent with MR (Message Reference): %s"),s); + } devcmd(NULL,NULL,"\r\nAT"); - logmsg("SMS sent (after %d retries), message reference: %s",retrycnt,s); + logmsg(_("SMS sent (after %d retries), %d part(s)"),retrycnt,parts); return(EXIT_SUCCESS); }