New option -w|--waittime as requested by Markus Widauer
[mdsms.git] / mdsms.c
1 #define WANT_DECLARATIONS 1
2 #include "config.h"
3 #ifndef lint
4 static char rcsid[] ATTR_UNUSED = "$Id$";
5 #endif
6
7 #include "setup.h"
8
9 #ifdef HAVE_STDIO_H
10 #include <stdio.h>
11 #endif
12 #ifdef HAVE_STDLIB_H
13 #include <stdlib.h>
14 #endif
15 #ifdef HAVE_STRING_H
16 #include <string.h>
17 #endif
18 #ifdef HAVE_SIGNAL_H
19 #include <signal.h>
20 #endif
21 #ifdef HAVE_STDARG_H
22 #include <stdarg.h>
23 #endif
24 #ifdef HAVE_LIMITS_H
25 #include <limits.h>
26 #endif
27 #ifdef HAVE_CTYPE_H
28 #include <ctype.h>
29 #endif
30 #ifdef HAVE_TERMIOS_H
31 #include <termios.h>
32 #endif
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #ifdef HAVE_ASSERT_H
37 #include <assert.h>
38 #endif
39 #ifdef HAVE_SYS_TYPES_H
40 #include <sys/types.h>
41 #endif
42 #ifdef HAVE_SYS_WAIT_H
43 #include <sys/wait.h>
44 #endif
45 #ifdef HAVE_SYS_STAT_H
46 #include <sys/stat.h>
47 #endif
48 #ifdef HAVE_FCNTL_H
49 #include <fcntl.h>
50 #endif
51 #ifdef HAVE_ERRNO_H
52 #include <errno.h>
53 #endif
54 #ifdef HAVE_TIME_H
55 #include <time.h>
56 #endif
57 #ifdef HAVE_SYS_TIME_H
58 #include <sys/time.h>
59 #endif
60 #ifdef HAVE_SYS_POLL_H
61 #include <sys/poll.h>
62 #endif
63 #ifdef HAVE_LOCALE_H
64 #include <locale.h>
65 #endif
66
67 #ifdef HAVE_GETOPT_LONG
68 #include <getopt.h>
69 #else
70 #include "getopt.h"
71 #endif
72
73
74 /* Always override possible system defintions as it is safe (used by glib) */
75 #undef MAX
76 #define MAX(a,b) ((a)>(b)?(a):(b))
77 #undef MIN
78 #define MIN(a,b) ((a)<(b)?(a):(b))
79
80 #define NELEM(x) (sizeof((x))/sizeof(*(x)))
81
82 #ifndef DEBUG
83 #define dbg(cmd)
84 #else
85 #define dbg(cmd) cmd
86 #endif
87 /* ANSI C does not allow macro with variable arguments */
88 #define dO stderr
89 #define dB(a) dbg(fprintf a)
90
91 #define d1(n1)                      dB((dO,n1                     ))
92 #define d2(n1,n2)                   dB((dO,n1,n2                  ))
93 #define d3(n1,n2,n3)                dB((dO,n1,n2,n3               ))
94 #define d4(n1,n2,n3,n4)             dB((dO,n1,n2,n3,n4            ))
95 #define d5(n1,n2,n3,n4,n5)          dB((dO,n1,n2,n3,n4,n5         ))
96 #define d6(n1,n2,n3,n4,n5,n6)       dB((dO,n1,n2,n3,n4,n5,n6      ))
97 #define d7(n1,n2,n3,n4,n5,n6,n7)    dB((dO,n1,n2,n3,n4,n5,n6,n7   ))
98 #define d8(n1,n2,n3,n4,n5,n6,n7,n8) dB((dO,n1,n2,n3,n4,n5,n6,n7,n8))
99
100 static const char version[]="Mobile Device SMS tool (" PACKAGE " " VERSION ")\n";
101
102 static int verbose
103 #ifdef DEBUG
104         =0xFFFF
105 #endif
106         ;
107 static char *pname;
108 static int dis_cleanup=0,devfd=-1;
109
110 static char *phone,*device,*logname,*lockfile,*smsmode,*pdusmscmode,*smsc,*maxretry,*readtime,*chartime,*cmdtime,*waittime,*baud,*restore;
111 static int readbody;
112 static long maxretryn=DEF_MAXRETRY,readtimen=-1,chartimen=DEF_CHARTIME,cmdtimen=DEF_CMDTIME,waittimen=DEF_WAITTIME,baudn=DEF_BAUD;
113 #ifdef HAVE_CRTSCTS
114 static int handshake_rtscts;
115 static unsigned handshake_stamp;
116 #else
117 #define handshake_rtscts (0)
118 #endif
119 static enum {
120         FSM_AUTO=0,
121         FSM_PDU,
122         FSM_TEXT
123         } force_smsmode=FSM_AUTO;
124 static enum {
125         FPSM_AUTO=0,
126         FPSM_COUNT_IN,
127         FPSM_COUNT_OUT,
128         FPSM_NONE
129         } force_pdusmscmode=FPSM_AUTO,
130 #define FPSM_MIN (FPSM_COUNT_IN)
131 #define FPSM_MAX (FPSM_NONE)
132                 try_pdusmscmode=FPSM_MIN;
133 static size_t bodylen;
134 /* --send / --send-mobildock / --receive specific */
135 static char *body;
136 /* --logo-send specific */
137 static char *logoname,*gsmnet;
138 /* --ring-send specific */
139 static char *ringname;
140 /* --picture-send specific */
141 static char *picturename;
142
143 static enum modenum {
144   MODE_UNKNOWN=0,
145 /* must differ from regular char-s */
146   MODE_FIRST         =0x3400,
147         MODE_SEND          =MODE_FIRST+0, /* --send / --send-mobildock */
148         MODE_SEND_MOBILDOCK=MODE_FIRST+1, /* --send-mobildock in before readtimen is set */
149         MODE_RECEIVE       =MODE_FIRST+2, /* --receive */
150         MODE_LOGO_SEND     =MODE_FIRST+3, /* --logo-send */
151         MODE_RING_SEND     =MODE_FIRST+4, /* --ring-send */
152         MODE_PICTURE_SEND  =MODE_FIRST+5  /* --picture-send */
153         } mode=MODE_UNKNOWN;
154 #define MODE_ORDER(x) ((x)-MODE_FIRST)
155 #define MODE_NAME(x) (longopts[MODE_ORDER((x))].name)
156 #define MODE_BIT(x) (1<<MODE_ORDER((x)))
157
158 static unsigned mode_stamp;
159
160 /* pdusmsc variable has to be filled in */
161 #define NEED_PDUSMSC() (mode==MODE_SEND)
162
163 static char *devicename; /* path stripped */
164 static char lockreal[512],locked;
165
166 static struct termios restios,tios;
167 static char restios_yes;
168 static FILE *logf;
169
170 static void vlogmsg(char pm,char fatal,const char *fmt,va_list ap) ATTR_PRINTFORMAT(3,0);
171 static void vlogmsg(char pm,char fatal,const char *fmt,va_list ap)
172 {
173 time_t stamp;
174 char *ctm,*s;
175 pid_t mypid=-1;
176 char host[LINE_MAX];
177
178         if (!logf) return;
179         if (mypid==-1) {
180                 mypid=getpid();
181                 if (gethostname(host,sizeof(host))) strcpy(host,_("<ERROR>"));
182                 }
183         time(&stamp);
184         ctm=ctime(&stamp);
185         if ((s=strchr(ctm,'\n'))) *s='\0';
186         fprintf(logf,"%s %s %s[%d]: ",ctm,host,pname,mypid);
187         vfprintf(logf,fmt,ap);
188         if (pm) { fputs(": ",logf); fputs(strerror(errno),logf); }
189         if (fatal!='\n') fputc((fatal=='.'?'.':'!'),logf);
190         fputc('\n',logf);
191         fflush(logf);
192 }
193
194 static void logmsg(const char *fmt,...) ATTR_PRINTFORMAT(1,2);
195 static void logmsg(const char *fmt,...)
196 {
197 va_list ap;
198         va_start(ap,fmt);
199         vlogmsg(0,'\n',fmt,ap);
200         va_end(ap);
201 }
202
203 static void error(const char *fmt,...) ATTR_PRINTFORMAT(1,2);
204 static void error(const char *fmt,...)
205 {
206 va_list ap;
207 char fatal,pm;
208
209         if ((pm=(*fmt=='^'))) fmt++;
210         fatal=*fmt;
211         if (fatal=='!' || fatal=='.' || fatal=='\n') fmt++;
212         else fatal=0;
213
214         fprintf(stderr,"%s: ",pname);
215         va_start(ap,fmt);
216         vfprintf(stderr,fmt,ap);
217         if (fatal=='!') vlogmsg(pm,fatal,fmt,ap);
218         va_end(ap);
219         if (pm) { fputs(": ",stderr); fputs(strerror(errno),stderr); }
220         if (fatal!='\n') fputc((fatal=='.'?'.':'!'),stderr);
221         fputc('\n',stderr);
222         if (fatal=='!') exit(EXIT_FAILURE);
223 }
224
225 static void chk(const void *p)
226 {
227         if (p) return;
228         error(_("!Virtual memory exhausted"));
229 }
230
231 static char *devcmd(const char *term,const char *catch,const char *send,...) ATTR_PRINTFORMAT(3,4);
232
233 static void unlockdevice(int hard)
234 {
235         d2("unlockdevice(), locked=%d\n",locked);
236         if (!locked || !*lockreal) return;
237         if (!hard && locked>1) { locked--; return; }
238         d2("Removing lockfile \"%s\"\n",lockreal);
239         if (unlink(lockreal))
240                 error(_("^Error removing my device lockfile \"%s\""),lockreal);
241         locked=0;
242 }
243
244 static void cleanup(void)
245 {
246         d1("cleanup()\n");
247         if (dis_cleanup) return;
248         if (restore) {
249 char *cmd=restore;
250                 restore=NULL;
251                 devcmd(NULL,NULL,"\r\nAT");
252                 devcmd(NULL,NULL,cmd);
253                 devcmd(NULL,NULL,"\r\nAT");
254                 }
255         if (restios_yes) {
256                 if (tcsetattr(devfd,TCSANOW,&restios))
257                         error(_("^Error restoring termios for device"));
258                 restios_yes=0;
259                 }
260         unlockdevice(1);
261         dis_cleanup=1;
262         exit(EXIT_FAILURE);
263 }
264
265 static void usage(void)
266 {
267         fprintf(stderr,_("\
268 \n\
269 %s\
270 \n\
271 Usage: %s [-c|--config <cfgfile>] [-d|--device <device>]\n\
272              [-L|--log <file>] [-l|--lockfile <lock>]\n\
273              [-b|--baud <rate>] [-x|--xonxoff] [-C|--rtscts]\n\
274              [-M|--smsmode <mode>] [-P|--pdusmscmode <mode>]\n\
275              [-s|--smsc <smsc #>] [-m|--maxretry <#>]\n\
276              [-r|--readtime <sec>] [-t|--chartime <msec>] [-T|--cmdtime <msec>]\n\
277              [-w|--waittime <sec>] [-v|--verbose] [-h|--help] [-V|--version]\n\
278              {--send | --send-mobildock | --receive | --logo-send}\n\
279   --send / --send-mobildock:\n\
280              [-f|--file] <dest. phone> <msg text|msg filename>\n\
281   --receive:\n\
282              <command name>\n\
283   --logo-send:\n\
284              <dest. phone> <logo filename> [<GSMnet id>]\n\
285   --ring-send:\n\
286              <dest. phone> <ring filename>\n\
287   --picture-send:\n\
288              <dest. phone> <picture .ras filename>\n\
289 \n\
290  -c, --config\tRead this additional config file\n\
291 \t\t(def. \"%s\" and \"$HOME%s\")\n\
292  -d, --device\tMobile on this serial device (def. \"%s\")\n\
293  -L, --log\tLog all important messages to this file (def. \"%s\")\n\
294  -l, --lockfile\tLock serial port by this file, \"%%s\" is basename of device\n\
295 \t\t(def. \"%s\")\n\
296  -b, --baud\tSet baudrate, 2400-57600 supported (def. %d)\n\
297  -x, --xonxoff\tUse XON/XOFF (AKA software) serial port handshaking - default\n\
298  -C, --rtscts\tUse RTS/CTS (AKA hardware) serial port handshaking%s\n\
299  -M, --smsmode\tForce SMS as: \"pdu\" or 0: PDU mode, \"text\" or 1: text mode\n\
300  -P, --pdusmscmode\tForce PDU as: \"count-in\", \"count-out\", \"none\"\n\
301  -s, --smsc\tUse this SMS Center number (def. query from mobile)\n\
302  -m, --maxretry\tMaximum retries of any command before giving up (def. %d)\n\
303  -r, --readtime\tSeconds for maximum wait time for response\n\
304 \t\t(def. %ds standard, %ds for MobilDock modes,\n\
305 \t\t multiplied %dx for long cmds)\n\
306  -t, --chartime\tMilliseconds between each char (def. %dms)\n\
307  -T, --cmdtime\tMilliseconds before each whole AT command (def. %dms)\n\
308  -w, --waittime\tSeconds to prevent timeout of 9110 FaxModem (def. %ds)\n\
309  -v, --verbose\tIncrease verbosity level, more \"-v\"s give more messages\n\
310  -h, --help\tPrint a summary of the options\n\
311  -V, --version\tPrint the version number\n\
312 \n\
313 --send / --send-mobildock:\n\
314  -f, --file\tRead contents of message from file instead\n\
315 --receive:\n\
316  <command name>\tProgram to run on receive, message will be on stdin\n\
317 \t\tFollowing substitutes are recognized:\n\
318 \t\t%%p - source phone number\n\
319 \t\t%%T - timestamp from SMSC as # of seconds from 1970 (-1 if invalid)\n\
320 \t\t%%t - ctime(3) style timestamp (e.g. \"Wed Jun 30 21:49:08 1993\"),\n\
321 \t\t     empty string if invalid\n\
322 \t\t%%s - originating SMSC number, if available (else empty)\n\
323 --logo-send:\n\
324  <GSMnet id>\t* Oper. logo: Enter custom network code MccMnc, e.g. 23002\n\
325 \t\t* Oper. logo: Specify \"%s\" to read network code from NOL file\n\
326 \t\t* Group gfx : Specify \"%s\" to send logo as group graphics\n\
327 \n\
328 You may need to use the following line to catch all of this help text:\n\
329 ./mdsms -h 2>&1|more\n\
330 \n"),version,PACKAGE,CONFIG_MAIN,CONFIG_HOME,DEF_DEVICE,DEF_LOGNAME,DEF_LOCKFILE,DEF_BAUD,
331 #ifdef HAVE_CRTSCTS
332                 "",
333 #else
334                 _("\n\t\t(Not supported on this platform!)"),
335 #endif
336 DEF_MAXRETRY,DEF_READTIME,DEF_READTIME_MOBILDOCK,EXT_READTIME,DEF_CHARTIME,DEF_CMDTIME,DEF_WAITTIME,
337 WORD_NET,WORD_GROUP);
338         exit(EXIT_FAILURE);
339 }
340
341 static const struct option longopts[]={
342 /* Modes has to be in-order on exact positions */
343 {"send"          ,0,0,MODE_SEND},
344 {"send-mobildock",0,0,MODE_SEND_MOBILDOCK},
345 {"receive"       ,0,0,MODE_RECEIVE},
346 {"logo-send"     ,0,0,MODE_LOGO_SEND},
347 {"ring-send"     ,0,0,MODE_RING_SEND},
348 {"picture-send"  ,0,0,MODE_PICTURE_SEND},
349 /* Mode aliases may follow in no particular order *
350  * as long as no non-mode options is between them */
351 {"send-md"       ,0,0,MODE_SEND_MOBILDOCK},
352 {"recv"          ,0,0,MODE_RECEIVE},
353 {"logo"          ,0,0,MODE_LOGO_SEND},
354 {"ring"          ,0,0,MODE_RING_SEND},
355 {"picture"       ,0,0,MODE_PICTURE_SEND},
356 {"config"      ,1,0,'c'},
357 {"device"      ,1,0,'d'},
358 {"log"         ,1,0,'L'},
359 {"lockfile"    ,1,0,'l'},
360 {"baud"        ,1,0,'b'},
361 {"xonxoff"     ,0,0,'x'},
362 {"rtscts"      ,0,0,'C'},
363 {"smsmode"     ,1,0,'M'},
364 {"pdusmscmode" ,1,0,'P'},
365 {"smsc"        ,1,0,'s'},
366 {"maxretry"    ,1,0,'m'},
367 {"readtime"    ,1,0,'r'},
368 {"chartime"    ,1,0,'t'},
369 {"cmdtime"     ,1,0,'T'},
370 {"waittime"    ,1,0,'w'},
371 {"file"        ,0,0,'f'},
372 {"verbose"     ,0,0,'v'},
373 {"help"        ,0,0,'h'},
374 {"version"     ,0,0,'V'},
375 {NULL          ,0,0,0  }};
376
377 static void processargs(int argp,char **args,const char *from);
378
379 static char *cfgstack[MAXCFGLOOP];
380 static unsigned cfgstacki=0;
381
382 static void chkfclose(FILE *f,const char *fname)
383 {
384         if (fclose(f))
385                 error(_("^Error closing \"%s\""),fname);
386 }
387
388 static long getfilesize(FILE *f,const char *fname)
389 {
390 long size;
391
392         if (fseek(f,0,SEEK_END))
393                 error(_("^Error seeking to end of \"%s\""),fname);
394         if ((size=ftell(f))<0)
395                 size=-1,error(_("^Error measuring length of \"%s\""),fname);
396         rewind(f);
397         return(size);
398 }
399
400 static void readfile(const char *fname,char quiet)
401 {
402 FILE *f;
403 size_t got;
404 char *args[MAXCFGARGS],*d,*s,blank,quote;
405 unsigned argp;
406 char *buf;
407 long size;
408 static unsigned tot=0;
409
410         if (tot++>=MAXCFGNUM) {
411                 if (tot==MAXCFGNUM+1) error(_("Too many config files to read, max is %d, break-out"),MAXCFGNUM);
412                 return;
413                 }
414         if (!(f=fopen(fname,"rt"))) {
415                 if (!quiet) error(_("^Can't open config file \"%s\" for r/o"),fname);
416                 return;
417                 }
418                 
419         if (verbose>=2) error(_(".Reading config file \"%s\""),fname);
420         if ((size=getfilesize(f,fname))==-1) size=0;
421         if (size>MAXCONFIG) 
422                 error(_("File \"%s\" is too long, read only %d bytes"),fname,MAXCONFIG);
423         chk(buf=malloc((size?size:MAXCONFIG)+1));
424         got=fread(buf,1,(size?size:MAXCONFIG),f);
425         if (size && got!=size)
426                 error(_("File \"%s\" read error, got only %u bytes of %ld"),fname,got,size);
427         chkfclose(f,fname);
428         buf[got]='\0';
429         args[0]=pname;
430         for (argp=1,d=s=buf,blank=1,quote=0;s<buf+got;s++) {
431 char c=*s;
432
433                 if (!quote && isspace(c)) {
434                         if (!blank) {
435                                 *d='\0';
436                                 blank=1;
437                                 if (verbose>=2) error(_("\nConfig \"%s\": arg#%d: %s"),fname,argp-1,args[argp-1]);
438                                 }
439                         continue;
440                         }
441                 if (blank) {
442                         if (argp>=NELEM(args)-1) {
443                                 error(_("Too many arguments in \"%s\", from offset %d ignored"),fname,s-buf);
444                                 break;
445                                 }
446                         args[argp++]=s;
447                         d=s;
448                         blank=0;
449                         }
450                 if (c=='\\') { *d++=*++s; continue; }
451                 if (c=='"' || c=='\'') {
452                         if (!quote   ) { quote=c; continue; }
453                         if ( quote==c) { quote=0; continue; }
454                         /* FALLTHRU */
455                         }
456                 *d++=c;
457                 }
458         args[argp]=NULL;
459         processargs(argp,args,fname);
460         free(buf);
461 }
462
463 static struct argstack {
464         struct argstack *next;
465         int num,offset;
466         const char *from;
467         char *arg[1];
468         } *argstack;
469
470 static struct argstack **argstack_tail=&argstack;
471 static size_t lastargstack_len;
472 static const char *lastargstack_from;
473 static int lastargstack_index;
474
475 static size_t argstack_size;
476 static int argstack_num;
477
478 static void pushargstack(char **args,int num,int offset,const char *from,char stack)
479 {
480 struct argstack *as;
481 int i;
482
483         if (!num) return;
484         assert(num>=1);
485         chk(as=malloc(sizeof(*as)+sizeof(as->arg)*(num-1)));
486         as->num=num;
487         as->offset=offset;
488         if (!from) as->from=NULL;
489         else chk(as->from=strdup(from));
490         for (i=0;i<num;i++) {
491                 chk(as->arg[i]=strdup(args[i]));
492                 argstack_size+=strlen(args[i]);
493                 }
494         argstack_num+=num;
495         if (stack) {
496                 as->next=argstack;
497                 argstack=as;
498                 }
499         else {
500                 as->next=NULL;
501                 *argstack_tail=as;
502                 argstack_tail=&as->next;
503                 }
504 }
505
506 static void pushargstack_one(char *s,char stack)
507 { pushargstack(&s,1,0,NULL,stack); }
508
509 static char *nextargstack(void)
510 {
511 static int order=0;
512 char *r;
513
514         if (argstack && order==argstack->num) {
515 struct argstack *as=argstack;
516                 if (!(argstack=as->next))
517                         argstack_tail=&argstack;
518                 order=0;
519                 free((char *)as->from);
520                 lastargstack_from=NULL;
521                 free(as);
522                 }
523         if (!argstack) {
524                 assert(!argstack_num); assert(!argstack_size);
525                 return(NULL);
526                 }
527         assert(order<argstack->num);
528         lastargstack_index=argstack->offset+order;
529         r=argstack->arg[order++];
530         assert(argstack_num>0); argstack_num--;
531         lastargstack_len=strlen(r);
532         assert(argstack_size>=lastargstack_len); argstack_size-=lastargstack_len;
533         lastargstack_from=argstack->from;
534         return(r);
535 }
536
537 static char *glueargstack(size_t *destlenp,const char *glue)
538 {
539 size_t gluel=(glue?strlen(glue):0),destlen;
540 char *dest,*d,*s;
541
542         if (!argstack_num) {
543                 chk(dest=strdup(""));
544                 if (destlenp) *destlenp=0;
545                 return(dest);
546                 }
547         destlen=argstack_size+(argstack_num-1)*gluel;
548         if (destlenp) *destlenp=destlen;
549         chk(dest=malloc(destlen+1));
550         for (d=dest;(s=nextargstack());) {
551                 memcpy(d,s,lastargstack_len);
552                 free(s);
553                 d+=lastargstack_len;
554                 if (!argstack_num) break;
555                 if (!glue) continue;
556                 memcpy(d,glue,gluel);
557                 d+=gluel;
558                 assert(d<=dest+destlen);
559                 }
560         assert(!argstack_num);
561         assert(d==dest+destlen);
562         *d='\0';
563         return(dest);
564 }
565
566 static struct {
567         const char c;
568         char **const var;
569         unsigned stamp;
570         } optset[]={
571                 { 'd',&device       },
572                 { 'L',&logname      },
573                 { 'l',&lockfile     },
574                 { 'b',&baud         },
575                 { 'M',&smsmode      },
576                 { 'P',&pdusmscmode  },
577                 { 's',&smsc         },
578                 { 'm',&maxretry     },
579                 { 'r',&readtime     },
580                 { 't',&chartime     },
581                 { 'T',&cmdtime      },
582                 { 'w',&waittime     },
583         };
584
585 static void processargs(int argp,char **args,const char *from)
586 {
587 int optc;
588 static unsigned seq=0;
589 int i;
590
591         seq++;
592         optarg=NULL; optind=0; /* FIXME: Possible portability problem. */
593         while ((optc=getopt_long(argp,args,"c:d:L:l:b:xCM:P:s:m:r:t:T:w:fvhV",longopts,NULL))!=EOF) switch (optc) {
594                 case 'c':
595                         if (cfgstacki>=NELEM(cfgstack)) {
596                                 error(_("Looping (%d) during attempt to read config file \"%s\", break-out"),NELEM(cfgstack),from);
597                                 break;
598                                 }
599                         chk(cfgstack[cfgstacki++]=strdup(optarg));
600                         break;
601                 case 'd': case 'L': case 'b': case 'l': case 'M': case 'P': case 's': case 'm': case 'r': case 't': case 'T': case 'w':
602                         for (i=0;i<NELEM(optset);i++)
603                                 if (optset[i].c==optc) {
604                                         if (optset[i].stamp && optset[i].stamp!=seq) {
605                                                 assert(!!*optset[i].var);
606                                                 break;
607                                                 }
608                                         free(*optset[i].var);
609                                         chk(*optset[i].var=strdup(optarg));
610                                         optset[i].stamp=seq;
611                                         break;
612                                         }
613                         assert(i<NELEM(optset));
614                         break;
615                 case 'x': case 'C':
616 #ifdef HAVE_CRTSCTS
617                         if (handshake_stamp && handshake_stamp!=seq) break;
618                         handshake_rtscts=(optc=='C');
619                         handshake_stamp=seq;
620 #else
621                         if (optc=='C')
622                                 error(_("!RTS/CTS handshake NOT supported on this platform! Occured during parsing option %d from \"%s\""),optind-1,from);
623 #endif
624                         break;
625                 case MODE_SEND:
626                 case MODE_SEND_MOBILDOCK:
627                 case MODE_RECEIVE:
628                 case MODE_LOGO_SEND:
629                 case MODE_RING_SEND:
630                 case MODE_PICTURE_SEND:
631                         if (mode_stamp && mode_stamp!=seq) break;
632                         mode=optc;
633                         mode_stamp=seq;
634                         break;
635                 case 'f':
636                         readbody++;
637                         break;
638                 case 'v':
639 #ifndef DEBUG   /* prevent suppositious overflow */
640                         verbose++;
641 #endif
642                         break;
643                 case 'V':
644                         fprintf(stderr,version);
645                         exit(EXIT_FAILURE);
646                 default:
647                         if (optc!='h')
648                                 error(_("\nLast getopt(3) error occured during parsing option %d from \"%s\"! Follows help:"),optind-1,from);
649                         usage();
650                         break;
651                 }
652         pushargstack(args+optind,argp-optind,optind,from,1);
653         while (cfgstacki) {
654 char *s=cfgstack[--cfgstacki];
655
656                 assert(cfgstacki>=0);
657                 readfile(s,0);
658                 free(s);
659                 assert(cfgstacki>=0 && cfgstacki<NELEM(cfgstack));
660                 }
661 }
662
663 static const struct nullcheck {
664         char **var;
665         enum modenum reqd;
666         const char *name;
667         } nullcheck[]={
668                 {&phone,MODE_BIT(MODE_SEND)
669                        |MODE_BIT(MODE_SEND_MOBILDOCK)
670                        |MODE_BIT(MODE_LOGO_SEND)
671                        |MODE_BIT(MODE_RING_SEND)
672                        |MODE_BIT(MODE_PICTURE_SEND),
673                         N_("destination phone number")},
674                 {&   logoname,MODE_BIT(   MODE_LOGO_SEND),N_(   "logo filename")},
675                 {&   ringname,MODE_BIT(   MODE_RING_SEND),N_(   "ring filename")},
676                 {&picturename,MODE_BIT(MODE_PICTURE_SEND),N_("picture filename")},
677                 {&body,MODE_BIT(MODE_RECEIVE),N_("body text")}, /* we allow empty bodies for SENDs */
678 #if 0
679                 {&gsmnet,MODE_BIT(MODE_LOGO_SEND),N_("GSM operator network code")},
680                 {&device,0,N_("device for communication")},
681 #endif
682         };
683 static char **emptycheck[]={&logname,&smsc,&logoname,&gsmnet};
684
685 static inline void emptyclean(void)
686 {
687 int i;
688
689         for (i=0;i<NELEM(emptycheck);i++)
690                 if (*emptycheck[i] && !**emptycheck[i]) {
691                         free(*emptycheck[i]);
692                              *emptycheck[i]=NULL;
693                         }
694 }
695
696 static inline void cmdline_done(void)
697 {
698 char *s;
699         while ((s=nextargstack())) {
700                 error(_("\nExcessive option %d from \"%s\" ignored: %s"),
701                         lastargstack_index,lastargstack_from,s);
702                 free(s);
703                 }
704         emptyclean();
705 }
706
707 static char *check_phone(const char *phone)
708 {
709 const char *s,*s1;
710 static char err[LINE_MAX];
711
712         for (s=s1=(phone+(*phone=='+'));*s && s-s1<MAXNUMLEN;s++)
713                 if (!isdigit(*s)) {
714                         VARPRINTF2(err,_("Invalid digit '%c' in phone number - at offset %d"),
715                                 *s,s-phone);
716                         return(err);
717                         }
718         if (!*s) return(NULL);
719         VARPRINTF2(err,_("Phone number too long (%d), max. %d digits allowed"),
720                 strlen(s1),MAXNUMLEN);
721         return(err);
722 }
723
724 static void cmdline_phone(void)
725 {
726         if (!phone && (phone=nextargstack())) {
727 char *s;
728
729                 if ((s=check_phone(phone)))
730                         error(_("!%s in option %d from \"%s\": %s"),
731                                         s,lastargstack_index,lastargstack_from,phone);
732                 }
733 }
734
735 static inline void cmdline_receive(void)
736 {
737 char *s;
738
739         if (!body && argstack_num) {
740                 body=glueargstack(&bodylen," ");
741                 for (s=body;(s=strchr(s,'%'));s++)
742                         switch (*++s) {
743                                 case 'p': case 'T': case 't': case 's': break;
744                                 default:
745                                         error(_("Unknown formatsymbol '%c' (use \"%%%%%c\" to fix it) at pos %d in: %s"),
746                                                 *s,*s,s-body,body);
747                                 }
748                 }
749 }
750
751 static inline void cmdline_send(void)
752 {
753         cmdline_phone();
754         if (!body && argstack_num)
755                 body=glueargstack(&bodylen," ");
756 }
757
758 static inline void cmdline_logo_send(void)
759 {
760 char *ogsmnet;
761
762         cmdline_phone();
763         if (!logoname) logoname=nextargstack();
764         if (!gsmnet && (ogsmnet=nextargstack())) {
765 char *s,*d,e=0;
766
767                 chk(gsmnet=strdup(ogsmnet));
768                 if (strtrycasecmp(gsmnet,WORD_NET) && strtrycasecmp(gsmnet,WORD_GROUP)) {
769                         for (d=s=gsmnet;*s;s++) {
770                                 if (isdigit(*s)) { *d++=*s; continue; }
771                                 if (isspace(*s)) continue;
772                                 error(_("\nInvalid characted '%c' in GSMnet at offs %d: %s"),
773                                         *s,s-gsmnet,ogsmnet);
774                                 e=1;
775                                 break;
776                                 }
777                         if ((d-gsmnet)!=5) {
778                                 error(_("\nGSMnet is required to have exactly 5 digits or to be\n\
779 either \"%s\" or \"%s\", but found length %d: %s"),
780                                         WORD_NET,WORD_GROUP,d-gsmnet,ogsmnet);
781                                 e=1;
782                                 }
783                         if (!e) *d='\0';
784                         else {
785                                 error(_("\nGSMnet option %d from \"%s\" rejected due to previous errors: %s"),
786                                         lastargstack_index,lastargstack_from,ogsmnet);
787                                 free(gsmnet);
788                                 gsmnet=NULL;
789                                 }
790                         }
791                 }
792 }
793
794 static inline void cmdline_ring_send(void)
795 {
796         cmdline_phone();
797         if (!ringname) ringname=nextargstack();
798 }
799
800 static inline void cmdline_picture_send(void)
801 {
802         cmdline_phone();
803         if (!picturename) picturename=nextargstack();
804 }
805
806 static void lockclose(int fd)
807 {
808         if (close(fd))
809                 error(_("Error closing lockfile \"%s\""),lockreal);
810 }
811
812 static int lockdevice(int attempt)
813 {
814 int fd=-1;
815 char buf[64];
816 ssize_t got;
817 int delay=0;
818 char empty=0;
819 pid_t pid;
820
821         d2("lockdevice(), locked=%d\n",locked);
822         if (locked) return (++locked);
823         for (;;) {
824                 if (fd!=-1) lockclose(fd);
825 recheck:
826                 if (delay) sleep(delay);
827                 delay=DEVLOCK_PERIOD;
828                 if (verbose>=3) error(_(".Checking the lockfile \"%s\".."),lockreal);
829                 if ((fd=open(lockreal,O_RDONLY))==-1) break;
830                 if ((got=read(fd,buf,sizeof(buf)-1))<=0) {
831 isempty:
832                         if (empty>=DEVLOCK_MAXEMPTY) {
833                                 error(_(".Lockfile \"%s\" is still not valid, removing it"),lockreal);
834                                 goto remove;
835                                 }
836                         empty++;
837                         continue;
838                         }
839                 assert(got<sizeof(buf));
840                 buf[got]='\0';
841                 if (sscanf(buf,"%d",&pid)!=1) goto isempty;
842                 empty=0;
843                 errno=0;
844                 if (kill(pid,0) && errno!=ESRCH && errno!=EPERM)
845                         error(_("^Error during checking consciousness of PID %d"),pid);
846                 if (errno!=ESRCH) {
847                         if (attempt) return(0);
848                         continue;
849                         }
850                 error(_(".Lockfile \"%s\" is stale (PID %d), removing it"),lockreal,pid);
851 remove:
852                 lockclose(fd);
853                 if (unlink(lockreal))
854                         error(_("^Error removing foreign lockfile \"%s\""),lockreal);
855                 break;
856                 }
857         errno=0;
858         if ((fd=open(lockreal,O_WRONLY|O_CREAT|O_EXCL,0644))==-1) {
859                 if (errno==EEXIST) goto recheck;
860                 error(_("^!Error creating lockfile \"%s\""),lockreal);
861                 }
862         locked=1;
863         got=VARPRINTF(buf,"%010d\n",getpid()); assert(got==11);
864         if (write(fd,buf,got)!=got)
865                 error(_("^!Error writing data to lockfile \"%s\""),lockreal);
866         lockclose(fd);
867         return((locked=1));
868 }
869
870 static char wasalarm=0;
871 static void sigalarm(int signo);
872
873 static void setalarm(void)
874 {
875         signal(SIGALRM,(RETSIGTYPE (*)(int))sigalarm);
876 #ifdef HAVE_SIGINTERRUPT
877         siginterrupt(SIGALRM,1);
878 #endif
879 }
880
881 static void sigalarm(int signo)
882 {
883         setalarm();
884         wasalarm=1;
885         if (verbose>=1) error(_("Timed out"));
886 }
887
888 static void blocking(char yes)
889 {
890 static char state=-1;
891         if (state==yes) return;
892         if (fcntl(devfd,F_SETFL,(yes?0:O_NONBLOCK)))
893                 error(_("^!fcntl() on device for %s mode"),(yes?_("blocking"):_("non-blocking")));
894         state=yes;
895 }
896
897 static const char *record,*recordend;
898 static char *catchdata;
899 static size_t catchdatal,catchdatasiz;
900
901 static const char *reform(const char *s,int slot);
902 static void catched(const char *end,char edata)
903 {
904 size_t len;
905 const char *p;
906
907         if (!record) return;
908         assert(end>=record);
909         p=memchr(record,edata,end-record);
910         if ((len=(p?p:end)-record)) {
911                 if (!catchdata)
912                         chk(catchdata=malloc((catchdatasiz=LINE_MAX)));
913                 if (catchdatal+len>catchdatasiz)
914                         chk(catchdata=realloc(catchdata,
915                                 (catchdatasiz=(catchdatal+len)*2)));
916                 memcpy(catchdata+catchdatal,record,len);
917                 catchdatal+=len;
918                 }
919         record   =(p?NULL:end);
920         recordend=(p?p   :end);
921         assert(catchdatal<=catchdatasiz);
922 }
923
924 static int retrycnt=0;
925 static void retrying(void)
926 {
927         if (maxretryn>=0 && ++retrycnt>=maxretryn) error(_("!Maximum command retry count (%ld) exceeded"),maxretryn);
928         if (verbose>=2) error(_(".Retrying phase, %d out of %ld.."),retrycnt,maxretryn);
929 }
930
931 static const char *reform(const char *s,int slot)
932 {
933 static struct formslot {
934         char *s;
935         size_t l;
936         } arr[3];
937 char c,*d;
938 struct formslot *fs;
939
940         assert(slot>=0 && slot<NELEM(arr));
941         if (!s) return(_("<unset>"));
942         if (!(fs=&arr[slot])->s)
943                 chk(fs->s=malloc(fs->l=LINE_MAX));
944         d=fs->s;
945         for (*d++='"';(c=*s);s++) {
946                 if (d>=fs->s+fs->l-10) {
947 off_t o=d-fs->s;
948                         chk(fs->s=realloc(fs->s,(fs->l=(fs->l?fs->l*2:LINE_MAX))));
949                         d=fs->s+o;
950                         }
951                 if (c!='\\' && c!='"' && isprint(c)) { *d++=c; continue; }
952                 *d++='\\';
953                 switch (c) {
954                         case '\\': case '"': *d++=c; break;
955                         case '\n': *d++='n'; break;
956                         case '\r': *d++='r'; break;
957                         case '\032': *d++='Z'; break;
958                         case '\033': *d++='e'; break;
959                         default:
960                                 d+=sprintf(d,"x%02X",(unsigned char)c);
961                                 break;
962                         }
963                 }
964         *d++='"'; *d='\0';
965         return(fs->s);
966 }
967
968 static char devcmd_empty_return='\0'; /* returned as catch when only newlines found */
969
970 static char *devcmd(const char *term,const char *catch,const char *send,...) ATTR_PRINTFORMAT(3,4);
971 static char *devcmd(const char *term,const char *catch,const char *send,...)
972 {
973 size_t l,bufl2,terml,catchl=0 /* GCC happiness */,fragl,offs;
974 static char buf[LINE_MAX];
975 static size_t bufl;
976 ssize_t got;
977 char *hit,*s;
978 va_list ap;
979 char errout,extend,catch_any,edata;
980 long alarmtime;
981 const char *osend;
982 static const char emptystring[]="";
983 size_t discard;
984
985         if (!term) term="\nOK\n";
986         if (!strcmp(send," ")) send=NULL; /* GCC formatstring-check workaround */
987         if (verbose>=2) error(_(".devcmd(sendfmt=%s,term=%s,catch=%s)"),
988                 reform(send,0),reform(term,1),reform(catch,2));
989         if (!(osend=send)) send="";
990         if ((catch_any=(catch && !strcmp(catch,"@")))) catch=NULL;
991         if ((errout=(*send=='!'))) send++;
992         errout|=(maxretryn==-1);
993         if ((extend=(*send=='~'))) send++;
994         alarmtime=readtimen*(extend?EXT_READTIME:1);
995         buf[bufl]='\0'; /* for d8() below */
996         d8("devcmd(), alarmtime=%ld, errout=%d, extend=%d, catch_any=%d, osend=%p, bufl=%d, buf: %s\n",
997                 alarmtime,errout,extend,catch_any,osend,bufl,reform(buf,0));
998         assert(!catch || !strchr(catch,'\r')); /* we are no longer supporting 'noconvcr'! */
999         assert(!term  || !strchr(term ,'\r'));
1000         if (0) {
1001 err:
1002                 alarm(0);
1003                 if (errout) return(NULL);
1004                 retrying();
1005                 }
1006         catchdatal=0;
1007         if (osend) {
1008                 bufl=0;
1009                 d1("Resetting bufl.\n");
1010                 va_start(ap,send);
1011                 l=VARVPRINTF(buf,send,ap); bufl=l+(!!osend);
1012                 va_end(ap);
1013                 if (bufl>=sizeof(buf)-1) error(_("!Command too big (%d>%d)"),bufl,sizeof(buf)-1);
1014                 if (verbose>=2) error(_(".devcmd formatted send=%s%s"),reform(buf,0),(osend?"+\"\\r\"":""));
1015                 if (osend) buf[l]='\r';
1016                 for (offs=0,got=0;offs<bufl;offs++) {
1017                         alarm(MAXSENDTIME);
1018                         usleep((offs?chartimen:cmdtimen)*1000);
1019                         if (!offs && tcflush(devfd,TCIOFLUSH))
1020                                 error(_("^Error flushing I/O queue of device"));
1021                         if (write(devfd,buf+offs,1)!=1) break;
1022                         got++;
1023                         if (tcdrain(devfd))
1024                                 error(_("^Error forcing output of char at pos %d of cmd %s"),offs,reform(buf,0));
1025                         }
1026                 alarm(0);
1027                 if (got!=bufl) {
1028                         error(_("^Wrote only %d of %d bytes of command"),got,bufl);
1029                         goto err;
1030                         }
1031                 }
1032
1033         if (!(terml=strlen(term))) {
1034                 assert(!catch); assert(!catch_any);
1035                 return(NULL);
1036                 }
1037         if (catch) {
1038                 catchl=strlen(catch);
1039                 fragl=MAX(terml,catchl);
1040                 }
1041         else fragl=terml;
1042         fragl=MAX(fragl,MAX(strlen(ERROR_SUBSTR1),strlen(ERROR_SUBSTR2)));
1043         record=recordend=NULL;
1044         wasalarm=0;
1045         alarm(alarmtime);
1046         edata='\n';
1047         if (!osend) {
1048                 /* "bufl" important */
1049                 goto skipread;
1050                 }
1051         for (;;) {
1052                 blocking(0);
1053                 errno=0;
1054                 got=read(devfd,buf+bufl,sizeof(buf)-1-bufl);
1055                 if (got==-1 && errno==EAGAIN) {
1056                         blocking(1);
1057                         errno=0;
1058                         got=read(devfd,buf+bufl,1);
1059                         }
1060                 if (got<=0) {
1061                         buf[bufl]='\0'; /* for strspn() below */
1062                         if (!strcmp(term,"\n") && catch /* written to trap on 'devcmd("\n","+CMT:"," ")' */
1063                             && bufl==strspn(buf,"\n" /* accept */)) { /* only newlines found */
1064                                 if (verbose>=2)
1065                                         error(_(".Blank (%d newlines) input read, ignoring it"),bufl);
1066                                 bufl=0; /* discard newlines */
1067                                 return(&devcmd_empty_return);
1068                                 }
1069                         if (wasalarm) error(_("Maximum response timeout (%lds) exceeded"),alarmtime);
1070                         else error(_("^Couldn't read device data (ret=%d)"),got);
1071                         goto err;
1072                         }
1073                 bufl2=bufl+got;
1074                 buf[bufl2]='\0';
1075                 s=buf+bufl;
1076                 while (buf+bufl2>s && (s=memchr(s,'\0',buf+bufl2-s))) *s++=REPL_NULLCHAR;
1077                 if (verbose>=3)
1078                         error(_("\nGot chunk of data from device: %s"),reform(buf+bufl,0));
1079                 /* convert CR */ {
1080                         s=buf+bufl;
1081                         while (buf+bufl2>s && (s=memchr(s,'\r',buf+bufl2-s))) *s++='\n';
1082                         }
1083                 bufl=bufl2;
1084 skipread:
1085                 catched(buf+bufl,edata); assert(!record || record==buf+bufl);
1086                 assert(bufl<sizeof(buf)-1);
1087                 buf[bufl]='\0';
1088                 assert(strlen(buf)==bufl);
1089                 /* d3(">%s|%s<\n",buf,term); */
1090                 if (strstr(buf,ERROR_SUBSTR1) || strstr(buf,ERROR_SUBSTR2)) {
1091                         error(_("Found ERROR response on command %s"),reform(send,0));
1092                         goto err;
1093                         }
1094 /* "record" may get NULLed here after successful 'catch'
1095  * but "recordend" will never be NULLed
1096  */
1097                 if (catch && !recordend && bufl>=catchl && (hit=strstr(buf,catch))) {
1098                         record=hit+catchl;
1099                         catched(buf+bufl,edata); assert(!record || record==buf+bufl);
1100                         }
1101                 if (catch_any && !recordend && buf[discard=strspn(buf,"\n" /* accept */)]) {
1102                         record=buf+discard;
1103                         catched(buf+bufl,edata); assert(!record || record==buf+bufl);
1104                         }
1105                 if (((!catch && !catch_any) || catchdatal) && bufl>= terml
1106                     && (hit=strstr((recordend?recordend:buf),term))) {
1107                         memmove(buf,hit+terml,(bufl2=(buf+bufl)-(hit+terml))); bufl=bufl2;
1108                         break;
1109                         }
1110                 if (bufl<fragl) continue;
1111                 memmove(buf,buf+bufl-(fragl-1),(bufl2=fragl-1));
1112                 if (record   ) record-=bufl-bufl2;
1113                 if (recordend) recordend-=bufl-bufl2;
1114                 bufl=bufl2;
1115                 }
1116         alarm(0);
1117         if (!catchdatal) {
1118                 assert(!catch && !catch_any);
1119                 return("");
1120                 }
1121         assert(!!catch || catch_any);
1122         record=emptystring;
1123         catched(record+1,edata);
1124         if (verbose>=2) error(_(".Returning data %s for cmd %s"),reform(catchdata,0),reform(send,1));
1125         return(catchdata);
1126 }
1127
1128 static int prepaddr(unsigned char *d,const char *addr)
1129 {
1130 int tot=0;
1131 char flip=0,plus;
1132 unsigned char n;
1133
1134         if ((plus=(*addr=='+'))) addr++;
1135         *++d=(plus?ADDR_INT:ADDR_NAT);
1136         while (*addr) {
1137                 if (*addr<'0' || *addr>'9')
1138                         error(_("!Error during conversion of number at: %s"),addr);
1139                 tot++;
1140                 n=(*addr++)-'0';
1141                 if ((flip=!flip)) *++d=0xF0|n;
1142                 else *d=(*d&0x0F)|(n<<4U);
1143                 }
1144         return(tot);
1145 }
1146
1147 static char *finalsmsc;
1148 #define SMSCBINSIZE (1+1+(MAXNUMLEN+1)/2)
1149 static char pdusmsc[SMSCBINSIZE*2+1];
1150
1151 static inline char tohex(unsigned char x)
1152 {
1153         x&=0x0F;
1154         if (x<10) return(x   +'0');
1155                   return(x-10+'A');
1156 }
1157
1158 static inline void textconv(char *d,unsigned char *s,size_t len)
1159 {
1160         while (len--) {
1161                 *d++=tohex(*s>>4U);
1162                 *d++=tohex(*s    );
1163                 s++;
1164                 }
1165         *d='\0';
1166 }
1167
1168 static inline void smscset(void)
1169 {
1170 char *s,*t,*e,*serr;
1171 unsigned char bin[2+(MAXNUMLEN+1)/2];
1172
1173         if (smsc) devcmd(NULL,NULL,"\r\nAT+CSCA=\"%s\"",smsc);
1174         s=devcmd(NULL,"\n+CSCA:","\r\nAT+CSCA?");
1175         while (isspace(*s)) s++;
1176         if (!*s || !strcmp(s,"EMPTY"))
1177                 error(_("!No SMSC set in mobile station found, please use option \"-s\""));
1178         if (verbose>=1) error(_("\nFound default SMSC in mobile: %s"),s);
1179         if (*s++!='"') error(_("!No left-quote found in: %s"),s);
1180         if (!(t=strrchr(s,'"'))) error(_("!No right-quote found in: %s"),s);
1181         if (s==t)
1182                 error(_("!No SMS set in mobile station found, please use option \"-s\""));
1183         e=t++;
1184         while (isspace(*t)) t++;
1185         if (*t) {
1186 long l;
1187
1188                 if (*t++!=',') error(_("!No comma found after quotes in: %s"),s);
1189                 while (isspace(*t)) t++;
1190                 l=strtol(t,&serr,10);
1191                 if ((l!=ADDR_NAT && l!=ADDR_INT) || (serr && *serr))
1192                         error(_("!Type parse error in: %s"),s);
1193                 if (l==ADDR_INT && *s!='+') *--s='+';
1194                 }
1195         *e='\0';
1196         if (verbose>=2) error(_("\nDecoded SMSC address: %s"),s);
1197         if (!NEED_PDUSMSC()) return;
1198         chk(finalsmsc=strdup(s));
1199         bin[0]=1+(prepaddr(bin,finalsmsc)+1)/2;
1200         textconv(pdusmsc,bin,bin[0]+1);
1201 }
1202
1203 static inline unsigned char charconv_send(char c,size_t offs)
1204 {
1205         switch (c) {
1206                 case '@': return(0);
1207                 case '$': return(2);
1208                 case 0: assert(0);
1209                 default:
1210                         return(c&0x7F);
1211                 }
1212 #if 0
1213         if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')) return(c);
1214         error(_("Can't convert character '%c' (0x%02X) at offs %d (0-based), substituted '?'"),
1215                 c,(unsigned char)c,offs);
1216         return('?');
1217 #endif
1218 }
1219
1220 static inline unsigned char charconv_recv(char c,size_t offs)
1221 { /* FIXME: unify with charconv_send() */
1222         switch (c) {
1223                 case 0: return('@');
1224                 case 2: return('$');
1225                 default:
1226                         return(c);
1227                 }
1228 /* strict checking not done, see charconv_send */
1229 }
1230
1231 /* Logo format shamelessly stolen from GNokii-0.3.0: http://www.gnokii.org/
1232  * Beware - Nokia Smart Messaging specification 1.0.0 and 2.0.0 is incompatible
1233  * with Nokia current product line implementation
1234  * http://www.forum.nokia.com/developers/smartmsg/download/ssm2_0_0.pdf
1235  */
1236
1237 static char *pdudata;
1238 static struct hexdata {
1239         struct hexdata *next;
1240         char data[140*2+1];
1241         } *hexdata,**hexdatatail=&hexdata;
1242
1243 static void nokiaprep(unsigned char *bin,size_t w)
1244 {
1245 struct hexdata *hd;
1246         assert(w<=140);
1247         chk(hd=malloc(sizeof(*hd)));
1248         *hexdatatail=hd;
1249         hd->next=NULL;
1250         hexdatatail=&hd->next;
1251         textconv(hd->data,bin,w);
1252         if (verbose>=2) error(_("\nWill send hexdata: %s"),hd->data);
1253 }
1254
1255 static inline void logoread(void)
1256 {
1257 FILE *f;
1258 char buf[32+140*8+1];
1259 unsigned char bin[140]={
1260         0x06, /* UDH length */
1261         0x05, /* IEI */
1262         0x04, /* IEDL */
1263         0x15, 0x83, /* dest port (group gfx) */
1264         0x15, 0x83  /* src port (unused) */
1265         };
1266 size_t got,r=0 /* GCC happiness */,w;
1267 ssize_t chars,bits;
1268 char gsmnetf[10];
1269 int sizex,sizey,bit;
1270
1271 #define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8))
1272
1273         if (!(f=fopen(logoname,"rb")))
1274                 error(_("^!Cannot open logo file \"%s\" for r/o"),logoname);
1275         got=fread(buf,1,sizeof(buf),f);
1276         chkfclose(f,logoname);
1277              if (got>=20 && !memcmp(buf,"NOL",4)) {
1278                 VARPRINTF2(gsmnetf,"%03.3u%02.2u",WORD(6),WORD(8));
1279                 assert(strlen(gsmnetf)==5);
1280                 r=10;
1281                 if (verbose>=1) error(_(".Reading NOL file \"%s\", GSMnet \"%s\", word@4=%d.."),
1282                         logoname,gsmnetf,WORD(4));
1283                 }
1284         else if (got>=16 && !memcmp(buf,"NGG",4)) {
1285                 r=6;
1286                 if (verbose>=1) error(_(".Reading NGG file \"%s\", word@4=%d.."),
1287                         logoname,WORD(4));
1288                 }
1289         else error(_("!Unknown file format of logo file \"%s\""),logoname);
1290         if (gsmnet && !strtrycasecmp(gsmnet,WORD_NET)) {
1291                 if (!*gsmnetf) error(_("!NOL network code detection requested but NOL file not loaded, please specify network code"));
1292                 gsmnet=gsmnetf;
1293                 }
1294         if (!gsmnet || !strtrycasecmp(gsmnet,WORD_GROUP) || !*gsmnet) {
1295                 error(_("\nSending logo as: group graphics"));
1296                 gsmnet=NULL;
1297                 }
1298         else {
1299                 error(_("\nSending logo as: operator logo for \"%s\""),gsmnet);
1300                 bin[4]=0x82; /* dest port 0x1582 */
1301                 }
1302         
1303         sizex=WORD(r); sizey=WORD(r+2);
1304         if (verbose>=2) error(_(".Magic words: @+4=%d, @+6=%d, @+8=%d"),
1305                         WORD(r+4),WORD(r+6),WORD(r+8));
1306         r+=10;
1307         if (sizex<1 || sizex>255
1308          || sizey<1 || sizey>255) error(_("!Invalid size: %dx%d"),sizex,sizey);
1309         chars=((bits=sizex*sizey)+7)/8;
1310         if (r+bits>got) error(_("!Logo file \"%s\" too short - actual=%d, need(%dx%d)=%d"),
1311                 logoname,got,sizex,sizey,r+chars);
1312         else if (r+bits<got)
1313                 if (verbose>=1) error(_("Ignoring trailing garbage in \"%s\", used only %d bytes"),logoname,r+bits);
1314         if ((got=(7+(gsmnet?3:0)+4+chars))>140)
1315                 error(_("!SMS size would be %d bytes but 140 is maximum"),got);
1316         w=7;
1317         if (gsmnet) {
1318                 bin[w++]=((gsmnet[1]&0x0F)<<4)|(gsmnet[0]&0x0F);
1319                 bin[w++]=0xF0                 |(gsmnet[2]&0x0F);
1320                 bin[w++]=((gsmnet[4]&0x0F)<<4)|(gsmnet[3]&0x0F);
1321                 }
1322         bin[w++]=0x00; /* RFU by Nokia */
1323         bin[w++]=sizex; bin[w++]=sizey;
1324         bin[w++]=0x01; /* one B/W plane */
1325         while (chars--) {
1326                 bin[w]=0;
1327                 for (bit=0x80;(bits>0) && (bit>0);bits--,bit>>=1) {
1328                         if (buf[r]!='0' && buf[r]!='1')
1329                                 error(_("!Invalid character (neither '0' nor '1') in logo file \"%s\" at offset 0x%X"),
1330                                         logoname,r);
1331                         if (buf[r++]=='1') bin[w]|=bit;
1332                         }
1333                 w++;
1334                 }
1335         assert(chars==-1); assert(bits==0); assert(w==got);
1336         nokiaprep(bin,w);
1337 #undef WORD
1338 }
1339
1340 static inline void ringread(void)
1341 {
1342 FILE *f;
1343 unsigned char bin1[140]={
1344         6, /* UDH length */
1345         0x05, /* IEI */
1346         0x04, /* IEDL */
1347         0x15, 0x81, /* dest port (ring tones) */
1348         0x15, 0x81  /* src port (unused) */
1349 #define BIN1_PAYLOAD (140-7)
1350         };
1351 unsigned char binn[140]={
1352         11, /* UDH length */
1353         0x05, /* IEI */
1354         0x04, /* IEDL */
1355         0x15, 0x81, /* dest port (ring tones) */
1356         0x15, 0x81, /* src port (unused) */
1357         0x00, 0x03, /* multipart */
1358         /* 0x??, unique serial ID */
1359         /* 0x??, total messages */
1360         /* 0x??, message number (# from 1) */
1361 #define BINN_PAYLOAD (140-12)
1362         };
1363 size_t got,want;
1364 int totn,fragn;
1365 long size;
1366
1367 #define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8))
1368
1369         if (!(f=fopen(ringname,"rb")))
1370                 error(_("^!Cannot open ring file \"%s\" for r/o"),ringname);
1371         if ((size=getfilesize(f,ringname))==-1)
1372                 error(_("!File size determination is essential to continue operation"));
1373         if (size<0x103)
1374                 error(_("!File \"%s\" size %ld too small (must >=0x103)! Is it .000 file?"),
1375                         ringname,size);
1376         if (fseek(f,0x100,SEEK_SET))
1377                 error(_("^Seeking error on \"%s\", ignoring"),ringname);
1378         size-=0x100;
1379         if (size<=BIN1_PAYLOAD) {
1380                 if ((got=fread(bin1+7,1,size,f))!=size)
1381                         error(_("^Read error on \"%s\", wanted %ld, got %d"),ringname,size,got);
1382                 error(_("\nSending ring tone \"%s\" as single SMS (size %ld, max %d)"),
1383                         ringname,size,BIN1_PAYLOAD);
1384                 nokiaprep(bin1,7+size);
1385                 }
1386         else {
1387                 totn=(size+BINN_PAYLOAD-1)/BINN_PAYLOAD;
1388                 if (totn>0xFF)
1389                         error(_("!File size %ld too large even for multi-SMS ring upload (max=%d)"),
1390                                 size,BINN_PAYLOAD*0xFF);
1391                 binn[10]=totn;
1392                 if (verbose>=1)
1393                         error(_("\nSending ring tone \"%s\" as %d multi-SMSes (size %ld, max %d, frag %d)"),
1394                                 ringname,totn,size,BIN1_PAYLOAD,BINN_PAYLOAD);
1395                 binn[9]=time(NULL)&0x100; /* rand() would be better but it is a compatibility pain */
1396                 if (verbose>=1)
1397                         error(_("\nUsing unique multi-SMS ID 0x%02X"),(unsigned)binn[9]);
1398                 for (fragn=1;fragn<=totn;fragn++) {
1399                         binn[11]=fragn;
1400                         want=MIN(size,BINN_PAYLOAD);
1401                         if ((got=fread(binn+12,1,want,f))!=want)
1402                                 error(_("^Read error on \"%s\", wanted %d, got %d"),ringname,want,got);
1403                         nokiaprep(binn,12+want);
1404                         size-=want;
1405                         }
1406                 }
1407         chkfclose(f,ringname);
1408 #undef WORD
1409 }
1410
1411 #define PICTURE_WIDTH  (72)
1412 #define PICTURE_HEIGHT (28)
1413
1414 static inline void pictureread(void)
1415 {
1416 FILE *f;
1417 unsigned char bin1[140]={
1418         6, /* UDH length */
1419         0x05, /* IEI */
1420         0x04, /* IEDL */
1421         0x15, 0x8A, /* dest port (ring tones) */
1422         0x15, 0x8A  /* src port (unused) */
1423 #define BIN1_PAYLOAD (140-7)
1424         };
1425 unsigned char binn[140]={
1426         11, /* UDH length */
1427         0x05, /* IEI */
1428         0x04, /* IEDL */
1429         0x15, 0x8A, /* dest port (ring tones) */
1430         0x15, 0x8A, /* src port (unused) */
1431         0x00, 0x03, /* multipart */
1432         /* 0x??, unique serial ID */
1433         /* 0x??, total messages */
1434         /* 0x??, message number (# from 1) */
1435 #define BINN_PAYLOAD (140-12)
1436         };
1437 unsigned char header[]={
1438         0x30,   /* version string '0' */
1439         0x02,   /* item=OTA bitmap */
1440 #define PICTURE_BYTES ((PICTURE_WIDTH*PICTURE_HEIGHT+7)/8)
1441 #define PICTURE_BYTES_INCL_HEADER (PICTURE_BYTES +4/*header*/)
1442         PICTURE_BYTES_INCL_HEADER>>8,PICTURE_BYTES_INCL_HEADER&0xFF,    /* picture size in bytes incl. header */
1443         0x00, /* animation pictures - 0=static picture */
1444         PICTURE_WIDTH,PICTURE_HEIGHT,   /* picture size in pixels */
1445         0x01,   /* picture depth - B/W */
1446         };
1447 size_t got,want;
1448 int totn,fragn;
1449 long size;
1450
1451 #define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8))
1452
1453         if (!(f=fopen(picturename,"rb")))
1454                 error(_("^!Cannot open picture file \"%s\" for r/o"),picturename);
1455         if ((size=getfilesize(f,picturename))==-1)
1456                 error(_("!File size determination is essential to continue operation"));
1457         if (size!=PICTURE_BYTES)
1458                 error(_("!File \"%s\" size %ld doesn't match .res size for %dx%d picture"),
1459                         picturename,size,PICTURE_WIDTH,PICTURE_HEIGHT);
1460         if (size<=BIN1_PAYLOAD-sizeof(header)) {
1461                 memcpy(bin1+7,header,sizeof(header));
1462                 if ((got=fread(bin1+7+sizeof(header),1,size,f))!=size)
1463                         error(_("^Read error on \"%s\", wanted %ld, got %d"),picturename,size,got);
1464                 error(_("\nSending picture \"%s\" as single SMS (size %ld, max %d)"),
1465                         picturename,size,BIN1_PAYLOAD-sizeof(header));
1466                 nokiaprep(bin1,7+sizeof(header)+size);
1467                 }
1468         else {
1469                 memcpy(binn+12,header,sizeof(header));
1470                 totn=(sizeof(header)+size+BINN_PAYLOAD-1)/BINN_PAYLOAD;
1471                 if (totn>0xFF)
1472                         error(_("!File size %ld too large even for multi-SMS picture upload (max=%d)"),
1473                                 size,BINN_PAYLOAD*0xFF-sizeof(header));
1474                 binn[10]=totn;
1475                 if (verbose>=1)
1476                         error(_("\nSending picture \"%s\" as %d multi-SMSes (size %ld, max %d, frag %d, header %d)"),
1477                                 picturename,totn,size,BIN1_PAYLOAD,BINN_PAYLOAD,sizeof(header));
1478                 binn[9]=time(NULL)&0x100; /* rand() would be better but it is a compatibility pain */
1479                 if (verbose>=1)
1480                         error(_("\nUsing unique multi-SMS ID 0x%02X"),(unsigned)binn[9]);
1481                 for (fragn=1;fragn<=totn;fragn++) {
1482 size_t isheader=(fragn==1 ? sizeof(header) : 0);
1483
1484                         binn[11]=fragn;
1485                         want=MIN(size,BINN_PAYLOAD-isheader);
1486                         if ((got=fread(binn+12+isheader,1,want,f))!=want)
1487                                 error(_("^Read error on \"%s\", wanted %d, got %d"),picturename,want,got);
1488                         nokiaprep(binn,12+isheader+want);
1489                         size-=want;
1490                         }
1491                 }
1492         chkfclose(f,picturename);
1493 #undef WORD
1494 }
1495
1496 static inline void genpdu(void)
1497 {
1498 static unsigned char pdu[64+MAXNUMLEN/2+(MAXBODYLEN*7)/8];
1499 unsigned char *d=pdu;
1500 int i;
1501 char inb=0,outb=0,xb,*bodyr;
1502 unsigned char inreg=0 /* GCC happiness */;
1503 size_t offs=0;
1504
1505         *d++=PDU_TYPE;
1506         *d++=PDU_MR;
1507         i=prepaddr(d,phone);
1508         *d=i; d+=1+1+(i+1)/2;
1509         *d++=PDU_PID;
1510         *d++=PDU_DCS;
1511         *d++=PDU_VP;
1512         if (bodylen>MAXBODYLEN) {
1513                 error(_("Body too large (%d>%d), cut"),bodylen,MAXBODYLEN);
1514                 body[(bodylen=MAXBODYLEN)]='\0';
1515                 }
1516         bodyr=body;
1517         *d=bodylen;
1518         assert(d<pdu+sizeof(pdu));
1519         while (bodylen || inb) {
1520                 if (!inb) {
1521                         assert(bodylen>0); assert(!!*body);
1522                         inreg=charconv_send(*bodyr++,offs++);
1523                         bodylen--;
1524                         inb=7;
1525                         }
1526                 if (!outb) {
1527                         *++d=0x00;
1528                         outb=8;
1529                         }
1530                 xb=MIN(inb,outb);
1531 #if 0
1532                 d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb);
1533 #endif
1534                 *d|=((inreg>>(unsigned)(7-inb))&((1<<xb)-1))<<(unsigned)(8-outb);
1535                 inb-=xb; outb-=xb;
1536                 }
1537         d++;
1538         assert(d<pdu+sizeof(pdu));
1539         pdudata=malloc(2*(d-pdu)+1);
1540         textconv(pdudata,pdu,d-pdu);
1541 }
1542
1543 static inline void preparebody(void)
1544 {
1545 FILE *fin=NULL /* GCC happiness */;
1546 char *finame;
1547
1548         if (body && readbody) {
1549                 finame=body;
1550                 body=NULL;
1551                 }
1552         else {
1553                 finame=NULL;
1554                 fin=stdin;
1555                 }
1556         if (body) return;
1557         readbody=0;
1558         if (!finame) {
1559                 if (verbose>=1)
1560                         error(_("\nPlease enter the SMS text body, end with EOF (ctrl-D):"));
1561                 }
1562         else {
1563                 if (!(fin=fopen(finame,"rt")))
1564                         error(_("^!Can't open data file \"%s\" for r/o"),finame);
1565                 }
1566         chk(body=malloc(BODYLOAD));
1567         bodylen=fread(body,1,BODYLOAD,fin);
1568         if (bodylen==-1)
1569                 error(_("^!Error reading stream \"%s\""),(finame?finame:_("<stdin>")));
1570         if (finame) {
1571                 chkfclose(fin,finame);
1572                 free(finame);
1573                 }
1574 }
1575
1576 static int datawait(int timeout)
1577 {
1578 int i;
1579 #ifdef HAVE_POLL
1580 struct pollfd ufd;
1581 #else /* HAVE_POLL */
1582 fd_set rfds,xfds;
1583 #endif /* HAVE_POLL */
1584
1585         assert(devfd>=0);
1586 retry:
1587         if (timeout && verbose>=2)
1588                 error(_(".Waiting for device incoming data.."));
1589 #ifdef HAVE_POLL
1590         ufd.fd=devfd;
1591         ufd.events=POLLIN;
1592         ufd.revents=0;
1593         errno=0;
1594         i=poll(&ufd,1,timeout*1000);
1595 #else /* HAVE_POLL */
1596 #ifdef HAVE_FD_SETSIZE
1597         if (devfd>=FD_SETSIZE)
1598                 error(_("!Device file descriptor %d can't fit in select() FD_SETSIZE (%d)"),
1599                         devfd,FD_SETSIZE);
1600 #endif /* HAVE_FD_SETSIZE */
1601         FD_ZERO(&rfds); FD_SET(devfd,&rfds);
1602         FD_ZERO(&xfds); FD_SET(devfd,&xfds);
1603         errno=0;
1604         i=select(devfd+1,&rfds,NULL,&xfds,NULL);
1605 #endif /* HAVE_POLL */
1606         if (i==0) return(0);
1607         if (i==-1 && errno==EINTR)
1608                 goto retry; /* silent retry, for example SIGCHLD could occur */
1609         if (i!=1)
1610                 error(_("^Failed (retval %d) while waiting for data, ignoring"),i);
1611
1612 #ifdef HAVE_POLL
1613         if (ufd.revents&(POLLERR|POLLHUP))
1614 #else /* HAVE_POLL */
1615         if (FD_ISSET(devfd,&xfds))
1616 #endif /* HAVE_POLL */
1617                 error(_("^Error while waiting for data, ignoring"));
1618
1619 #ifdef HAVE_POLL
1620         if (!(ufd.revents&POLLIN))
1621 #else /* HAVE_POLL */
1622         if (!(FD_ISSET(devfd,&rfds)))
1623 #endif /* HAVE_POLL */
1624                 {
1625                 error(_("^No data input after waited for data, retrying"));
1626                 goto retry;
1627                 }
1628         return(1);
1629 }
1630
1631 static char *check_format(const char *fmt,const char *string)
1632 {
1633 static char err[LINE_MAX],sub[50];
1634 char cf,cs;
1635 const char *sf,*ss,*subp;
1636
1637         for (sf=fmt,ss=string;(cf=*sf) && (cs=*ss);sf++,ss++) {
1638                 subp=NULL;
1639                 switch (cf) {
1640                         case '?':
1641                                 break;
1642                         case '9':
1643                                 if (isdigit(cs)) break;
1644                                 subp=_("digit");
1645                                 break;
1646                         case '+':
1647                                 if (cs=='+' || cs=='-') break;
1648                                 subp=_("+/- sign");
1649                                 break;
1650                         default:
1651                                 if (cf==cs) break;
1652                                 VARPRINTF(sub,"'%c'",cf); subp=sub;
1653                         }
1654                 if (!subp) continue;
1655                 VARPRINTF5(err,_("Expected %s, found '%c' at pos %d of string [%s], formatstring [%s]"),
1656                         subp,cs,ss-string,string,fmt);
1657                 return(err);
1658                 }
1659         if (*sf) {
1660                 VARPRINTF2(err,_("String too short for format, string [%s], formatstring [%s]"),
1661                         string,fmt);
1662                 return(err);
1663                 }
1664         if (*ss) {
1665                 VARPRINTF2(err,_("Trailing garbage in string [%s], formatstring [%s]"),
1666                         string,fmt);
1667                 return(err);
1668                 }
1669         return(NULL);
1670 }
1671
1672 static char *receive_number,*receive_smsc;
1673 static time_t receive_time;
1674
1675 struct tm tm;
1676 static const struct {
1677         off_t strpos;
1678         off_t tmpos;
1679         int min,max;
1680         const char *name;
1681         } timeparse[]={
1682 #define TP_ENT(a,b,c,d,e) { a,offsetof(struct tm,b),c,d,e }
1683                 TP_ENT( 3,tm_year,0,99,N_("year")),
1684                 TP_ENT( 6,tm_mon ,1,12,N_("month")),
1685                 TP_ENT( 9,tm_mday,1,31,N_("day of month")),
1686                 TP_ENT(12,tm_hour,0,23,N_("hour")),
1687                 TP_ENT(15,tm_min ,0,59,N_("minute")),
1688                 TP_ENT(18,tm_sec ,0,59,N_("second")),
1689                 /* Time zone ignored */
1690                 };
1691 #define GETTIME(i) (*(int *)(((char *)&tm)+timeparse[(i)].tmpos))
1692
1693 static void maketime(const char *string)
1694 {
1695 int val;
1696 int i;
1697
1698         for (i=0;i<NELEM(timeparse);i++) {
1699                 val=GETTIME(i);
1700                 if (val<timeparse[i].min || val>timeparse[i].max) {
1701                         error(_("Weird value of %s, is %d but expected %d..%d, setting to %d"),
1702                                 _(timeparse[i].name),val,timeparse[i].min,timeparse[i].max,timeparse[i].min);
1703                         GETTIME(i)=timeparse[i].min;
1704                         }
1705                 }
1706         if (tm.tm_year<70) tm.tm_year+=100;
1707         tm.tm_mon--;
1708         d7("mktime(y%dm%dd%dh%dm%ds%d)\n",
1709                 tm.tm_year,tm.tm_mon,tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec);
1710         tm.tm_isdst=-1; /* "timezone" info not available */
1711         if ((receive_time=mktime(&tm))==-1)
1712                 error(_("^mktime(3) failed for %s"),string);
1713 }
1714
1715 /* +CMT: "+420602431329",,"99/10/25,03:21:03-00" */
1716 static int receive_headerparse(char *buf)
1717 {
1718 char *s,*s1,*err;
1719 int i;
1720
1721 #define DIGIT2ASC(s) (((s)[0]-'0')*10+((s)[1]-'0'))
1722
1723         for (s=buf;*s==' ';s++);
1724         if (*s++!='"') {
1725                 error(_("Cannot find initial '\"' in CMT header: %s"),buf);
1726                 return(0);
1727                 }
1728         for (s1=s;*s && *s!='"';s++);
1729         if (!*s) {
1730                 error(_("Only one '\"' found in CMT header: %s"),buf);
1731                 return(0);
1732                 }
1733         free(receive_smsc); receive_smsc=NULL;
1734         free(receive_number);
1735         chk(receive_number=malloc(s-s1+1));
1736         memcpy(receive_number,s1,s-s1); receive_number[s-s1]='\0';
1737         s++;
1738         if ((err=check_phone(receive_number)) ||
1739             (err=check_format(",,\"99/99/99,99:99:99+99\"",s))) {
1740                 error(_("%s in CMT header: %s"),err,buf);
1741                 return(0);
1742                 }
1743         memset(&tm,0,sizeof(tm)); /* may be redundant */
1744         for (i=0;i<NELEM(timeparse);i++)
1745                 GETTIME(i)=DIGIT2ASC(s+timeparse[i].strpos);
1746         maketime(s+2);
1747         return(1);
1748 #undef DIGIT2ASC
1749 }
1750
1751 static void signal_chld(int signo)
1752 {
1753 int status;
1754 pid_t pid;
1755
1756         signal(SIGCHLD,(RETSIGTYPE (*)(int))signal_chld);
1757         /* we don't care about siginterrupt(3) as it doesn't matter how it is set */
1758
1759         d2("signal_chld: signo=%d\n",signo);
1760         while (0<(pid=waitpid(-1 /* ANY process */,&status,WNOHANG /* options */))) {
1761                 if (verbose>=2)
1762                         error(_(".Child process w/PID %d has exited, %s, status=%d"),
1763                                         pid,(WIFEXITED(status)? _("normally") : _("abnormally")),(WIFEXITED(status) ? WEXITSTATUS(status) : -1));
1764                 }
1765 }
1766
1767 static void receive_text(char *bodyline)
1768 {
1769 char *buf,*s,*s1,*s2,*s3;
1770 pid_t pid;
1771 char tbuf[32];
1772 int i;
1773 FILE *f;
1774
1775         d2("receive_text: %s\n",bodyline);
1776         signal(SIGCHLD,(RETSIGTYPE (*)(int))signal_chld);
1777 #if RECEIVE_TEST
1778         pid=0;
1779 #else
1780         pid=fork();
1781 #endif
1782         if (pid>0) {
1783                 if (verbose>=2)
1784                         error(_(".Spawned child receive-SMS process w/PID %d"),pid);
1785                 return; /* parent context */
1786                 }
1787         if (pid==-1) {
1788                 error(_("Can't fork(2), process spawning may block receive"));
1789                 }
1790         else { /* child process */
1791                 dis_cleanup=1;
1792                 }
1793         for (s=body;*s;) {
1794                 s1=s;
1795                 do {
1796                         s1=strchr(s1+(s1!=s),'%');
1797                         } while (s1 && s1[1]!='p' && s1[1]!='T' && s1[1]!='t' && s1[1]!='s');
1798                 if (!s1) {
1799                         pushargstack_one(s,0);
1800                         break;
1801                         }
1802                 *s1='\0';
1803                 pushargstack_one(s,0);
1804                 *s1++='%';
1805                 s=s1;
1806                 switch (*s++) {
1807                         case 'p':
1808                                 pushargstack_one(receive_number,0);
1809                                 break;
1810                         case 'T':
1811                                 VARPRINTF(tbuf,"%ld",receive_time);
1812                                 pushargstack_one(tbuf,0);
1813                                 break;
1814                         case 't':
1815                                 if (receive_time==-1) break;
1816                                 if (!(s2=ctime(&receive_time))) {
1817                                         error(_("Failing ctime(3), ignoring substitution"));
1818                                         break;
1819                                         }
1820                                 if ((s3=strchr(s2,'\n'))) *s3='\0';
1821                                 pushargstack_one(s2,0);
1822                                 break;
1823                         case 's':
1824                                 if (receive_smsc) pushargstack_one(receive_smsc,0);
1825                                 break;
1826                         default: assert(0);
1827                         }
1828                 }
1829         buf=glueargstack(NULL,NULL); assert(buf);
1830         if (!(f=popen(buf,"w"))) {
1831                 error(_("^Failing spawn of receive command: %s"),buf);
1832                 goto err;
1833                 }
1834         if (fputs(bodyline,f)<0 || putc('\n',f)!='\n')
1835                 error(_("^Failing write to child receive command: %s"),buf);
1836         if ((i=pclose(f)))
1837                 error(_("^Spawned receive command failure (code %d): %s"),i,buf);
1838 err:
1839         free(buf);
1840         if (pid==-1) return;
1841         exit(EXIT_SUCCESS); /* cleanup() has been disabled */
1842 }
1843
1844 static inline unsigned char fromhex(unsigned c)
1845 {
1846         c&=0xDF;
1847         return(c<'A'?c-('0'&0xDF):(c-('A'&0xDF))+0xA);
1848 }
1849
1850 static int teldecode(char *text,unsigned char *bin,size_t digits)
1851 {
1852 unsigned char b;
1853 int r=0,i;
1854
1855         for (i=0;i<digits;text++,i++) {
1856                 if (!(i&1)) b=*bin;
1857                 else b=(*bin++)>>4;
1858                 b&=0x0F;
1859                 if (b<=0x09)
1860                         *text=b+'0';
1861                 else {
1862                         *text='?';
1863                         r++;
1864                         }
1865                 }
1866         *text='\0';
1867         return(r);
1868 }
1869
1870 static void sctsparse(unsigned char *bin,const char *pduline,int offs)
1871 {
1872 #define DIGIT2BIN(v) (((v)&0x0F)*10+(((v)>>4)&0x0F))
1873 int i;
1874
1875         receive_time=-1;
1876         memset(&tm,0,sizeof(tm)); /* may be redundant */
1877         for (i=0;i<NELEM(timeparse);offs++,i++) {
1878                 if ((*bin&0x0F)>0x09 || (*bin&0xF0)>0x90) {
1879                         error(_("Invalid value of \"%s\" at offset %d in: %s"),
1880                                 timeparse[i].name,offs,pduline);
1881                         return;
1882                         }
1883                 GETTIME(i)=DIGIT2BIN(*bin);
1884                 bin++;
1885                 }
1886         maketime(pduline);
1887
1888 #undef DIGIT2BIN
1889 }
1890
1891 static void receive_pdu(char *pduline)
1892 {
1893 unsigned char pdu[140+0x100],*pdup,*pdue,oalen,inreg;
1894 char text[160+1],*textp,*s,*pdulinescan;
1895 size_t pdulinel=strlen(pduline),want;
1896 size_t udl,udlb;
1897 int inb,outb,xb;
1898
1899         d2("receive_pdu: %s\n",pduline);
1900         if (pdulinel>2*sizeof(pdu))
1901                 { error(_("PDU too long (%d/2) to be valid: %s"),pdulinel,pduline); return; }
1902         if (pdulinel&1)
1903                 { error(_("PDU length odd (%d): %s"),pdulinel,pduline); return; }
1904         if (pdulinel<2*13)
1905                 { error(_("PDU length %d too small (min. 2*%d): %s"),pdulinel,13,pduline); return; }
1906         for (pdup=pdu,pdulinescan=pduline;*pdulinescan;pdulinescan+=2) {
1907                 if (!isxdigit(pdulinescan[0]) || !(isxdigit(pdulinescan[1])))
1908                 { error(_("Invalid hex byte: %c%c on byte %d in: %s"),
1909                         pdulinescan[0],pdulinescan[1],pdup-pdu,pduline); return; }
1910                 *pdup++=(fromhex(pdulinescan[0])<<4)|fromhex(pdulinescan[1]);
1911                 }
1912         pdue=pdup;
1913         free(receive_smsc);
1914         if (*pdu<=1) {
1915                 receive_smsc=NULL;
1916                 }
1917         else {
1918                 if (*pdu>10)
1919                         { error(_("SMSC length too large (%d, max. %d): %s"),*pdu,10,pduline); return; }
1920                 chk(receive_smsc=malloc(1+2*(*pdu)+1));
1921                 s=receive_smsc;
1922                 if (pdu[1]==ADDR_INT) *s++='+';
1923                 else {
1924                         if (pdu[1]!=ADDR_NAT)
1925                                 error(_("Unknown address type 0x%02X of %s, ignoring in PDU: %s"),pdu[1],_("SMSC"),pduline); return;
1926                         }
1927                 if (teldecode(s,pdu+2,2*(*pdu-1)-((pdu[1+(*pdu)]&0xF0)==0xF0)))
1928                         error(_("Some digits unrecognized in %s \"%s\", ignoring in PDU: %s"),_("SMSC"),receive_smsc,pduline);
1929                 }
1930         pdup=pdu+1+(*pdu);
1931         if (*pdup&0x03) /* PDU type */
1932                 error(_("Unrecognized PDU type 0x%02X at offset %d, dropping: %s"),*pdup,pdup-pdu,pduline);
1933         pdup++;
1934         free(receive_number);
1935         if ((oalen=*pdup++)>2*0x10) /* OA len */
1936                 { error(_("Originating number too large (0x%X, max. 2*0x%X): %s"),oalen,0x10,pduline); return; }
1937         if (pdup+(want=1+(oalen+1)/2+10)>pdue)
1938                 { error(_("PDU length too short (want %d, is %d): %s"),(pdup-pdu)+want,pdue-pdu,pduline); return; }
1939         chk(receive_number=malloc(1+2*(*pdup)+1));
1940         s=receive_number;
1941         if (*pdup==ADDR_INT) *s++='+';
1942         else {
1943                 if (*pdup!=ADDR_NAT)
1944                         error(_("Unknown address type 0x%02X of %s, ignoring in PDU: %s"),*pdup,_("originating number"),pduline); return;
1945                 }
1946         pdup++;
1947         if (teldecode(s,pdup,oalen))
1948                 error(_("Some digits unrecognized in %s \"%s\", ignoring in PDU at offset %d: %s"),
1949                         _("originating number"),receive_number,pdup-pdu,pduline);
1950         pdup+=(oalen+1)/2;
1951         if (*pdup) /* PID */
1952                 error(_("PID number %02X unsupported, ignoring: %s"),*pdup,pduline);
1953         pdup++;
1954         if (*pdup) { /* DCS */
1955                 if ((*pdup&0xF4)==0xF4)
1956                         { error(_("DCS 0x%02X indicates 8-bit data, unsupported, dropping: %s"),*pdup,pduline); return; }
1957                 error(_("DCS 0x%02X unsupported, will attempt decoding: %s"),*pdup,pduline);
1958                 }
1959         pdup++;
1960         sctsparse(pdup,pduline,pdup-pdu);
1961         pdup+=7;
1962         /* UDL */
1963         udl=*pdup++;
1964         if (pdue-pdup>140) {
1965                 error(_("PDU data (%d) exceed maximum length of %d bytes, cut: %s"),
1966                         pdue-pdup,140,pduline);
1967                 pdue=pdup+140;
1968                 }
1969         udlb=(udl*7+7)/8;
1970         if (pdup+udlb>pdue) {
1971 size_t udl1,udlb1;
1972
1973                 udlb1=pdue-pdup;
1974                 udl1=(udlb1*8)/7;
1975                 error(_("PDU data length (%d/7->%d/8) longer than data (%d), cut to %d/7->%d/8: %s"),
1976                         udl,udlb,pdue-pdup,udl1,udlb1,pduline);
1977                 udl=udl1; udlb=udlb1;
1978                 }
1979         else
1980                 assert(pdup+udlb==pdue); /* should be checked by 'PDU length too short' above */
1981         textp=text;
1982         inb=outb=0;
1983         inreg=0; /* GCC happiness */
1984         while (udl) {
1985                 if (!inb) {
1986                         inreg=*pdup++;
1987                         inb=8;
1988                         }
1989                 if (!outb) {
1990                         assert(textp<text+160);
1991                         *textp=0x00;
1992                         outb=7;
1993                         }
1994                 xb=MIN(inb,outb);
1995 #if 0
1996                 d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb);
1997 #endif
1998                 *textp|=((inreg>>(unsigned)(8-inb))&((1<<xb)-1))<<(unsigned)(7-outb);
1999                 inb-=xb; outb-=xb;
2000                 if (!outb) {
2001                         *textp=charconv_recv(*textp,textp-text);
2002                         textp++;
2003                         udl--;
2004                         }
2005                 }
2006         *textp=0;
2007         receive_text(text);
2008 }
2009
2010 static struct {
2011         char **sp;
2012         long *ip;
2013         const char *const msg;
2014         } numarg[]={
2015                 { &maxretry,&maxretryn,"maxretry" },
2016                 { &readtime,&readtimen,"readtime" },
2017                 { &chartime,&chartimen,"chartime" },
2018                 { &cmdtime ,&cmdtimen ,"cmdtime"  },
2019                 { &waittime,&waittimen,"waittime" },
2020                 { &baud    ,&baudn    ,"baud"     },
2021         };
2022
2023 int main(int argc,char **argv)
2024 {
2025 char *s;
2026 int i,cmgf=-1 /* GCC happiness */;
2027 unsigned fatal=0;
2028 speed_t portbaud=0 /* GCC happiness */;
2029 enum modenum argsmode;
2030 unsigned parts=0;
2031
2032         if ((s=strrchr((pname=*argv),'/'))) pname=s+1;
2033
2034 #ifdef ENABLE_NLS
2035         /* Initialize the i18n stuff */
2036         bindtextdomain(PACKAGE,LOCALEDIR);
2037         if (!setlocale(LC_ALL,""))
2038                 error("Locale not supported by C library");
2039         textdomain(PACKAGE);
2040 #endif
2041
2042 #ifdef HAVE_ATEXIT
2043         atexit(cleanup);
2044 #else
2045         error(_("atexit(3) not available at compilation time, device cleanup may be missed"));
2046 #endif
2047         signal(SIGTERM,(RETSIGTYPE (*)(int))cleanup);
2048         signal(SIGQUIT,(RETSIGTYPE (*)(int))cleanup);
2049         signal(SIGINT ,(RETSIGTYPE (*)(int))cleanup);
2050         signal(SIGHUP ,(RETSIGTYPE (*)(int))cleanup);
2051         assert(mode==MODE_UNKNOWN);
2052         for (i=0;i<NELEM(longopts);i++) {
2053                 if (longopts[i].val<MODE_FIRST) break;
2054                 if (!strstr(pname,longopts[i].name)) continue;
2055                 if (mode==MODE_UNKNOWN || mode==longopts[i].val) {
2056                         mode=longopts[i].val;
2057                         continue;
2058                         }
2059                 mode=MODE_UNKNOWN;
2060                 break;
2061                 }
2062         argsmode=mode;
2063         processargs(argc,argv,_("<command-line>"));
2064         if ((s=getenv("HOME"))) {
2065 size_t l=strlen(s);
2066 char *buf=malloc(l+50);
2067
2068                 memcpy(buf,s,l);
2069                 strcpy(buf+l,CONFIG_HOME);
2070                 readfile(buf,1);
2071                 free(buf);
2072                 }
2073         readfile(CONFIG_MAIN,1);
2074         if (verbose>=1) {
2075                 if (argsmode)
2076                         error(_(".Detected mode \"%s\" from my program name \"%s\""),MODE_NAME(argsmode),pname);
2077                 else
2078                         error(_(".Automatic mode detection unsuccessul for my progam name \"%s\""),pname);
2079                 }
2080
2081         if (!mode)
2082                 error(_("!Operation mode unset, use --send or similiar command, see help (-h)"));
2083         error(_(".Running program in mode \"%s\""),MODE_NAME(mode));
2084         switch (mode) {
2085
2086                 case MODE_SEND:           /* FALLTHRU */
2087                 case MODE_SEND_MOBILDOCK: cmdline_send        (); break;
2088                 case MODE_LOGO_SEND:      cmdline_logo_send   (); break;
2089                 case MODE_RING_SEND:      cmdline_ring_send   (); break;
2090                 case MODE_PICTURE_SEND:   cmdline_picture_send(); break;
2091                 case MODE_RECEIVE:        cmdline_receive     (); break;
2092                 default: assert(0);
2093                 }
2094         cmdline_done();
2095         for (i=0;i<NELEM(nullcheck);i++) {
2096 const struct nullcheck *n=nullcheck+i;
2097
2098                 if (*n->var) continue;
2099                 if (n->reqd && !(MODE_BIT(mode)&n->reqd)) continue;
2100                 error(_("Missing parameter \"%s\""),_(n->name));
2101                 fatal++;
2102                 }
2103         if (fatal) error(_("!Previous %s considered unrecoverable"),(fatal==1?_("error"):_("errors")));
2104         emptyclean();
2105         if (!logname) logname=DEF_LOGNAME;
2106         if (!lockfile) lockfile=DEF_LOCKFILE;
2107         if (!device) device=DEF_DEVICE;
2108
2109         for (i=0;i<NELEM(numarg);i++) {
2110 char *serr;
2111                 if (!*numarg[i].sp) continue;
2112                 *numarg[i].ip=strtol(*numarg[i].sp,&serr,0);
2113                 if (*numarg[i].ip<0 || *numarg[i].ip>=LONG_MAX || !serr || *serr)
2114                         error(_("!Number parse error for parameter \"%s\" of \"%s\" at: %s"),
2115                                 numarg[i].msg,*numarg[i].sp,serr);
2116                 }
2117         if (readtimen==-1)
2118                 readtimen=(mode==MODE_SEND_MOBILDOCK?DEF_READTIME_MOBILDOCK:DEF_READTIME);
2119         if (mode==MODE_SEND_MOBILDOCK) mode=MODE_SEND;
2120
2121         if (!strchr(device,'/')) {
2122 size_t l=strlen(device);
2123                 chk(s=malloc(5+l+1));
2124                 strcpy(s,"/dev/");
2125                 strcpy(s+5,device);
2126                 free(device);
2127                 device=s;
2128                 }
2129         devicename=strrchr(device,'/')+1; assert(!!(devicename-1));
2130         for (i=0,s=lockfile;*s;s++) {
2131                 if (*s!='%') continue;
2132                 s++;
2133                 if (*s=='%') continue;
2134                 if (*s=='s') {
2135                         if (i) error(_("!Only one \"%%s\" permitted in lockfile format-string"));
2136                         i=1; continue;
2137                         }
2138                 error(_("!Invalid format-character '%c' in lockfile format-string, only \"%%s\" allowed"),*s);
2139                 }
2140         
2141         if (*logname) {
2142                 if (!(logf=fopen(logname,"a")))
2143                         error(_("^!Error opening log \"%s\" for append"),logname);
2144                 logmsg(_("Starting up: %s"),PACKAGE " " VERSION);
2145                 }
2146
2147         switch (mode) {
2148                 case MODE_SEND:
2149                         preparebody();
2150                         genpdu();
2151                         readbody=0;
2152                         break;
2153                 case MODE_LOGO_SEND:
2154                         logoread();
2155                         break;
2156                 case MODE_RING_SEND:
2157                         ringread();
2158                         break;
2159                 case MODE_PICTURE_SEND:
2160                         pictureread();
2161                         break;
2162                 case MODE_RECEIVE: break;
2163                 default: assert(0);
2164                 }
2165         if (readbody)
2166                 error(_("Warning: -f / --file is forbidden with mode \"%s\""),MODE_NAME(mode));
2167         if (smsmode) {
2168                      if (!strcmp(smsmode,"pdu" ) || !strcmp(smsmode,"0"))
2169                         force_smsmode=FSM_PDU ;
2170                 else if (!strcmp(smsmode,"text") || !strcmp(smsmode,"1"))
2171                         force_smsmode=FSM_TEXT;
2172                 else
2173                         error(_("!Unrecognized %s argument \"%s\", supported only: %s"),"-M/--smsmode",smsmode,"pdu/0/text/1");
2174                 }
2175         if (pdusmscmode) {
2176                      if (!strcmp(pdusmscmode,"count-in"))
2177                         force_pdusmscmode=FPSM_COUNT_IN;
2178                 else if (!strcmp(pdusmscmode,"count-out"))
2179                         force_pdusmscmode=FPSM_COUNT_OUT;
2180                 else if (!strcmp(pdusmscmode,"none"))
2181                         force_pdusmscmode=FPSM_NONE;
2182                 else
2183                         error(_("!Unrecognized %s argument \"%s\", supported only: %s"),"-P/--pdusmscmode",pdusmscmode,"count-in/count-out/none");
2184                 try_pdusmscmode=force_pdusmscmode;
2185                 }
2186
2187         switch (baudn) {
2188                 case  2400: portbaud= B2400; break;
2189                 case  4800: portbaud= B4800; break;
2190                 case  9600: portbaud= B9600; break;
2191                 case 19200: portbaud=B19200; break;
2192                 case 38400: portbaud=B38400; break;
2193                 case 57600: portbaud=B57600; break;
2194                 default:
2195                         error(_("!Specified baudrate %ld is not supported"),baudn);
2196                 }
2197         if (verbose>=2) error(_(".Will use baudrate %ld with hexval 0x%X"),baudn,portbaud);
2198                 
2199         if (lockfile && *lockfile && VARPRINTF(lockreal,lockfile,devicename)>0) {
2200 time_t start,end;
2201                 if (verbose>=1) error(_(".Locking device \"%s\" by \"%s\".."),device,lockreal);
2202                 time(&start);
2203                 lockdevice(0);
2204                 time(&end);
2205                 if ((end-=start)>LOCKREPORT)
2206                         logmsg(_("Device lock succeeded after %ld seconds"),(long)end);
2207                 }
2208
2209 retryopen:
2210
2211         if (verbose>=1) error(_(".Opening device \"%s\".."),device);
2212         if ((devfd=open(device,O_RDWR|O_NDELAY))<0)
2213                 error(_("^!Cannot open device \"%s\" for r/w access"),device);
2214         
2215 retryall:
2216
2217                 if (tcgetattr(devfd,&restios))
2218                         error(_("^Unable to get termios settings"));
2219                 else {
2220                         restios.c_cflag=(restios.c_cflag&~(CBAUD|CBAUDEX))|B0|HUPCL;
2221                         restios_yes=1;
2222                         }
2223                 tios.c_iflag=IGNBRK|IGNPAR|(handshake_rtscts ? 0 : IXON|IXOFF);
2224                 tios.c_oflag=0;
2225                 tios.c_cflag=CS8|CREAD|CLOCAL|HUPCL|portbaud|(handshake_rtscts ? CRTSCTS : 0);
2226                 tios.c_lflag=IEXTEN|NOFLSH;
2227                 memset(tios.c_cc,_POSIX_VDISABLE,sizeof(tios.c_cc));
2228                 tios.c_cc[VTIME]=0;
2229                 tios.c_cc[VMIN ]=1;
2230                                 cfsetispeed(&tios,portbaud);
2231                 if (cfsetospeed(&tios,portbaud)|cfsetispeed(&tios,portbaud))
2232                         error(_("^Error setting termios baudrate on device"));
2233                 if (tcflush(devfd,TCIOFLUSH))
2234                         error(_("^Error flushing termios (TCIOFLUSH) on device"));
2235                 if (tcsetattr(devfd,TCSANOW,&tios))
2236                         error(_("^!Unable to set initial termios device settings"));
2237
2238                 setalarm();
2239
2240                 devcmd("",NULL,"\r\nAT\033\032"); /* ESCAPE, CTRL-Z */
2241                 devcmd(NULL,NULL,"\r\nAT");
2242                 smscset();
2243                 if (mode==MODE_SEND || mode==MODE_RECEIVE) {
2244                         cmgf=-1;
2245                         do {
2246                                 /* condition is _negative_ here: */
2247                                 if (force_smsmode==FSM_TEXT || !devcmd(NULL,NULL,"!\r\nAT+CMGF=0")) {
2248                                         if (force_smsmode==FSM_PDU || !devcmd(NULL,NULL,"!\r\nAT+CMGF=1"))
2249                                                 { retrying(); continue; }
2250                 /* CMGF=1 */
2251                                         if (verbose>=1)
2252                                                 error(_(".Using AT+CMGF=1 (text mode).."));
2253                                         cmgf=1;
2254                                         }
2255                                 else {
2256                 /* CMGF=0 */
2257                                         if (verbose>=1)
2258                                                 error(_(".Using AT+CMGF=0 (PDU mode).."));
2259                                         cmgf=0;
2260                                         }
2261                                 } while (cmgf==-1);
2262                         }
2263                 switch (mode) {
2264                         case MODE_SEND:
2265                                 if (cmgf) {
2266                                         devcmd("\n> ",NULL,"\r\nAT+CMGS=\"%s\"",phone);
2267                                         s=devcmd(NULL,"\n+CMGS:","!~%s\032",body);
2268                                         }
2269                                 else {
2270                                         devcmd("\n> ",NULL,"\r\nAT+CMGS=%d",(
2271                                                         (try_pdusmscmode==FPSM_COUNT_IN ? strlen(pdusmsc) : 0)
2272                                                         +strlen(pdudata))/2);
2273                                         s=devcmd(NULL,"\n+CMGS:","!~%s%s\032",
2274                                                         (try_pdusmscmode!=FPSM_NONE ? pdusmsc : ""),
2275                                                         pdudata);
2276                                         if (!s && force_pdusmscmode==FPSM_AUTO) {
2277                                                 if (FPSM_MAX==try_pdusmscmode++)
2278                                                         try_pdusmscmode=FPSM_MIN;
2279                                                 else
2280                                                         retrycnt--;
2281                                                 }
2282                                         }
2283                                 break;
2284                         case MODE_LOGO_SEND:
2285                         case MODE_RING_SEND:
2286                         case MODE_PICTURE_SEND: {
2287 struct hexdata *hd;
2288
2289                                 restore="\r\nAT+CSMP=17,,0,0";
2290                                 devcmd(NULL,NULL,"\r\nAT+CSMP=81,,0,245");
2291                                 while ((hd=hexdata)) {
2292                                         devcmd("\n> ",NULL,"\r\nAT+CMGS=\"%s\"",phone);
2293                                         if (!(s=devcmd(NULL,"\n+CMGS:","!~%s\032",hd->data))) break;
2294                                         if ((hexdata=hd->next)) pushargstack_one(s,0);
2295                                         free(hd);
2296                                         parts++;
2297                                         }
2298                                 } break;
2299                         case MODE_RECEIVE: {
2300 int gotdatawait;
2301
2302                                 restore="\r\nAT+CNMI=,0";
2303                                 devcmd(NULL,NULL,"\r\nAT+CNMI=,2");
2304                                 devcmd(NULL,NULL,"\r\nAT+CSDH=0");
2305 continue_receive:
2306                                 unlockdevice(0);
2307                                 /* Never bail-out when we got up to this point */
2308                                 if (maxretryn!=-1 && verbose>=1)
2309                                         error(_(".Initialization successful, infinite retry count set"));
2310                                 maxretryn=-1;
2311 #if RECEIVE_TEST
2312         receive_headerparse(" \"+420602123456\",,\"99/10/25,03:21:03-00\"");
2313         receive_accept("TESTBODY");
2314         exit(EXIT_SUCCESS);
2315 #endif
2316                                 gotdatawait=datawait(waittimen);
2317                                 if (!lockdevice(1)) {
2318                                         if (verbose>=1)
2319                                                 error(_(".Dialout detected, waiting for lock.."));
2320                                         if (verbose>=1) error(_(".Closing device \"%s\".."),device);
2321                                         if (close(devfd))
2322                                                 error(_("Error closing device \"%s\""),device);
2323                                         lockdevice(0);
2324                                         goto retryopen;
2325                                         }
2326                                 d1("Lock-device succeeded\n");
2327                                 do {
2328                                         if (!(s=devcmd("\n","+CMT:"," ")))
2329                                                 goto retryall;
2330                                         if (s==&devcmd_empty_return) { /* only newlines found */
2331                                                 if (gotdatawait==0) /* timeout, rather reinitialize the modem */
2332                                                         goto retryall;
2333                                                 goto continue_receive;
2334                                                 }
2335                                         d1("Reading a message for us...\n");
2336                                         if (cmgf && !(i=receive_headerparse(s)))
2337                                                 error(_("Receive-header parsing failed on: %s"),s);
2338                                         if (!(s=devcmd("\n","@"," ")))
2339                                                 goto retryall;
2340                                         if (cmgf) {
2341                                                 if (i) receive_text(s);
2342                                                 }
2343                                         else receive_pdu(s);
2344                                         } while (datawait(0));
2345                                 goto retryall;
2346                                 }
2347
2348                         default: assert(0);
2349                         }
2350                 if (!s) { retrying(); goto retryall; }
2351
2352         pushargstack_one(s,0); s=NULL;
2353         if (verbose>=1) while ((s=nextargstack())) {
2354                 while (isspace(*s)) s++;
2355                 error(_("\nMessage successfuly sent with MR (Message Reference): %s"),s);
2356                 }
2357         devcmd(NULL,NULL,"\r\nAT");
2358
2359         if (parts)
2360                 logmsg(_("SMS sent (after %d retries), %d part(s)"),retrycnt,parts);
2361         else
2362                 logmsg(_("SMS sent (after %d retries)"),retrycnt);
2363         return(EXIT_SUCCESS);
2364 }