summaryrefslogtreecommitdiff
path: root/usr/discovery.c
blob: e78177c505dfd77faae877967d7902ce6cf3f747 (plain)
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
/*
 * iSCSI Discovery
 *
 * Copyright (C) 2002 Cisco Systems, Inc.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * See the file COPYING included with this distribution for more details.
 */

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <errno.h>
#include <netdb.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/poll.h>
#include <sys/time.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "strings.h"
#include "types.h"
#include "iscsi_proto.h"
#include "initiator.h"
#include "log.h"
#include "idbm.h"
#include "iscsi_settings.h"
#include "sysdeps.h"
#include "fw_context.h"
#include "iscsid_req.h"
#include "iscsi_util.h"
/* libisns includes */
#include "isns.h"
#include "paths.h"
#include "message.h"

#ifdef SLP_ENABLE
#include "iscsi-slp-discovery.h"
#endif

#define DISCOVERY_NEED_RECONNECT 0xdead0001

static int rediscover = 0;

static char initiator_name[TARGET_NAME_MAXLEN + 1];
static char initiator_alias[TARGET_NAME_MAXLEN + 1];

static int request_initiator_name(void)
{
	int rc;
	iscsiadm_req_t req;
	iscsiadm_rsp_t rsp;

	memset(initiator_name, 0, sizeof(initiator_name));
	initiator_name[0] = '\0';
	memset(initiator_alias, 0, sizeof(initiator_alias));
	initiator_alias[0] = '\0';

	memset(&req, 0, sizeof(req));
	req.command = MGMT_IPC_CONFIG_INAME;

	rc = iscsid_exec_req(&req, &rsp, 1);
	if (rc)
		return EIO;

	if (rsp.u.config.var[0] != '\0')
		strcpy(initiator_name, rsp.u.config.var);

	memset(&req, 0, sizeof(req));
	req.command = MGMT_IPC_CONFIG_IALIAS;

	rc = iscsid_exec_req(&req, &rsp, 0);
	if (rc)
		/* alias is optional so return ok */
		return 0;

	if (rsp.u.config.var[0] != '\0')
		strcpy(initiator_alias, rsp.u.config.var);
	return 0;
}

int discovery_isns(struct discovery_rec *drec, struct iface_rec *iface,
		   struct list_head *rec_list)
{
	isns_object_list_t objects = ISNS_OBJECT_LIST_INIT;
	isns_simple_t *qry;
	isns_client_t *clnt;
	isns_attr_list_t *attrs;
	char *server;
	uint32_t status;
	int rc, i;

	isns_config.ic_security = 0;

	if (iface && strlen(iface->iname))
		isns_assign_string(&isns_config.ic_source_name, iface->iname);
	else {
		if (request_initiator_name() || initiator_name[0] == '\0') {
			log_error("Cannot perform discovery. Initiatorname "
				  "required.");
			return EINVAL;
		}
		isns_assign_string(&isns_config.ic_source_name, initiator_name);
	}

	if (drec->port > USHRT_MAX) {
		log_error("Invalid port %d\n", drec->port);
		rc = EINVAL;
		goto free_mem;
	}

	/* 5 for port and 1 for colon and 1 for null */
	i = strlen(drec->address) + 7;
	server = calloc(1, i);
	if (!server) {
		rc = ENOMEM;
		goto free_mem;
	}

	snprintf(server, i, "%s:%d", drec->address, drec->port);
	isns_assign_string(&isns_config.ic_server_name, server);
	free(server);

	clnt = isns_create_default_client(NULL);
	if (!clnt) {
		rc = ENOMEM;
		goto free_mem;
	}

	/* do not retry forever */
	isns_socket_set_disconnect_fatal(clnt->ic_socket);

	qry = isns_simple_create(ISNS_DEVICE_ATTRIBUTE_QUERY,
				 clnt->ic_source, NULL);
	if (!qry) {
		rc = ENOMEM;
		goto free_clnt;
	}

	attrs = &qry->is_message_attrs;
	isns_attr_list_append_uint32(attrs, ISNS_TAG_ISCSI_NODE_TYPE,
				     ISNS_ISCSI_TARGET_MASK);

	attrs = &qry->is_operating_attrs;
	isns_attr_list_append_nil(attrs, ISNS_TAG_ISCSI_NAME);
	isns_attr_list_append_nil(attrs, ISNS_TAG_ISCSI_NODE_TYPE);
	isns_attr_list_append_nil(attrs, ISNS_TAG_PORTAL_IP_ADDRESS);
	isns_attr_list_append_nil(attrs, ISNS_TAG_PORTAL_TCP_UDP_PORT);
	isns_attr_list_append_nil(attrs, ISNS_TAG_PG_ISCSI_NAME);
	isns_attr_list_append_nil(attrs, ISNS_TAG_PG_PORTAL_IP_ADDR);
	isns_attr_list_append_nil(attrs, ISNS_TAG_PG_PORTAL_TCP_UDP_PORT);
	isns_attr_list_append_nil(attrs, ISNS_TAG_PG_TAG);

	status = isns_client_call(clnt, &qry);
	if (status != ISNS_SUCCESS) {
		log_error("iSNS discovery failed: %s", isns_strerror(status));
		rc = EIO;
		goto free_query;
	}

	status = isns_query_response_get_objects(qry, &objects);
	if (status) {
		log_error("Unable to extract object list from query "
			  "response: %s\n", isns_strerror(status));
		rc = EIO;
		goto free_query;
	}

