This week’s arrival in Gaza of the Emir of Qatar and his entourage of fifty Mercedes revived the frenetic pace of activity in the coastal enclave, which has been uncommonly quiet in recent months. On his day-trip spent laying foundation stones for cities, hospitals, and schools all bearing his name, the Emir, Sheikh Hamad Al Thani, came pledging gifts of $400 million in reconstruction, and promised to end the political and economic isolation Gaza has endured since the Palestinian Islamist movement Hamas took power six years ago.

For Hamas leaders the trip, the first by a head of state since the siege on Gaza began, heralds their latest attempt to escape political pariahdom, after their hopes of deliverance by the new Muslim Brotherhood–led Egypt ran aground this summer. On August 5, sixteen Egyptian soldiers were gunned down by militants just across Gaza’s borders from Egypt; Egypt suspected the killers had crossed over from Gaza. Fearing the ire of its powerful neighbor, Hamas temporarily barred access to the border, including the vast tunnel complex connecting Gaza with Egypt that serves as Gaza’s economic lifeline. The trucks that cart thousands of tons of raw materials and fuel every day lay silent, and a few of the Gazan government officials and 9,000 tunnel workers who had bothered to make an appearance sat on stools disconsolately counting the lost revenue, which they estimated in the tens of millions of dollars.

The tunnels symbolize Hamas’s paradox: on the one hand, they have enabled Palestine’s main Islamist movement to thrive amid an external siege, and despite a Western boycott to take their place amongst the Islamist parties that have gained or strengthened their hold on power in many parts of the Middle East. Thanks to Gaza’s supply lines to Egypt, its GDP outpaced by a factor of five that of Hamas’s Western-funded rival, the Palestinian Authority (PA) in the West Bank. Further propelling Gaza’s economy, Arab governments across the region, like Qatar’s, have been shifting hundreds of millions of dollars in aid money from the PA to Hamas, signaling what may be a historic shift in Palestinian politics.

Yet the tunnels are also a reminder of just how much of a clandestine underground authority Hamas still is, and how fragile the territory’s recovery may be. Gaza continues to rely on smuggling for even basic goods, and the underground trade can be turned on and off as easily as a tap. The current restrictions, if they continue, could have devastating effects not only on the economy, but on Hamas’s own longevity. “We can’t keep ourselves imprisoned much longer,” a Hamas commander tells me as he and his patrol slouch bootless on mattresses under a makeshift tent erected between the tunnel mouths.

A testimony to human ingenuity and survival instinct, Gaza’s tunnel economy rapidly expanded after Hamas gained control of the territory in 2007. Western powers and the Mubarak government in Egypt saw the rise of Palestine’s Islamists as a national security threat and initially joined Israel’s siege of the enclave, which included a trade ban on all but eight basic goods. (“Why pasta?” protested an incredulous John Kerry when he visited after the largest of Israel’s recent invasions in January 2009.) The maritime blockade—still in force as Israel showed in mid-October, when it impounded another aid vessel—has prevented supplies getting in by sea.

Gazans responded by burrowing under their southern border into Egypt’s Sinai and digging several hundred tunnels, some large enough for vehicles to pass through. This network provides a conduit for goods (and people) not only to enter, but to exit: eggs, scrap metal, and even a shipment of three million carnations have all left Gaza through the tunnels. In the process, the tunnels have also helped Gaza rebuild itself. While international donors failed to deliver $4.5 billion in promised aid for reconstruction in protest at Hamas’s continued rule, tunnel operators have ferried in 7,500 tons of steel rods, cement, and gravel daily, supplying 90 percent of the enclave’s construction materials. According to World Bank figures, construction starts in the first half of 2011 grew by 220 percent.

