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