	for (i = 0; i < objects.iol_count; ++i) {
		isns_object_t *obj = objects.iol_data[i];
		const char *pg_tgt = NULL;
		struct in6_addr in_addr;
		uint32_t pg_port = ISCSI_LISTEN_PORT;
		uint32_t pg_tag = PORTAL_GROUP_TAG_UNKNOWN;
		char pg_addr[INET6_ADDRSTRLEN + 1];
		struct node_rec *rec;

		if (!isns_object_is_pg(obj))
			continue;

		if (!isns_object_get_string(obj, ISNS_TAG_PG_ISCSI_NAME,
					    &pg_tgt)) {
			log_debug(1, "Missing target name");
			continue;
		}

		if (!isns_object_get_ipaddr(obj, ISNS_TAG_PG_PORTAL_IP_ADDR,
					    &in_addr)) {
			log_debug(1, "Missing addr");
			continue;
		}
		if (IN6_IS_ADDR_V4MAPPED(&in_addr) ||
		    IN6_IS_ADDR_V4COMPAT(&in_addr)) {
			struct in_addr ipv4;

			ipv4.s_addr = in_addr.s6_addr32[3];
			inet_ntop(AF_INET, &ipv4, pg_addr, sizeof(pg_addr));
		} else
			inet_ntop(AF_INET6, &in_addr, pg_addr, sizeof(pg_addr));

		if (!isns_object_get_uint32(obj,
					    ISNS_TAG_PG_PORTAL_TCP_UDP_PORT,
					    &pg_port)) {
			log_debug(1, "Missing port");
			continue;
		}

		if (!isns_object_get_uint32(obj, ISNS_TAG_PG_TAG, &pg_tag)) {
			log_debug(1, "Missing tag");
			continue;
		}

		rec = calloc(1, sizeof(*rec));
		if (!rec) {
			rc = ENOMEM;
			goto destroy_list;
		}

		idbm_node_setup_from_conf(rec);
		rec->disc_type = drec->type;
		rec->disc_port = drec->port;
		strcpy(rec->disc_address, drec->address);

		strlcpy(rec->name, pg_tgt, TARGET_NAME_MAXLEN);
		rec->tpgt = pg_tag;
		rec->conn[0].port = pg_port;
		strlcpy(rec->conn[0].address, pg_addr, NI_MAXHOST);

		list_add_tail(&rec->list, rec_list);
	}
	rc = 0;

	isns_flush_events();
destroy_list:
	isns_object_list_destroy(&objects);
free_query:
	isns_simple_free(qry);
free_clnt:
	isns_client_destroy(clnt);
free_mem:
	if (isns_config.ic_source_name)
		free(isns_config.ic_source_name);
	isns_config.ic_source_name = NULL;

	if (isns_config.ic_server_name)
		free(isns_config.ic_server_name);
	isns_config.ic_server_name = NULL;
	return rc;
}



int discovery_fw(struct discovery_rec *drec, struct iface_rec *iface,
		 struct list_head *rec_list)
{
	struct boot_context *bcontext;
	struct list_head targets;
	struct node_rec *rec;
	int rc;

	INIT_LIST_HEAD(&targets);
	rc = fw_get_targets(&targets);
	if (rc) {
		log_error("Could not get list of targets from firmware. "
			  "(err %d)\n", rc);
		return rc;
	}
	if (list_empty(&targets))
		return 0;
	/*
	 * TODO: Do we want to match the iface MAC/netdev with what is in
	 * the firmware or could the user want to bind based on what is
	 * in passed in or in the default ifaces?
	 */

	list_for_each_entry(bcontext, &targets, list) {
		rec = idbm_create_rec_from_boot_context(bcontext);
		if (!rec) {
			log_error("Could not convert firmware info to "
				  "node record.\n");
			rc = ENOMEM;
			goto free_targets;
		}
		rec->disc_type = drec->type;

		list_add_tail(&rec->list, rec_list);
	}

free_targets:
	fw_free_targets(&targets);
	return rc;
}

int discovery_offload_sendtargets(int host_no, int do_login,
				  discovery_rec_t *drec)
{
	struct sockaddr_storage ss;
	char default_port[NI_MAXSERV];
	iscsiadm_req_t req;
	iscsiadm_rsp_t rsp;
	int rc;

	log_debug(4, "offload st though host %d to %s", host_no,
		  drec->address);

	memset(&req, 0, sizeof(req));
	req.command = MGMT_IPC_SEND_TARGETS;
	req.u.st.host_no = host_no;
	req.u.st.do_login = do_login;

	/* resolve the DiscoveryAddress to an IP address */
	sprintf(default_port, "%d", drec->port);
	if (resolve_address(drec->address, default_port, &ss)) {
		log_error("Cannot resolve host name %s.", drec->address);
		return EIO;
	}       
	req.u.st.ss = ss;

	/*
	 * We only know how ask qla4xxx to do discovery and login
	 * to what it finds. We are not able to get what it finds or
	 * is able to log into so we just send the command and proceed.
	 *
	 * There is a way to just use the hw to send a sendtargets command
	 * and get back the results. We should do this since it would
	 * allows us to then process the results like software iscsi.
	 */
	rc = iscsid_exec_req(&req, &rsp, 1);
	if (rc) {
		log_error("Could not offload sendtargets to %s.\n",
			  drec->address);
		iscsid_handle_error(rc);
		return EIO;
	}

	return 0;
}

