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