+ int fdflags;
+ int rc = -1;
+
+ become_session(IO->CitContext);
+
+ if (ReadFirst) {
+ IO->NextState = eReadMessage;
+ }
+ else {
+ IO->NextState = eSendReply;
+ }
+
+ IO->SendBuf.fd = IO->RecvBuf.fd =
+ socket(
+ (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
+ SOCK_STREAM,
+ IPPROTO_TCP);
+
+ if (IO->SendBuf.fd < 0) {
+ EV_syslog(LOG_ERR,
+ "EVENT: socket() failed: %s\n",
+ strerror(errno));
+
+ StrBufPrintf(IO->ErrMsg,
+ "Failed to create socket: %s",
+ strerror(errno));
+ return eAbort;
+ }
+ fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
+ if (fdflags < 0) {
+ EV_syslog(LOG_DEBUG,
+ "EVENT: unable to get socket flags! %s \n",
+ strerror(errno));
+ StrBufPrintf(IO->ErrMsg,
+ "Failed to get socket flags: %s",
+ strerror(errno));
+ return eAbort;
+ }
+ fdflags = fdflags | O_NONBLOCK;
+ if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
+ EV_syslog(
+ LOG_DEBUG,
+ "EVENT: unable to set socket nonblocking flags! %s \n",
+ strerror(errno));
+ StrBufPrintf(IO->ErrMsg,
+ "Failed to set socket flags: %s",
+ strerror(errno));
+ close(IO->SendBuf.fd);
+ IO->SendBuf.fd = IO->RecvBuf.fd = -1;
+ return eAbort;
+ }
+/* TODO: maye we could use offsetof() to calc the position of data...
+ * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
+ */
+ ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
+ IO->recv_event.data = IO;
+ ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
+ IO->send_event.data = IO;
+
+ ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
+ IO->conn_fail.data = IO;
+ ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout,0);
+ IO->rw_timeout.data = IO;
+
+
+ /* Bypass it like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
+/// ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr = inet_addr("127.0.0.1");
+ if (IO->ConnectMe->IPv6)
+ rc = connect(IO->SendBuf.fd,
+ &IO->ConnectMe->Addr,
+ sizeof(struct sockaddr_in6));
+ else
+ rc = connect(IO->SendBuf.fd,
+ (struct sockaddr_in *)&IO->ConnectMe->Addr,
+ sizeof(struct sockaddr_in));
+
+ if (rc >= 0){
+ EVM_syslog(LOG_DEBUG, "connect() immediate success.\n");
+ set_start_callback(event_base, IO, 0);
+ ev_timer_start(event_base, &IO->rw_timeout);
+ return IO->NextState;
+ }
+ else if (errno == EINPROGRESS) {
+ EVM_syslog(LOG_DEBUG, "connect() have to wait now.\n");
+
+ ev_io_init(&IO->conn_event,
+ IO_connestd_callback,
+ IO->SendBuf.fd,
+ EV_READ|EV_WRITE);
+
+ IO->conn_event.data = IO;
+
+ ev_io_start(event_base, &IO->conn_event);
+ ev_timer_start(event_base, &IO->conn_fail);
+ return IO->NextState;
+ }
+ else {
+ ev_idle_init(&IO->conn_fail_immediate,
+ IO_connfailimmediate_callback);
+ IO->conn_fail_immediate.data = IO;
+ ev_idle_start(event_base, &IO->conn_fail_immediate);
+
+ EV_syslog(LOG_ERR, "connect() failed: %s\n", strerror(errno));
+ StrBufPrintf(IO->ErrMsg,
+ "Failed to connect: %s",
+ strerror(errno));
+ return IO->NextState;
+ }
+ return IO->NextState;