static int
iscsi_make_text_pdu(iscsi_session_t *session, struct iscsi_hdr *hdr,
		    char *data, int max_data_length)
{
	struct iscsi_text *text_pdu = (struct iscsi_text *)hdr;

	/* initialize the PDU header */
	memset(text_pdu, 0, sizeof (*text_pdu));

	text_pdu->opcode = ISCSI_OP_TEXT;
	text_pdu->itt = htonl(session->itt);
	text_pdu->ttt = ISCSI_RESERVED_TAG;
	text_pdu->cmdsn = htonl(session->cmdsn++);
	text_pdu->exp_statsn = htonl(session->conn[0].exp_statsn);

	return 1;
}

static int
request_targets(iscsi_session_t *session)
{
	char data[64];
	struct iscsi_text text;
	struct iscsi_hdr *hdr = (struct iscsi_hdr *) &text;

	memset(&text, 0, sizeof (text));
	memset(data, 0, sizeof (data));

	/* make a text PDU with SendTargets=All */
	if (!iscsi_make_text_pdu(session, hdr, data, sizeof (data))) {
		log_error("failed to make a SendTargets PDU");
		return 0;
	}

	if (!iscsi_add_text(hdr, data, sizeof (data), "SendTargets", "All")) {
		log_error("failed to add SendTargets text key");
		exit(1);
	}

	text.ttt = ISCSI_RESERVED_TAG;
	text.flags = ISCSI_FLAG_CMD_FINAL;

	if (++session->itt == ISCSI_RESERVED_TAG)
		session->itt = 1;

	if (!iscsi_io_send_pdu(&session->conn[0], hdr, ISCSI_DIGEST_NONE, data,
		    ISCSI_DIGEST_NONE, session->conn[0].active_timeout)) {
		log_error("failed to send SendTargets PDU");
		return 0;
	}

	return 1;
}

static int
iterate_targets(iscsi_session_t *session, uint32_t ttt)
{
	char data[64];
	struct iscsi_text text;
	struct iscsi_hdr *pdu = (struct iscsi_hdr *) &text;

	memset(&text, 0, sizeof (text));
	memset(data, 0, sizeof (data));

	/* make an empty text PDU */
	if (!iscsi_make_text_pdu(session, pdu, data, sizeof (data))) {
		log_error("failed to make an empty text PDU");
		return 0;
	}

	text.ttt = ttt;
	text.flags = ISCSI_FLAG_CMD_FINAL;

	if (++session->itt == ISCSI_RESERVED_TAG)
		session->itt = 1;

	if (!iscsi_io_send_pdu(&session->conn[0], pdu, ISCSI_DIGEST_NONE, data,
		    ISCSI_DIGEST_NONE, session->conn[0].active_timeout)) {
		log_error("failed to send empty text PDU");
		return 0;
	}

	return 1;
}

static int add_portal(struct list_head *rec_list, discovery_rec_t *drec,
		      char *targetname, char *address, char *port, char *tag)
{
	struct sockaddr_storage ss;
	char host[NI_MAXHOST];
	struct node_rec *rec;

	/* resolve the address, in case it was a DNS name */
	if (resolve_address(address, port, &ss)) {
		log_error("cannot resolve %s", address);
		return 0;
	}

	/* convert the resolved name to text */
	getnameinfo((struct sockaddr *) &ss, sizeof(ss),
		    host, sizeof(host), NULL, 0, NI_NUMERICHOST);

	rec = calloc(1, sizeof(*rec));
	if (!rec)
		return 0;

	idbm_node_setup_from_conf(rec);
	rec->disc_type = drec->type;
	rec->disc_port = drec->port;
	strcpy(rec->disc_address, drec->address);

	strlcpy(rec->name, targetname, TARGET_NAME_MAXLEN);
	if (tag && *tag)
		rec->tpgt = atoi(tag);
	else
		rec->tpgt = PORTAL_GROUP_TAG_UNKNOWN;
	if (port && *port)
		rec->conn[0].port = atoi(port);
	else
		rec->conn[0].port = ISCSI_LISTEN_PORT;
	strlcpy(rec->conn[0].address, address, NI_MAXHOST);

	list_add_tail(&rec->list, rec_list);
	return 1;
}

static int
add_target_record(char *name, char *end, discovery_rec_t *drec,
		  struct list_head *rec_list, char *default_port)
{
	char *text = NULL;
	char *nul = name;
	size_t length;

	/* address = IPv4
	 * address = [IPv6]
	 * address = DNSname
	 * address = IPv4:port
	 * address = [IPv6]:port
	 * address = DNSname:port
	 * address = IPv4,tag
	 * address = [IPv6],tag
	 * address = DNSname,tag
	 * address = IPv4:port,tag
	 * address = [IPv6]:port,tag
	 * address = DNSname:port,tag
	 */

	log_debug(7, "adding target record %p, end %p", name, end);

	/* find the end of the name */
	while ((nul < end) && (*nul != '\0'))
		nul++;

	length = nul - name;
	if (length > TARGET_NAME_MAXLEN) {
		log_error("TargetName %s too long, ignoring", name);
		return 0;
	}
	text = name + length;

	/* skip NULs after the name */
	while ((text < end) && (*text == '\0'))
		text++;

	/* if no address is provided, use the default */
	if (text >= end) {
		if (drec->address == NULL) {
			log_error("no default address known for target %s",
				  name);
			return 0;
		} else if (!add_portal(rec_list, drec, name, drec->address,
				       default_port, NULL)) {
			log_error("failed to add default portal, ignoring "
				  "target %s", name);
			return 0;
		}
		/* finished adding the default */
		return 1;
	}