The economic effects have been remarkable: after notching 6 percent growth in 2008, the Gazan economy grew by 20 percent in 2010 and a whopping 27 percent last year; unemployment in the formal economy fell to 29 percent, its lowest in a decade and an improvement of eight percentage points in a year. A recent International Labor Organization report cited the emergence of 600 “tunnel millionaires”; many of them, seeking somewhere to park their profits, have invested first in land, and then in hundreds of luxury apartment buildings. So great is the demand that Gazans complain builders have to be booked months in advance, and decorators are never available. The UN, which previously warned that Gaza faces an imminent humanitarian crisis, has now concluded that it may be years off: Gaza in 2020 was the title of its recent report.

Even when they are open for business, however, the tunnels have their downsides. Some two hundred workers have been killed, many of them children, who are preferred, as in Victorian mines, for their slight frames. Moreover, part of the tunnel complex lies inside Israel’s self-declared buffer zone, which Hamas forces say is beyond their reach. These tunnels double as portals for smugglers trafficking drugs and weapons, and may, as Cairo alleges, offer Sinai’s militants an escape hatch from Egyptian patrols. Above all, Hamas’s dependence on smuggling has underlined its continued illegitimacy in the eyes of much of the world.

So far, succor has come from Gaza’s wealthier neighbors. Irate that the billions they have been spoon-feeding the Palestinian Authority are serving to perpetuate Israel’s occupation of the West Bank rather than end it, Turkey and the Gulf powers have shifted funding southward. Turkey has contributed $300 million; Saudi Arabia $250 million. And at the end of the airstrip that Gaza’s former Jewish settlers built for themselves, a new town funded by the United Arab Emirates will provide spacious free housing for 11,000 Gazans rendered homeless by Israeli offensives. (The UN calls them “shelters” to avoid the impression that it is resettling refugees in suburban apartments.)

The Qatari government has gone even further. Not only has it donated fuel, which can bring Gaza’s power plant to full capacity—when Egypt lets it pass—and launched a $254 million modernization program. It also opened, this fall, a diplomatic mission in Gaza, which it consummated with the Emir’s October visit and the promise of an additional $150 million. (All of which has been much to the dismay of the Palestinian Authority in the West Bank. “Opening Gaza without the West Bank is the end of Palestine,” Tayib Abdel Rahim, perhaps the closest adviser to PA leader Mahmoud Abbas, told me recently. “Israel will increasingly treat Gaza as the Palestinian State, and turn the West Bank into its biblical Judea and Samaria.”)

The geyser of aid money has bought the new donors influence. The new Gaza offices of the IHH—the Islamist charity in Turkey that spearheaded the 2010 aid flotilla to Gaza intercepted by Israel—dominate Gaza City’s Katiba Square, newly grassed with turf hauled through the tunnels. The Islamic University has added Turkish to its curriculum. And at the site of the hospital it is building, Qatar has put up renderings of the future facility replete with palm trees and limousines, not withstanding the fact that incomes here are about a hundredth of those in Doha. Tellingly, for a country that is seeking to replace Iranian and Syrian patronage of Hamas, the signs depict Gazans wearing white Gulf Arab gowns. In full Gulf style, Hamas’s prime minister, Ismail Haniya, played host to the Qatari emir in an ornate Arab tent.

But Egypt remains the missing piece in Hamas’s regional jigsaw puzzle. With the triumph of the Muslim Brotherhood, Hamas’s ideological twin, the Gazan leadership anticipated a rapprochement, and on the night of Mohammed Morsi’s election victory, Hamas loyalists cheered in the streets. Hamas ministers prepared feasibility studies for a highway stretching from North Africa’s farthest reaches to Gaza, and appealed to Gulf labor markets to absorb Gaza’s jobless graduates. The Gaza-Egypt border crossing at Rafah “will open fully and Egypt will supply fuel, medicine, and electricity. No one will be refused entry,” mused Mahmoud al-Zahar, a veteran Hamas leader, as we sat in his garden in July on his return from a meeting with Morsi.

