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