	/* process TargetAddresses */
	while (text < end) {
		char *next = text + strlen(text) + 1;

		log_debug(7, "text %p, next %p, end %p, %s", text, next, end,
			 text);

		if (strncmp(text, "TargetAddress=", 14) == 0) {
			char *port = NULL;
			char *tag = NULL;
			char *address = text + 14;
			char *temp;

			if ((tag = strrchr(text, ','))) {
				*tag = '\0';
				tag++;
			}
			if ((port = strrchr(text, ':'))) {
				*port = '\0';
				port++;
			}

			if (*address == '[') {
				address++;
				if ((temp = strrchr(text, ']')))
					*temp = '\0';
			}

			if (!add_portal(rec_list, drec, name, address, port,
					tag)) {
				log_error("failed to add default portal, "
					 "ignoring target %s", name);
				return 0;
			}
		} else
			log_error("unexpected SendTargets data: %s",
			       text);
		text = next;
	}

	return 1;
}

static int
process_sendtargets_response(struct str_buffer *sendtargets,
			     int final, discovery_rec_t *drec,
			     struct list_head *rec_list,
			     char *default_port)
{
	char *start = str_buffer_data(sendtargets);
	char *text = start;
	char *end = text + str_data_length(sendtargets);
	char *nul = end - 1;
	char *record = NULL;
	int num_targets = 0;

	if (start == end) {
		/* no SendTargets data */
		goto done;
	}

	/* scan backwards to find the last NUL in the data, to ensure we
	 * don't walk off the end.  Since key=value pairs can span PDU
	 * boundaries, we're not guaranteed that the end of the data has a
	 * NUL.
	 */
	while ((nul > start) && *nul)
		nul--;

	if (nul == start) {
		/* couldn't find anything we can process now,
		 * it's one big partial string
		 */
		goto done;
	}

	/* find the boundaries between target records (TargetName or final PDU)
	 */
	for (;;) {
		/* skip NULs */
		while ((text < nul) && (*text == '\0'))
			text++;

		if (text == nul)
			break;

		log_debug(7,
			 "processing sendtargets record %p, text %p, line %s",
			 record, text, text);

		/* look for the start of a new target record */
		if (strncmp(text, "TargetName=", 11) == 0) {
			if (record) {
				/* send the last record, which we just found
				 * the end of. don't bother passing the
				 * "TargetName=" prefix.
				 */
				if (!add_target_record(record + 11, text,
							drec, rec_list,
							default_port)) {
					log_error(
					       "failed to add target record");
					str_truncate_buffer(sendtargets, 0);
					goto done;
				}
				num_targets++;
			}
			record = text;
		}

		/* everything up til the next NUL must be part of the
		 * current target record
		 */
		while ((text < nul) && (*text != '\0'))
			text++;
	}

	if (record) {
		if (final) {
			/* if this is the last PDU of the text sequence,
			 * it also ends a target record
			 */
			log_debug(7,
				 "processing final sendtargets record %p, "
				 "line %s",
				 record, record);
			if (add_target_record (record + 11, text,
					       drec, rec_list, default_port)) {
				num_targets++;
				record = NULL;
				str_truncate_buffer(sendtargets, 0);
			} else {
				log_error("failed to add target record");
				str_truncate_buffer(sendtargets, 0);
				goto done;
			}
		} else {
			/* remove the parts of the sendtargets buffer we've
			 * processed, and move the parts we haven't to the
			 * beginning of the buffer.
			 */
			log_debug(7,
				 "processed %d bytes of sendtargets data, "
				 "%d remaining",
				 (int)(record - str_buffer_data(sendtargets)),
				 (int)(str_buffer_data(sendtargets) +
				 str_data_length(sendtargets) - record));
			str_remove_initial(sendtargets,
					   record - str_buffer_data(sendtargets));
		}
	}

      done:

	return 1;
}

static void
clear_timer(struct timeval *timer)
{
	memset(timer, 0, sizeof (*timer));
}

/* set timer to now + seconds */
static void
set_timer(struct timeval *timer, int seconds)
{
	if (timer) {
		memset(timer, 0, sizeof (*timer));
		gettimeofday(timer, NULL);

		timer->tv_sec += seconds;
	}
}

static int
timer_expired(struct timeval *timer)
{
	struct timeval now;

	/* no timer, can't have expired */
	if ((timer == NULL) || ((timer->tv_sec == 0) && (timer->tv_usec == 0)))
		return 0;

	memset(&now, 0, sizeof (now));
	gettimeofday(&now, NULL);

	if (now.tv_sec > timer->tv_sec)
		return 1;
	if ((now.tv_sec == timer->tv_sec) && (now.tv_usec >= timer->tv_usec))
		return 1;
	return 0;
}

static int
msecs_until(struct timeval *timer)
{
	struct timeval now;
	int msecs;
	long partial;

	/* no timer, can't have expired, infinite time til it expires */
	if ((timer == NULL) || ((timer->tv_sec == 0) && (timer->tv_usec == 0)))
		return -1;

	memset(&now, 0, sizeof (now));
	gettimeofday(&now, NULL);

	/* already expired? */
	if (now.tv_sec > timer->tv_sec)
		return 0;
	if ((now.tv_sec == timer->tv_sec) && (now.tv_usec >= timer->tv_usec))
		return 0;

	/* not expired yet, do the math */
	partial = timer->tv_usec - now.tv_usec;
	if (partial < 0) {
		partial += 1000 * 1000;
		msecs = (partial + 500) / 1000;
		msecs += (timer->tv_sec - now.tv_sec - 1) * 1000;
	} else {
		msecs = (partial + 500) / 1000;
		msecs += (timer->tv_sec - now.tv_sec) * 1000;
	}

	return msecs;
}