But after the initial welcome, Egypt backed off, swayed both by pressure from western powers negotiating an IMF package and by its security forces’ claims that Gaza was complicit in the August 5 attack. In late September, Prime Minister Haniya arrived in Cairo at the head of a twenty-man Gazan delegation only to find his anticipated audience with Morsi declined and his requests for upgrading ties rebuffed. Egypt, he discovered, remained noncommittal on the Qatari fuel it had blocked after the August 5 attack, on boosting Egypt’s supply of electricity and water to Gaza, and above all, on the launch of a free trade zone on the Gaza-Egypt border that would make Hamas a legitimate trading partner. In a further slight, the foreign ministry described Haniya as a visiting guest, not an official.

Passenger crossings between Gaza and Egypt at the main Rafah terminal, which had reached almost quarter of a million since the start of the year, fell back to levels of a year earlier. And at their common border, Egyptian bulldozers began digging up tunnels with a tenacity Morsi’s predecessor, Hosni Mubarak, had rarely shown. Tunnel traffic dwindled to a third of pre-August 5 levels: had it not been for a significant easing of Israel’s closures on Gaza the impact would have been intense. In a huff, Hamas removed the banner of a smiling Morsi and Haniya holding hands against the backdrop of the pyramids from the walls of its Gaza City parliament, and replaced it with a large portrait of Qatar’s Emir.

Still, Hamas leaders have been quick to appreciate that an attack on Egyptian forces so close to the Gaza border poses a serious threat to their hoped-for alliance with Egypt—not least, because Hamas has faced their own jihadi threat at home. In August 2009, following a spate of militant attacks on such symbols of decadence as Internet cafes, hairdressers, and Christian places of worship, Hamas laid siege to a jihadi mosque and killed its preacher Abdel Latif Moussa and more than twenty of his followers. The assault marked Hamas’s transition from grassroots guerrilla movement to member-in-waiting of the regional security order.

Having routed its jihadi opposition, Hamas backpedalled on its Islamist agenda and resistance against Israel and focused instead on accumulating and protecting its own assets. Its militants evolved into a defensive force, stationed near the border to prevent wildcat rocket fire against Israel and uphold a tahdiya, or calm. They have not always succeeded. Just as Hamas fighters once spoiled the calm by firing at Israel, when their nationalist rivals, Fatah, ruled Gaza, so now Hamas’s own militant rivals now scheme against them. No sooner had the Qatari emir completed his visit this week than Israel retaliated for the earlier maiming of one its soldiers with a series of air and tank strikes, including an attack on the Palestinian exit point into Israel. The following day, Palestinian militants fired eighty rockets and mortars at southern Israel, and Israeli aircraft struck Gaza four times. But although Hamas briefly joined the fray, it restricted its fire to short-range rockets away from civilian areas, and Israel for the moment seems to have refrained from further escalation.

Meanwhile, in Gaza itself, after three summers of zealous patrols, the morality police withdrew from the beaches and began to let shopkeepers again garb unveiled mannequins in mini-skirts. Hamas licensed and sometimes invested in upscale beach resorts along the coast; last year Palestine’s most luxurious hotel opened, replete with a cocktail bar that is somewhat hopefully awaiting an alcohol license.

In its rush to join the haves, Hamas began forgetting its former constituency of have-nots. Haniya’s government assigned only $14 million of its $769 million budget in 2012 to welfare. And for the first time shantytowns are cropping up on the outskirts of Gaza City. In the shanty next to an abattoir, the only meat homeless Gazans can afford for Islamic festivities is a crippled horse bought from a knacker’s yard, slaughtered in the sand outside their shacks and fried in discarded wheel-hubs.

On occasion discontent among the poor spills over. In late September in Bureij, a refugee camp of over 34,000 people on the outskirts of Gaza City, a three-year-old boy and his one-year-old sister burned to death by a fire started by the candle his family was using because of power cuts caused by Egypt’s interruption of fuel supplies through the tunnels. As an ambulance rushed the family to the hospital, hundreds of camp residents poured into the streets. “Down with Hamas,” they chanted, and then mocked them as “Shias,” because of their close ties with distant Iran. Hamas had to resort to its heavies with clubs to regain control of the camp.

