-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGetMailFromIvanti.java
More file actions
610 lines (520 loc) · 20.5 KB
/
GetMailFromIvanti.java
File metadata and controls
610 lines (520 loc) · 20.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
package Jvakt;
/*
* 2025-05-08 V.02 Michael Ekdal Adjusted the log output.
* 2025-04-25 V.01 Michael Ekdal Reading mail from Ivanti about resolved incidents and update Jvakt DB.
*/
import jakarta.mail.*;
import jakarta.mail.search.*;
//import Jvakt.Message;
import java.util.*;
import Jvakt.Message;
import java.io.*;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class GetMailFromIvanti {
// static boolean newMsgId = false;
static String DBUrl = "jdbc:postgresql://localhost:5433/Jvakt";
static Connection conn = null;
static String database = "jVakt";
static String dbuser = "jVakt";
static String dbpassword = "";
static String dbhost = "localhost";
static String dbport = "5433";
static boolean msgFixat = false;
static boolean swHtml = false;
static boolean swHelp = false;
static boolean swOkSender = false;
static boolean swPrio = false;
static boolean swMailcheck = true;
static boolean swDormant = false;
static boolean swId = false;
static boolean swDelete = false;
static boolean swOKtot = false;
static String mimeType;
static String msgId;
static String t_id;
// static boolean swSunet = false;
static boolean swSerious = false;
static boolean swShow = false;
static boolean swRun = true;
static String from;
static String subject;
static String body;
static int antal;
static int detached;
static String agent = null;
static String jvhost = "localhost";
static String jvport = "1956";
static int jvporti ;
static String jvrc = "";
static String uname;
static String pwd;
static String imaphost;
static String imapport;
static String imapssl;
static String imaprw;
static String imapFolder;
static String senders;
static String sender;
static List<String> listSenders;
static String exSubjects;
static String exSubject;
static List<String> listExsubjects;
static String config = null;
static File configF;
static InetAddress inet;
public static void main(String[] args) {
String version = "GetMailFromIvanti ";
version += getVersion()+".02";
for (int i=0; i<args.length; i++) {
if (args[i].equalsIgnoreCase("-config")) config = args[++i];
if (args[i].equalsIgnoreCase("-help")) swHelp = true;
if (args[i].equalsIgnoreCase("-?")) swHelp = true;
if (args[i].equalsIgnoreCase("-norun")) swRun = false;
if (args[i].equalsIgnoreCase("-nomailcheck")) swMailcheck = false;
if (args[i].equalsIgnoreCase("-id")) swId = true;
if (args[i].equalsIgnoreCase("-delete")) swDelete = true;
if (args[i].equalsIgnoreCase("-show")) swShow = true;
}
if (swHelp) {
System.out.println("--- GetMailFromIvanti --- ");
System.out.println("by Michael Ekdal Perstorp Sweden.\n");
System.out.println("Analyses mail from Ivanti and updates the Jvakt dadtabase");
System.out.println("\n\nThe parameters and their meaning are:\n"+
"\n-config \tThe directory of the input files. Like: \"-dir c:\\Temp\" "+
"\n-norun \tTo turn of the status update in Jvakt." +
"\n-nomailcheck \tDo not read an analyze the mails. Only log-on the mail server to verify it is possible." +
"\n-id \tCreates an ID in the Jvakt server showing the status of the mail server. OK when able to log-on, ERR when not." +
"\n-delete \tWhen a mai is found, delete it! ( the default is to mark it as seen )"+
"\n-show \tA verbose log showing the response from the server."
);
System.exit(4);
}
if (config == null ) configF = new File("PlugIvantiSM.properties");
else configF = new File(config,"PlugIvantiSM.properties");
System.out.println("\n"+new Date()+" ----- Jvakt: Version: "+version);
System.out.println(new Date()+" -config file: "+configF);
Properties props = new Properties();
getProps(); // get Jvakt properties
if (swRun) {
SendMsg jm = new SendMsg(jvhost, jvporti); // Check if JvaktServer is available and if dormant.
jvrc = jm.open();
System.out.println(new Date()+" Jvakt server status: "+jvrc);
if (jvrc.toLowerCase().startsWith("dormant")) swDormant = true;
if (jvrc.toLowerCase().startsWith("failed")) {
swRun = false;
swDormant = true;
System.out.println(new Date()+" ----- Access to Jvakt failed! \"run\" set to false !!");
}
jm.close();
}
// System.exit(4);
if (swDormant) {
System.out.println(new Date()+" *** Jvakt in DORMANT mode, GetMailFromIvanti exiting *** ");
System.exit(4);
}
String provider = "imap"; // plain
int imapPort = 993; // secure
Address[] adr;
try {
imapPort = Integer.parseInt(imapport);
// Connect to the imap4 server
if (imapssl.startsWith("N")) {
props.put("mail.imap.ssl.enable", "false"); // plain
provider = "imap";
System.out.println(new Date()+" *** imap plain connection selected *** ");
}
else {
props.put("mail.imap.ssl.enable", "true"); // secure
provider = "imaps";
System.out.println(new Date()+" *** imaps secure connection selected *** ");
}
props.put("mail.imap.ssl.trust", "*");
props.put("mail.imaps.ssl.trust", "*");
System.out.println(new Date()+" Initiating connection to imap4 server....");
System.out.println(new Date()+" Connection... " + imaphost+":"+imapport+" User: "+uname);
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore(provider);
try {
store.connect(imaphost, imapPort, uname, pwd);
} catch (Exception e) {
System.out.println(new Date()+" Connection to " + imaphost+":"+imapport+" User "+uname+" Pass "+pwd+" failed!");
System.out.println(e);
if (swId) sendJv("GetMail2Jvakt_"+imaphost+"_"+uname , "ERR" , "T", "Connection to imap4 server "+imaphost+" user "+uname+" failed!" );
System.exit(8);
}
System.out.println(new Date()+" Connection to imap4 server established.");
if (swId) sendJv("GetMailFromIvanti_"+imaphost+"_"+uname , "OK" , "T", "Connection to imap4 server "+imaphost+" user "+uname+" established." );
if (swRun) {
// Open the folder
System.out.println(new Date()+" Open folder: " + imapFolder+ " (store folder separator "+store.getDefaultFolder().getSeparator()+" )");
Folder inbox = store.getFolder(imapFolder);
if (inbox == null) {
System.out.println(new Date()+" Mailbox folder "+imapFolder+" not found!");
System.exit(1);
}
if (imaprw.startsWith("Y") && swRun && swMailcheck) {
System.out.println(new Date()+" Opens "+imapFolder+" READ_WRITE");
inbox.open(Folder.READ_WRITE); // remove the marked messages from the server
}
else {
System.out.println(new Date()+" Opens "+imapFolder+" READ_ONLY");
inbox.open(Folder.READ_ONLY);
}
// Get the messages from the server
// Fetch all messages from inbox folder
// javax.mail.Message[] messages = inbox.getMessages();
// Fetch unseen messages from inbox folder
jakarta.mail.Message[] messages = null;
messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
// System.out.println("\n------------ NewMessageCount " + inbox.getNewMessageCount() + " ------------");
// System.out.println("------------ UnreadMessageCount " + inbox.getUnreadMessageCount() + " ------------");
System.out.println(new Date()+" *** Number of mails-> " +messages.length);
if (swMailcheck) {
for (int i = 0; i < messages.length; i++) {
adr = messages[i].getFrom();
from = null;
if (adr != null) {
// System.out.println("adr null ");
for (int j = 0; j < adr.length; j++) {
from = adr[j].toString();
}
} else {
from = "unknown";
}
System.out.println("\n"+new Date()+" >>> Mail from From: " + from );
// if (from == null) subject = "null."; 2013-05-23
if (from == null) from = "null.";
subject = messages[i].getSubject();
if (subject == null) subject = "null.";
mimeType = messages[i].getContentType();
System.out.println(new Date()+" MimeType> " + mimeType);
System.out.println(new Date()+" Subject: " + subject);
// if (from.contains("postmaster@internal.perscorp.com")) continue;
body = null;
swHtml = false;
Object o = null;
// if (messages[i].isMimeType("text/plain") || messages[i].isMimeType("text/html") || messages[i].isMimeType("multipart/alternative") || messages[i].isMimeType("multipart/mixed") ) {
// if (messages[i].isMimeType("text/plain") || messages[i].isMimeType("text/html") ) {
if (mimeType.toLowerCase().indexOf("text/plain")>=0 || mimeType.toLowerCase().indexOf("text/html")>=0) {
try {
o = messages[i].getContent();
body = (String)o;
} catch (IOException e) {
body = "";
}
if (messages[i].isMimeType("text/html")) swHtml = true;
}
if (messages[i].getContentType().startsWith("multipart")) {
System.out.println(new Date()+" *** multipart ");
Multipart mp = (Multipart)messages[i].getContent();
System.out.println(new Date()+" ***Count> " + mp.getCount());
for (int j=0, n=mp.getCount(); j<n; j++) {
Part part = mp.getBodyPart(j);
System.out.println(new Date()+" *** Attachment Descript : "+part.getDescription());
System.out.println(new Date()+" *** Attachment ContentType : "+part.getContentType());
if (part.getContentType().contains("text/plain")) {
body = part.getContent().toString();
// System.out.println(new Date()+" *** Attachment Content : "+body);
}
}
}
if (body == null) body = "null.";
//********************************
//************** analyse start *****
System.out.println(new Date()+" From-> " + from);
System.out.println(new Date()+" Subject-> " + subject);
System.out.println(new Date()+" Body-> " + body);
msgFixat = false;
swOkSender = false;
swPrio = false;
for(Object object : listSenders) {
sender = (String)object;
sender = sender.trim().toLowerCase();
if (from.toLowerCase().indexOf(sender) >= 0) swOkSender = true;
if (sender.compareTo("*")==0) swOkSender = true;
}
if (swOkSender) {
System.out.println(new Date()+" - Sender "+from+" is accepted");
if (messages[i].getContentType().toLowerCase().startsWith("multipart")) {
// System.out.println("*** multipart ");
Multipart mp = (Multipart)messages[i].getContent();
// System.out.println("*** Count> " + mp.getCount());
for (int j=0, n=mp.getCount(); j<n; j++) {
Part part = mp.getBodyPart(j);
// System.out.println("*** Attachment Descript : "+part.getDescription());
// System.out.println("*** Attachment ContentType : "+part.getContentType());
if (part.getContentType().toLowerCase().contains("text/plain")) {
body = part.getContent().toString();
// System.out.println("*** Attachment Content : \n"+body);
}
}
}
for(Object object : listExsubjects) {
exSubject = (String)object;
exSubject = exSubject.trim().toLowerCase();
if (subject.toLowerCase().indexOf(exSubject) >= 0) {
swOkSender = false;
System.out.println(" - but subject '"+exSubject+"' is exempted!");
}
if (body.toLowerCase().indexOf(exSubject) >= 0) {
swOkSender = false;
System.out.println(" - but body '"+exSubject+"' is exempted!");
}
}
if (swOkSender) {
// System.out.println(new Date()+" - swOkSender");
if (subject.toLowerCase().indexOf("is resolved") >= 0) {
System.out.println(new Date()+" - is resolved");
String id[];
id = null;
int bodyindex = body.toLowerCase().indexOf("jvakt-id:");
if (bodyindex >= 0) {
bodyindex=bodyindex+9;
// System.out.println(new Date()+" Jvakt-id::"+bodyindex);
// System.out.println("body::"+body.substring(bodyindex,bodyindex+100));
id = body.substring(bodyindex,bodyindex+100).split(";");
id[0] = id[0].trim();
System.out.println("id::"+id[0]);
if (!id[0].isEmpty() && imaprw.startsWith("Y") && swRun) {
msgFixat=updDBSTS(id[0]);
}
}
if (id == null) {
bodyindex = body.toLowerCase().indexOf("description:");
id = null;
if (bodyindex >= 0) {
bodyindex=bodyindex+12;
// System.out.println(new Date()+" Description::"+bodyindex);
// System.out.println("body::"+body.substring(bodyindex,bodyindex+100));
id = body.substring(bodyindex,bodyindex+100).split(" - ");
id[0] = id[0].trim();
System.out.println("id::"+id[0]);
if (!id[0].isEmpty() && imaprw.startsWith("Y") && swRun ) {
msgFixat=updDBSTS(id[0]);
}
}
}
}
}
}
else System.out.println(new Date()+" - Sender "+from+" is NOT accepted");
if (msgFixat && imaprw.startsWith("Y") && swRun) {
if (swDelete) {
System.out.println(new Date()+" * Mark as DELETED ");
messages[i].setFlag(Flags.Flag.DELETED, true);
}
else {
System.out.println(new Date()+" * Mark as SEEN ");
messages[i].setFlag(Flags.Flag.SEEN, true);
}
}
if (!msgFixat && swRun && imaprw.startsWith("Y")) {
System.out.println("* Mail ignored ");
messages[i].setFlag(Flags.Flag.SEEN, false);
}
//************ Analyze stop ******
//*******************************
}
}
// Close the connection
if (imaprw.startsWith("Y") && swRun && swMailcheck ) {
System.out.println(new Date()+" Close Mailbox folder "+imapFolder+" with option true");
inbox.close(true); // remove the marked messages from the server
}
else {
System.out.println(new Date()+" Close Mailbox folder "+imapFolder+" with option false");
inbox.close(false);
}
}
store.close();
swOKtot = true;
}
catch (Exception ex) {
ex.printStackTrace();
swOKtot = false;
}
if ( swRun ) {
if (swOKtot ) try {sendSTS(true);} catch (IOException e) { e.printStackTrace();}
else try {sendSTS(false);} catch (IOException e) { e.printStackTrace();}
}
}
// End of program
static protected void sendJv( String ID, String STS, String type, String msg) throws IOException {
Message jmsg = new Message();
SendMsg jm = new SendMsg(jvhost, jvporti);
System.out.println(jm.open());
jmsg.setId(ID);
jmsg.setRptsts(STS);
jmsg.setBody(msg);
jmsg.setType(type);
jmsg.setAgent(agent);
if (swSerious) {
jmsg.setPrio(20);
swSerious = false;
} else jmsg.setPrio(30);
if (jm.sendMsg(jmsg)) {
System.out.println("-- Rpt Delivered -- " + ID +" - "+ STS +" - "+ type +" - "+ agent);
msgFixat = true;
}
else {
System.out.println("-- Rpt Failed --");
msgFixat = false;
}
jm.close();
}
static void getProps() {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(configF);
prop.load(input);
// get the property value and print it out
jvport = prop.getProperty("jvport");
jvhost = prop.getProperty("jvhost");
jvporti = Integer.parseInt(jvport);
database = prop.getProperty("database");
dbuser = prop.getProperty("dbuser");
dbpassword = prop.getProperty("dbpassword");
if (dbpassword.startsWith("==y")) {
byte[] decodedBytes = Base64.getDecoder().decode(dbpassword.substring(3));
String decodedString = new String(decodedBytes);
dbpassword=decodedString;
}
dbhost = prop.getProperty("dbhost");
dbport = prop.getProperty("dbport");
uname = prop.getProperty("smtpuser");
pwd = prop.getProperty("smtppwd");
if (pwd.startsWith("==y")) {
byte[] decodedBytes = Base64.getDecoder().decode(pwd.substring(3));
String decodedString = new String(decodedBytes);
pwd=decodedString;
}
imaphost = prop.getProperty("imaphost");
imapport = prop.getProperty("imapport");
imapssl = prop.getProperty("imapSSL");
imaprw = prop.getProperty("imapRW");
imapFolder = prop.getProperty("imapFolder");
senders = prop.getProperty("senders");
String[] senderAddr = senders.split("\\,");
listSenders = new ArrayList<String>(); // Alla mailadresser.
System.out.println(new Date()+" -- Accepted senders --");
for(int i=0 ; i<senderAddr.length;i++) {
System.out.println(senderAddr[i]);
listSenders.add(senderAddr[i]);
}
exSubjects = prop.getProperty("exsubjects");
String[] exSubjectsStrings = exSubjects.split("\\,"); // All no-wanted subjects
listExsubjects = new ArrayList<String>();
System.out.println(new Date()+" -- exempted subjects --");
for(int i=0 ; i<exSubjectsStrings.length;i++) {
System.out.println(exSubjectsStrings[i]);
listExsubjects.add(exSubjectsStrings[i]);
}
// int imapporti = Integer.parseInt(imapport);
System.out.println(new Date()+" getProps jvport:" + jvport + " jvhost:"+jvhost) ;
} catch (IOException ex) {
ex.printStackTrace();
}
try {
inet = InetAddress.getLocalHost();
System.out.println(new Date()+" -- Inet: "+inet);
agent = inet.toString();
}
catch (Exception e) { System.out.println(e); }
}
static private String getVersion() {
String version = "0";
try {
Class<?> c1 = Class.forName("Jvakt.Version",false,ClassLoader.getSystemClassLoader());
Version ver = new Version();
version = ver.getVersion();
}
catch (java.lang.ClassNotFoundException ex) {
version = "?";
}
return version;
}
// sends status to the Jvakt server
static protected void sendSTS( boolean STS) throws IOException {
System.out.println("--- Connecting to "+jvhost+":"+jvport);
Message jmsg = new Message();
SendMsg jm = new SendMsg(jvhost, jvporti);
// System.out.println(jm.open());
jm.open();
jmsg.setId("Jvakt-GetMailFromIvanti");
if (STS) {
jmsg.setBody("The GetMailFromIvanti program is working. "+configF.getCanonicalPath());
jmsg.setRptsts("OK");
}
else {
jmsg.setBody("The GetMailFromIvanti program is not working! "+configF.getCanonicalPath());
jmsg.setRptsts("ERR");
}
jmsg.setType("T");
inet = InetAddress.getLocalHost();
// System.out.println("-- Inet: "+inet);
agent = inet.toString();
jmsg.setAgent(agent);
if (!jm.sendMsg(jmsg)) System.out.println("--- Rpt to Jvakt Failed for GetMailFromIvanti ---");
jm.close();
System.out.println("--- Status about GetMailFromIvanti sent to "+jvhost+":"+jvport);
}
static protected boolean updDBSTS( String id) throws IOException {
try {
String SQL_UPDATE;
PreparedStatement StmtUpdate;
Class.forName("org.postgresql.Driver").newInstance();
DBUrl = "jdbc:postgresql://"+dbhost+":"+dbport+"/"+database;
System.out.println(new Date()+ "DBUrl > "+DBUrl);
conn = DriverManager.getConnection(DBUrl,dbuser,dbpassword);
System.out.println(new Date()+ "conn > "+conn);
conn.setAutoCommit(false);
SQL_UPDATE ="UPDATE CONSOLE SET RECID=? WHERE ID ilike '"+id+"'" ;
System.out.println(new Date()+ " > "+SQL_UPDATE);
// logg.write(new Date()+" "+recid+ " > "+SQL_UPDATE);
// logg.newLine();
StmtUpdate = conn.prepareStatement(SQL_UPDATE);
StmtUpdate.setString(1, null);
System.out.println(new Date()+" Updated records > "+StmtUpdate.executeUpdate());
// logg.write(new Date()+" Updated records > "+StmtUpdate.executeUpdate());
// logg.newLine();
SQL_UPDATE ="UPDATE STATUS SET RECID=? WHERE ID ilike '"+id+"'";
System.out.println(new Date()+ " > "+SQL_UPDATE);
// logg.write(new Date()+" "+recid+ " > "+SQL_UPDATE);
// logg.newLine();
StmtUpdate = conn.prepareStatement(SQL_UPDATE);
StmtUpdate.setString(1, null);
System.out.println(new Date()+" Updated records > "+StmtUpdate.executeUpdate());
// logg.write(new Date()+" Updated records > "+StmtUpdate.executeUpdate());
// logg.newLine();
StmtUpdate.close();
conn.commit();
conn.close();
}
catch (SQLException e) {
System.out.println(new Date()+" SQLExeption ");
// logg.write(new Date()+" > "+e);
// logg.newLine();
// logg.write(new Date()+" > "+e.getMessage());
// logg.newLine();
System.err.println(e);
System.err.println(e.getMessage());
return false;
}
catch (Exception e) {
System.out.println(new Date()+" Exeption");
// logg.write(new Date()+" > "+e);
// logg.newLine();
// logg.write(new Date()+" > "+e.getMessage());
// logg.newLine();
System.err.println(e);
System.err.println(e.getMessage());
return false;
}
return true;
}
}