static iscsi_session_t *
init_new_session(struct iscsi_sendtargets_config *config,
		 struct iface_rec *iface)
{
	iscsi_session_t *session;

	session = calloc(1, sizeof (*session));
	if (session == NULL)
		goto done;

	/* initialize the session's leading connection */
	session->conn[0].socket_fd = -1;
	session->conn[0].login_timeout = config->conn_timeo.login_timeout;
	session->conn[0].auth_timeout = config->conn_timeo.auth_timeout;
	session->conn[0].active_timeout = config->conn_timeo.active_timeout;
	session->conn[0].hdrdgst_en = ISCSI_DIGEST_NONE;
	session->conn[0].datadgst_en = ISCSI_DIGEST_NONE;

	session->conn[0].max_recv_dlength =
					config->iscsi.MaxRecvDataSegmentLength;
	if (session->conn[0].max_recv_dlength < ISCSI_MIN_MAX_RECV_SEG_LEN ||
	    session->conn[0].max_recv_dlength > ISCSI_MAX_MAX_RECV_SEG_LEN) {
		log_error("Invalid iscsi.MaxRecvDataSegmentLength. Must be "
			  "within %u and %u. Setting to %u.",
			  ISCSI_MIN_MAX_RECV_SEG_LEN,
			  ISCSI_MAX_MAX_RECV_SEG_LEN,
			  DEF_INI_DISC_MAX_RECV_SEG_LEN);
		session->conn[0].max_recv_dlength =
						DEF_INI_DISC_MAX_RECV_SEG_LEN;
	}
	session->conn[0].max_xmit_dlength = ISCSI_DEF_MAX_RECV_SEG_LEN;

	session->reopen_cnt = config->reopen_max + 1;

	/* OUI and uniqifying number */
	session->isid[0] = DRIVER_ISID_0;
	session->isid[1] = DRIVER_ISID_1;
	session->isid[2] = DRIVER_ISID_2;
	session->isid[3] = 0;
	session->isid[4] = 0;
	session->isid[5] = 0;

	request_initiator_name();

	if (iface && strlen(iface->iname)) {
		strcpy(initiator_name, iface->iname);
		/* MNC TODO add iface alias */
	} else {
		if (initiator_name[0] == '\0') {
			log_error("Cannot perform discovery. Initiatorname "
				  "required.");
			free(session);
			return NULL;
		}
	}

	session->initiator_name = initiator_name;
	session->initiator_alias = initiator_alias;
	session->portal_group_tag = PORTAL_GROUP_TAG_UNKNOWN;
	session->type = ISCSI_SESSION_TYPE_DISCOVERY;
done:
	return session;
}


static int
setup_authentication(iscsi_session_t *session,
		     discovery_rec_t *drec,
		     struct iscsi_sendtargets_config *config)
{
	int rc;

	rc = 1;

	/* if we have any incoming credentials, we insist on authenticating
	 * the target or not logging in at all
	 */
	if (config->auth.username_in[0]
	    || config->auth.password_in_length) {
		session->bidirectional_auth = 1;

		/* sanity check the config */
		if (config->auth.password_length == 0) {
			log_error(
			       "discovery process to %s:%d has incoming "
			       "authentication credentials but has no outgoing "
			       "credentials configured",
			       drec->address, drec->port);
			log_error(
			       "discovery process to %s:%d exiting, bad "
			       "configuration",
			       drec->address, drec->port);
			rc = 0;
			goto done;
		}
	} else {
		/* no or 1-way authentication */
		session->bidirectional_auth = 0;
	}

	/* copy in whatever credentials we have */
	strlcpy(session->username, config->auth.username,
		sizeof (session->username));
	session->username[sizeof (session->username) - 1] = '\0';
	if ((session->password_length = config->auth.password_length))
		memcpy(session->password, config->auth.password,
		       session->password_length);

	strlcpy(session->username_in, config->auth.username_in,
		sizeof (session->username_in));
	session->username_in[sizeof (session->username_in) - 1] = '\0';
	if ((session->password_in_length =
	     config->auth.password_in_length))
		memcpy(session->password_in, config->auth.password_in,
		       session->password_in_length);

	if (session->password_length || session->password_in_length) {
		/* setup the auth buffers */
		session->auth_buffers[0].address = &session->auth_client_block;
		session->auth_buffers[0].length =
		    sizeof (session->auth_client_block);
		session->auth_buffers[1].address =
		    &session->auth_recv_string_block;
		session->auth_buffers[1].length =
		    sizeof (session->auth_recv_string_block);

		session->auth_buffers[2].address =
		    &session->auth_send_string_block;
		session->auth_buffers[2].length =
		    sizeof (session->auth_send_string_block);

		session->auth_buffers[3].address =
		    &session->auth_recv_binary_block;
		session->auth_buffers[3].length =
		    sizeof (session->auth_recv_binary_block);

		session->auth_buffers[4].address =
		    &session->auth_send_binary_block;
		session->auth_buffers[4].length =
		    sizeof (session->auth_send_binary_block);

		session->num_auth_buffers = 5;
	} else {
		session->num_auth_buffers = 0;
	}
 done:
	return(rc);
}