The anti-Hamas protests are not yet a serious challenge to the Islamists’ six-year-old rule, but they suggest how much public perception of Gaza’s leaders may be changing. Once a bedrock of Hamas support, Bureij has wavered ever since Hamas preachers there promised residents sky-high rates of return from a pyramid scheme they set up to fund tunnel construction. It went bust, costing tens of thousands their savings. Predictably, the population rather than Hamas footed most of the bill.

If the frustration grows, what form might it take? At the entrance of the Bureij camp off the main road to Gaza lies a four-story unplastered apartment building, with a mosque called al-Mumineen, or The Faithful, on the ground floor. Above it, in a small square room, I found Abu Walid al-Maqdisi, a 43-year-old reputed to be Gaza’s leading mentor of global Jihad. His group Tawhid (Monotheism) and Jihad claims affiliation with al-Qaeda; Egypt suspects it had a hand in the killing of its soldiers. As it happens, Hamas had released al-Maqdisi from prison two days before the August attack.

My interview was awkward. Al-Maqdisi insisted that he was not under house arrest, but said that intelligence officers I had met on the staircase as I took off my shoes had warned him against speaking publicly. He was surrounded by a dozen acolytes, and my concentration kept wandering as I imagined better places to be than sitting shoulder-to-shoulder with a man whose followers had strangled a well-known Italian aid worker in Gaza a year ago in a failed bid to obtain their sheikh’s release. He was also the only person I spoke to in Gaza, however, who justified the killing of Egyptian soldiers. “If they were protecting Jews [across Egypt’s borders],” he told me, “it is permitted to kill them.” And if Hamas forces also prevented jihadi groups from targeting Jews? It was time for me to go.

On the night of October 12, just weeks after my interview, an Israeli drone killed al-Maqdisi and one of his followers, along with a passerby, on a motorbike in a refugee camp, threatening to precipitate another round of fighting. Tawhid and Jihad vowed to spur its efforts to convert Gaza into Islamic state, fire rockets at Israel, and launch attacks inside Sinai, prompting Egypt to put its troops in its south Sinai resorts on alert. Israel increased the pace of its drone attacks on Gaza’s Salafis. The killing also exposed the limits of Hamas’s pretensions to protect its population. Still, fearing that escalation might spoil the impending visit of the Qatari emir, Hamas held fire. According to Salafi groups in Gaza, instead of responding with rockets against Israel or even a statement of protest, Hamas arrested more of their militants and impounded their weapons.

Undoubtedly, Hamas would prefer an open relationship with Cairo. It says it will crack down on its Salafi militants and plug their conduits to Sinai. “More than anyone we seek relations above ground, not below it,” says Zahar, the Hamas leader who sees formal trade ties as the economic counterpart to political recognition. “Once that’s achieved, we will close the tunnels.” But Hamas leaders also flinch from the backlash that would likely come from cutting jihadi conduits, dissolving a business worth hundreds of millions, and joining Israel and Egypt’s anti-jihadi onslaught. Faced with Egyptian demands to crack down on jihadi groups it suspected of perpetrating the August 5 attack, Hamas declared that it had made dozens of arrests, but then quietly released most of the detainees after questioning. Struggling to reconcile both Egypt’s authorities and its own Salafists, Hamas’ leaders have appeared to sit on the fence, leaving both mistrustful of the Gazan leadership.

The protesters in Bureij show no sympathy for radical groups like Tawhid and Jihad; if anything they want a more liberal government. But as elsewhere, an enemy’s enemy can often become a friend. In neighboring Sinai, which has strong linguistic and cultural, as well as economic, affinities with Gaza, jihadi militants have proved adept at harnessing the grievances young Bedouin harbor against the Egyptian authorities. And in Gaza, itself, for all the dividends the government has reaped from the construction boom, the ranks of those left out offer fertile ground for recruits. Once an elite Palestinian militia, Islamic Jihad has acquired a substantial grassroots following, but has so far stopped short of rallying malcontents to openly challenge Hamas. While currently nursing their losses, smaller groups like al-Maqdisi’s, however, might feel less constrained.