static int
process_recvd_pdu(struct iscsi_hdr *pdu,
		  discovery_rec_t *drec,
		  struct list_head *rec_list,
		  iscsi_session_t *session,
		  struct str_buffer *sendtargets,
		  char *default_port,
		  int *active,
		  int *valid_text,
		  char *data)
{
	int rc=0;

	switch (pdu->opcode) {
		case ISCSI_OP_TEXT_RSP:{
			struct iscsi_text_rsp *text_response =
				(struct iscsi_text_rsp *) pdu;
			int dlength = ntoh24(pdu->dlength);
			int final =
				(text_response->flags & ISCSI_FLAG_CMD_FINAL) ||
				(text_response-> ttt == ISCSI_RESERVED_TAG);
			size_t curr_data_length;

			log_debug(4, "discovery session to %s:%d received text"
				 " response, %d data bytes, ttt 0x%x, "
				 "final 0x%x",
				 drec->address,
				 drec->port,
				 dlength,
				 ntohl(text_response->ttt),
				 text_response->flags & ISCSI_FLAG_CMD_FINAL);

			/* mark how much more data in the sendtargets
			 * buffer is now valid
			 */
			curr_data_length = str_data_length(sendtargets);
			if (str_enlarge_data(sendtargets, dlength)) {
				log_error("Could not allocate memory to "
					  "process SendTargets response.");
				rc = 0;
				goto done;
			}

			memcpy(str_buffer_data(sendtargets) + curr_data_length,
			       data, dlength);

			*valid_text = 1;
			/* process as much as we can right now */
			process_sendtargets_response(sendtargets,
						     final,
						     drec,
						     rec_list,
						     default_port);

			if (final) {
				/* SendTargets exchange is now complete
				 */
				*active = 0;
				/* from now on, after any reconnect,
				 * assume LUNs may have changed
				 */
			} else {
				/* ask for more targets */
				if (!iterate_targets(session,
						     text_response->ttt)) {
					rc = DISCOVERY_NEED_RECONNECT;
					goto done;
				}
			}
			break;
		}
		default:
			log_warning(
			       "discovery session to %s:%d received "
			       "unexpected opcode 0x%x",
			       drec->address, drec->port, pdu->opcode);
			rc = DISCOVERY_NEED_RECONNECT;
			goto done;
	}
 done:
	return(rc);
}

/*
 * Make a best effort to logout the session, then disconnect the
 * socket.
 */
static void
iscsi_logout_and_disconnect(iscsi_session_t * session)
{
	struct iscsi_logout logout_req;
	struct iscsi_logout_rsp logout_resp;
	int rc;

	/*
	 * Build logout request header
	 */
	memset(&logout_req, 0, sizeof (logout_req));
	logout_req.opcode = ISCSI_OP_LOGOUT | ISCSI_OP_IMMEDIATE;
	logout_req.flags = ISCSI_FLAG_CMD_FINAL |
		(ISCSI_LOGOUT_REASON_CLOSE_SESSION &
				ISCSI_FLAG_LOGOUT_REASON_MASK);
	logout_req.itt = htonl(session->itt);
	if (++session->itt == ISCSI_RESERVED_TAG)
		session->itt = 1;
	logout_req.cmdsn = htonl(session->cmdsn);
	logout_req.exp_statsn = htonl(++session->conn[0].exp_statsn);

	/*
	 * Send the logout request
	 */
	rc = iscsi_io_send_pdu(&session->conn[0],(struct iscsi_hdr *)&logout_req,
			    ISCSI_DIGEST_NONE, NULL, ISCSI_DIGEST_NONE, 3);
	if (!rc) {
		log_error(
		       "iscsid: iscsi_logout - failed to send logout PDU.");
		goto done;
	}

	/*
	 * Read the logout response
	 */
	memset(&logout_resp, 0, sizeof(logout_resp));
	rc = iscsi_io_recv_pdu(&session->conn[0],
		(struct iscsi_hdr *)&logout_resp, ISCSI_DIGEST_NONE, NULL,
		0, ISCSI_DIGEST_NONE, 1);
	if (!rc) {
		log_error("iscsid: logout - failed to receive logout resp");
		goto done;
	}
	if (logout_resp.response != ISCSI_LOGOUT_SUCCESS) {
		log_error("iscsid: logout failed - response = 0x%x",
		       logout_resp.response);
	}

done:
	/*
	 * Close the socket.
	 */
	iscsi_io_disconnect(&session->conn[0]);
}

int discovery_sendtargets(discovery_rec_t *drec, struct iface_rec *iface,
			  struct list_head *rec_list)
{
	iscsi_session_t *session;
	struct pollfd pfd;
	struct iscsi_hdr pdu_buffer;
	struct iscsi_hdr *pdu = &pdu_buffer;
	char *data = NULL;
	int active = 0, valid_text = 0;
	struct timeval connection_timer;
	int timeout;
	int rc;
	struct str_buffer sendtargets;
	uint8_t status_class = 0, status_detail = 0;
	unsigned int login_failures = 0, data_len;
	int login_delay = 0;
	struct sockaddr_storage ss;
	char host[NI_MAXHOST], serv[NI_MAXSERV], default_port[NI_MAXSERV];
	struct iscsi_sendtargets_config *config = &drec->u.sendtargets;

	/* initial setup */
	log_debug(1, "starting sendtargets discovery, address %s:%d, ",
		 drec->address, drec->port);
	memset(&pdu_buffer, 0, sizeof (pdu_buffer));
	clear_timer(&connection_timer);

	/* allocate a new session, and initialize default values */
	session = init_new_session(config, iface);
	if (session == NULL) {
		log_error("Discovery process to %s:%d failed to "
			  "create a discovery session.",
			  drec->address, drec->port);
		return 1;
	}

	log_debug(4, "sendtargets discovery to %s:%d using "
		 "isid 0x%02x%02x%02x%02x%02x%02x",
		 drec->address, drec->port, session->isid[0],
		 session->isid[1], session->isid[2], session->isid[3],
		 session->isid[4], session->isid[5]);

	/* allocate data buffers for SendTargets data */
	data = malloc(session->conn[0].max_recv_dlength);
	if (!data) {
		rc = 1;
		goto free_session;
	}
	data_len = session->conn[0].max_recv_dlength;

	str_init_buffer(&sendtargets, 0);

	sprintf(default_port, "%d", drec->port);
	/* resolve the DiscoveryAddress to an IP address */
	if (resolve_address(drec->address, default_port, &ss)) {
		log_error("cannot resolve host name %s", drec->address);
		rc = 1;
		goto free_sendtargets;
	}

	log_debug(4, "discovery timeouts: login %d, reopen_cnt %d, auth %d.",
		 session->conn[0].login_timeout, session->reopen_cnt,
		 session->conn[0].auth_timeout);

	/* setup authentication variables for the session*/
	rc = setup_authentication(session, drec, config);
	if (rc == 0) {
		rc = 1;
		goto free_sendtargets;
	}

set_address:
	/*
	 * copy the saved address to the session,
	 * undoing any temporary redirect
	 */
	session->conn[0].saddr = ss;

reconnect:

	if (--session->reopen_cnt < 0) {
		log_error("connection login retries (reopen_max %d) exceeded",
			  config->reopen_max);
		rc = 1;
		goto free_sendtargets;
	}

redirect_reconnect:

	iscsi_io_disconnect(&session->conn[0]);

	session->cmdsn = 1;
	session->itt = 1;
	session->portal_group_tag = PORTAL_GROUP_TAG_UNKNOWN;

	/* slowly back off the frequency of login attempts */
	if (login_failures == 0)
		login_delay = 0;
	else if (login_failures < 10)
		login_delay = 1;	/* 10 seconds at 1 sec each */
	else if (login_failures < 20)
		login_delay = 2;	/* 20 seconds at 2 sec each */
	else if (login_failures < 26)
		login_delay = 5;	/* 30 seconds at 5 sec each */
	else if (login_failures < 34)
		login_delay = 15;	/* 60 seconds at 15 sec each */
	else
		login_delay = 60;	/* after 2 minutes, try once a minute */

	if (login_delay) {
		log_debug(4, "discovery session to %s:%d sleeping for %d "
			 "seconds before next login attempt",
			 drec->address, drec->port, login_delay);
		sleep(login_delay);
	}

	getnameinfo((struct sockaddr *) &session->conn[0].saddr,
		    sizeof(session->conn[0].saddr), host,
		    sizeof(host), serv, sizeof(serv),
		    NI_NUMERICHOST|NI_NUMERICSERV);

	if (!iscsi_io_connect(&session->conn[0])) {
		log_error("connection to discovery address %s "
			  "failed", host);

		login_failures++;
		/* If a temporary redirect sent us to something unreachable,
		 * we want to go back to the original IP address, so make sure
		 * we reset the session's IP.
		 */
		goto set_address;
	}

	log_debug(1, "connected to discovery address %s", host);

	log_debug(4, "discovery session to %s:%d starting iSCSI login on fd %d",
		 drec->address, drec->port, session->conn[0].socket_fd);

	/* In case of discovery, we using socket's descriptor as ctrl. */
	session->ctrl_fd = session->conn[0].socket_fd;
	session->conn[0].session = session;

	status_class = 0;
	status_detail = 0;

	memset(data, 0, data_len);
	rc = iscsi_login(session, 0, data, data_len,
			 &status_class, &status_detail);

	switch (rc) {
	case LOGIN_OK:
	case LOGIN_REDIRECT:
		break;

	case LOGIN_IO_ERROR:
	case LOGIN_REDIRECTION_FAILED:
		/* try again */
		log_warning("retrying discovery login to %s", host);
		iscsi_io_disconnect(&session->conn[0]);
		login_failures++;
		goto set_address;

	default:
	case LOGIN_FAILED:
	case LOGIN_NEGOTIATION_FAILED:
	case LOGIN_AUTHENTICATION_FAILED:
	case LOGIN_VERSION_MISMATCH:
	case LOGIN_INVALID_PDU:
		log_error("discovery login to %s failed, giving up", host);
		iscsi_io_disconnect(&session->conn[0]);
		rc = 1;
		goto free_sendtargets;
	}

	/* check the login status */
	switch (status_class) {
	case ISCSI_STATUS_CLS_SUCCESS:
		log_debug(4, "discovery login success to %s", host);
		login_failures = 0;
		break;
	case ISCSI_STATUS_CLS_REDIRECT:
		switch (status_detail) {
			/* the session IP address was changed by the login
			 * library, so just try again with this portal
			 * config but the new address.
			 */
		case ISCSI_LOGIN_STATUS_TGT_MOVED_TEMP:
			log_warning(
				"discovery login temporarily redirected to "
				"%s port %s", host, serv);
			goto redirect_reconnect;
		case ISCSI_LOGIN_STATUS_TGT_MOVED_PERM:
			log_warning(
				"discovery login permanently redirected to "
				"%s port %s", host, serv);
			/* make the new address permanent */
			ss = session->conn[0].saddr;
			goto redirect_reconnect;
		default:
			log_error(
			       "discovery login rejected: redirection type "
			       "0x%x not supported",
			       status_detail);
			goto set_address;
		}
		break;
	case ISCSI_STATUS_CLS_INITIATOR_ERR:
		log_error(
			"discovery login to %s rejected: "
			"initiator error (%02x/%02x), non-retryable, giving up",
			host, status_class, status_detail);
		iscsi_io_disconnect(&session->conn[0]);
		rc = 1;
		goto free_sendtargets;
	case ISCSI_STATUS_CLS_TARGET_ERR:
		log_error(
			"discovery login to %s rejected: "
			"target error (%02x/%02x)",
			host, status_class, status_detail);
		iscsi_io_disconnect(&session->conn[0]);
		login_failures++;
		goto reconnect;
	default:
		log_error(
			"discovery login to %s failed, response "
			"with unknown status class 0x%x, detail 0x%x",
			host,
			status_class, status_detail);
		iscsi_io_disconnect(&session->conn[0]);
		login_failures++;
		goto reconnect;
	}

	/* reinitialize */
	str_truncate_buffer(&sendtargets, 0);

	/* ask for targets */
	if (!request_targets(session)) {
		goto reconnect;
	}
	active = 1;

	/* set timeouts */
	set_timer(&connection_timer, session->conn[0].active_timeout);

	/* prepare to poll */
	memset(&pfd, 0, sizeof (pfd));
	pfd.fd = session->conn[0].socket_fd;
	pfd.events = POLLIN | POLLPRI;

repoll:
	timeout = msecs_until(&connection_timer);
	/* block until we receive a PDU, a TCP FIN, a TCP RST,
	 * or a timeout
	 */
	log_debug(4,
		 "discovery process  %s:%d polling fd %d, "
		 "timeout in %f seconds",
		 drec->address, drec->port, pfd.fd,
		 timeout / 1000.0);

	pfd.revents = 0;
	rc = poll(&pfd, 1, timeout);

	log_debug(7,
		 "discovery process to %s:%d returned from poll, rc %d",
		 drec->address, drec->port, rc);

	if (timer_expired(&connection_timer)) {
		log_warning("discovery session to %s:%d session "
			    "logout, connection timer expired",
			    drec->address, drec->port);
			    iscsi_logout_and_disconnect(session);
		rc = 1;
		goto free_sendtargets;
	}

	if (rc > 0) {
		if (pfd.revents & (POLLIN | POLLPRI)) {
			timeout = msecs_until(&connection_timer);

			memset(data, 0, data_len);
			if (!iscsi_io_recv_pdu(&session->conn[0],
					       pdu, ISCSI_DIGEST_NONE, data,
			     		       data_len, ISCSI_DIGEST_NONE,
					       timeout)) {
				log_debug(1, "discovery session to "
					  "%s:%d failed to recv a PDU "
					  "response, terminating",
					   drec->address,
					   drec->port);
				iscsi_io_disconnect(&session->conn[0]);
				rc = 1;
				goto free_sendtargets;
			}

			/*
			 * process iSCSI PDU received
			 */
			rc = process_recvd_pdu(pdu, drec, rec_list,
					       session, &sendtargets,
					       default_port,
					       &active, &valid_text, data);
			if (rc == DISCOVERY_NEED_RECONNECT)
				goto reconnect;

			/* reset timers after receiving a PDU */
			if (active) {
				set_timer(&connection_timer,
				       session->conn[0].active_timeout);
				goto repoll;
			}
		}

		if (pfd.revents & POLLHUP) {
			log_warning("discovery session to %s:%d "
				    "terminating after hangup",
				     drec->address, drec->port);
			iscsi_io_disconnect(&session->conn[0]);
			rc = 1;
			goto free_sendtargets;
		}

		if (pfd.revents & POLLNVAL) {
			log_warning("discovery POLLNVAL");
			sleep(1);
			goto reconnect;
		}

		if (pfd.revents & POLLERR) {
			log_warning("discovery POLLERR");
			sleep(1);
			goto reconnect;
		}
	} else if (rc < 0) {
		if (errno == EINTR) {
			/* if we got SIGHUP, reconnect and rediscover */
			if (rediscover) {
				rediscover = 0;
				log_debug(1, "rediscovery requested");
				goto reconnect;
			}
		} else {
			log_error("poll error");
			rc = 1;
			goto free_sendtargets;
		}
	}

	log_debug(1, "discovery process to %s:%d exiting",
		 drec->address, drec->port);
	rc = 0;

free_sendtargets:
	str_free_buffer(&sendtargets);
	free(data);
free_session:
	free(session);
	return rc;
}

#ifdef SLP_ENABLE
int
slp_discovery(struct iscsi_slp_config *config)
{
	struct sigaction action;
	char *pl;
	unsigned short flag = 0;

	memset(&action, 0, sizeof (struct sigaction));
	action.sa_sigaction = NULL;
	action.sa_flags = 0;
	action.sa_handler = SIG_DFL;
	sigaction(SIGTERM, &action, NULL);
	sigaction(SIGINT, &action, NULL);
	sigaction(SIGPIPE, &action, NULL);

	action.sa_handler = sighup_handler;
	sigaction(SIGHUP, &action, NULL);

	if (iscsi_process_should_exit()) {
		log_debug(1, "slp discovery process %p exiting", discovery);
		exit(0);
	}

	discovery->pid = getpid();

	pl = generate_predicate_list(discovery, &flag);

	while (1) {
		if (flag == SLP_MULTICAST_ENABLED) {
			discovery->flag = SLP_MULTICAST_ENABLED;
			slp_multicast_srv_query(discovery, pl, GENERIC_QUERY);
		}

		if (flag == SLP_UNICAST_ENABLED) {
			discovery->flag = SLP_UNICAST_ENABLED;
			slp_unicast_srv_query(discovery, pl, GENERIC_QUERY);
		}

		sleep(config->poll_interval);
	}

	exit(0);
}

#endif